BOTO3 -- 从 EC2 实例附加/分离安全组 [英] BOTO3 -- Attach / Detach Security Group from EC2 instance

查看:34
本文介绍了BOTO3 -- 从 EC2 实例附加/分离安全组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何解除特定安全组与所有 EC2 实例的关联,然后将其与新的 EC2 实例(BOTO3)相关联?

How can I go about disassociating a particular security group from all EC2 instances and then associate it with a new EC2 instance, with BOTO3?

我正在尝试类似的东西:

I'm trying something like:

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

感谢您的帮助!

推荐答案

  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]  # Get a list of ids of all securify groups attached to the instance
     if sg_id in all_sg_ids:                                          # Check the SG to be removed is in the list
       all_sg_ids.remove(sg_id)                                       # Remove the SG from the list
       instance.modify_attribute(Groups=all_sg_ids)                   # Attach the remaining SGs to the instance

这篇关于BOTO3 -- 从 EC2 实例附加/分离安全组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆