boto3列出与ec2实例关联的安全组

时间:2019-04-30 02:21:09

标签: python amazon-ec2 boto3

是否可以用boto3列出与EC2实例关联的所有安全组?如果是这样,如何完成?

我尝试了以下方法,但是它们没有按照我想要的做:

for region in regions:
    client = boto3.client('ec2', region_name=region)
    try:
        payload = client.describe_security_groups(Filters=[{'Name': 'vpc-id', 'Values': ['vpc-*']}])
        for sg in payload["SecurityGroups"]:
            if sg["Description"] != "default VPC security group":
                resp = client.describe_security_group_references(DryRun=False, GroupId=[sg["GroupId"]])
                print resp

    except Exception as E:
        print region, E
        continue
for region in regions:
    client = boto3.client('ec2', region_name=region)
    try:
        payload = client.describe_security_groups(Filters=[{'Name': 'vpc-id', 'Values': ['vpc-*']}])
        for sg in payload["SecurityGroups"]:
            if sg["Description"] != "default VPC security group":
                sg = json.dumps(sg)
                pp(sg)
                # x = requests.post(url=sumocollector, data=sg)
                # print x.status_code

    except Exception as E:
        print region, E
        continue

1 个答案:

答案 0 :(得分:2)

如果要查找每个实例的SG列表,则可以改用describe_instances

for region in regions:
    client = boto3.client('ec2', region_name=region)
    try:
        response = client.describe_instances()
        for reservation in response['Reservations']:
            for instance in reservation['Instances']:
                print("Instance: " + instance['InstanceId'])
                for securityGroup in instance['SecurityGroups']:
                    print("SG ID: {}, Name: {}".format(securityGroup['GroupId'], securityGroup['GroupName']))

    except Exception as E:
        print(region, E)
        continue