如何使用 Boto 在 ENI 中添加或删除安全组?

How do I add or remove security groups from ENIs using Boto?

我正在使用 Boto Python 界面来管理我的 EC2 软件定义网络,并且我正在编写一种方法来管理弹性网络接口 (ENI) 上的安全组。

我不知道如何告诉 EC2 添加或删除安全组 to/from ENI。

到目前为止,我的方法基本上是:

import boto
conn = boto.connect_ec2()

my_eni = conn.get_all_network_interfaces(['eni-xxxx1234'])[0]
my_eni_groups = my_eni.groups
my_eni_sg_ids = [ x.id for x in my_eni_groups ]

desired_sg_state = ['sg-xxxx1234','sg-xxxx5678']

# if present, do nothing, else, add it somehow..
for sg in desired_sg_state:
    if sg in my_eni_sg_ids:
        print('Okay: ', sg)
    else:
        # not sure what method to use here!

我搜索了文档,但在 boto.ec2.securitygroupboto.ec2.networkinterface 对象中找不到任何关于 association/disassociation 安全组的信息。我确定有办法做到这一点,但对我来说并不明显。

相关操作是在 boto.ec2.connection level -- you can use modify_network_interface_attribute 更改弹性网络接口上的安全组:

import boto

sg_string_list = ['sg-xxxx1234', 'sg-xxxx5678']

conn = boto.connect_ec2()
conn.modify_network_interface_attribute(interface_id=eni_id,
                                        attr='groupSet',
                                        value=sg_string_list)

广义形式为: modify_network_interface_attribute(interface_id, attr, value, attachment_id=None, dry_run=False).

重要的是要记住,您指定的是您希望 ENI 处于 的状态,而不仅仅是 adding/removing SG 与 modify_network_interface_attribute称呼;如果你想要添加行为,首先获取当前 SG 列表,然后附加你的新 SG:

import boto
conn = boto.connect_ec2()

my_eni_groups = conn.get_all_network_interfaces(['eni-1582af5d'])[0].groups
my_eni_sg_ids = [ x.id for x in my_eni_groups ]

add_sg = 'sg-xxxx1234'

if add_sg not in my_eni_sg_ids:
    my_eni_sg_ids.append(add_sg)

    #only need to call this if we modified the list
    conn.modify_network_interface_attribute(interface_id=eni_id,
                                            attr='groupSet',
                                            value=my_eni_sg_ids)

EC2 documentation of the endpoint and Boto's parameters, so be sure to see the attribute option names in the Boto documentation or by visiting the source code 之间没有一对一的请求参数映射(请注意,您可能需要更改分支以匹配您的版本(以及可能的链接行号))。