列出属于一个vpc的实例

时间:2018-08-16 11:35:25

标签: amazon-ec2 boto3

我正在尝试将某些安全组附加到某些ec2实例,但是我有多个vpc-s,并且我想将它们附加到属于特定vpc的实例。

我应该如何修改脚本以仅获取这些实例?

ec2 = boto3.resource('ec2')
instances = ec2.instances.filter()
for instance in instances:
   print(instance.id, instance.instance_type)
   all_sg_ids = [sg['GroupId'] for sg in instance.security_groups]
   if sg_id not in all_sg_ids: 
       all_sg_ids.append(sg_id)
       instance.modify_attribute(Groups=all_sg_ids)

1 个答案:

答案 0 :(得分:0)

与此同时,我找到了解决方案:

ec2 = boto3.resource('ec2')
vpc_id="vpc-0abcde1"
instances = instances = ec2.instances.filter(Filters=[{'Name': 'vpc-id', 'Values': [vpc_id]}])
for instance in instances:
    print(instance.id, instance.instance_type, instance.vpc_id)
    all_sg_ids = [sg['GroupId'] for sg in instance.security_groups]
    # for allsg in all_sg_ids:
    #   print (allsg)
    if sg_id not in all_sg_ids: 
        all_sg_ids.append(sg_id)
        instance.modify_attribute(Groups=all_sg_ids)