【问题标题】:Attach / Detach Security Group from EC2 instance using boto3BOTO3 -- 从 EC2 实例附加/分离安全组
【发布时间】:2017-01-14 02:36:28
【问题描述】:

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

我正在尝试类似的东西:

      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 ???

感谢您的帮助!

【问题讨论】:

  • 建议标记所有安全组,并使用 describe_security_groups.filter 获取正确标记的security_group。

标签: amazon-web-services amazon-ec2 boto3


【解决方案1】:
  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

【讨论】:

  • 谢谢@helloV——我在上面的代码中有 modify_attribute。我难以理解的部分是,我需要什么逻辑来获取实例的当前组(可能分配了一些),然后只删除有问题的一个组,而让其他组保持连接。
  • @DrewOConnor 检查我的解决方案。在两者之间添加一个 print 语句(或在 Python shell 中运行它)以了解它是如何工作的。
猜你喜欢
  • 2021-05-29
  • 1970-01-01
  • 2019-09-18
  • 2020-08-25
  • 1970-01-01
  • 2019-02-09
  • 2018-07-31
  • 1970-01-01
  • 2020-07-20
相关资源
最近更新 更多