尝试使用Python删除未使用的AWS安全组。获取错误“ec2.serviceresource”对象没有属性“delete\u securitygroup”

2024-05-19 12:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的代码。我不太确定最后一点该怎么办,我认为这是不对的。如何从变量“unused”中获取安全组ID的列表,并将其添加到boto3的“delete_security_group”调用中?在

谢谢

import boto3

ec2 = boto3.resource('ec2') 

sgs = list(ec2.security_groups.all())
insts = list(ec2.instances.all())

all_sgs = set([sg.group_id for sg in sgs])
all_inst_sgs = set([sg['GroupName'] for inst in insts for sg in inst.security_groups])
unused_sgs = all_sgs - all_inst_sgs

print("Total SGs:", len(all_sgs))
print("SGS attached to instances:", len(all_inst_sgs))
print("Orphaned SGs:", len(unused_sgs))
print('Unattached SG names:', unused_sgs)

for group_id in unused_sgs:
        ec2.delete_security_group(group_id)
print("Deleted Unused Groups")

Tags: inidforlenunusedgroupallsg
2条回答

海洛夫提供的答案是正确的。我必须更新delete_security_group命令才能使用客户机方法。我还不得不使用夸格斯来使它正常工作。 谢谢你的帮助。在

delete_security_group是一个客户端方法。在

ec2 = boto3.resource('ec2') 
client = boto3.client('ec2')

....
....
for group_id in unused_sgs:
  client.delete_security_group(GroupId=group_id)

相关问题 更多 >