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

时间:2015-05-21 20:14:52

标签: python amazon-web-services boto

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

我不知道如何告诉EC2在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个对象中安全组关联/取消关联的任何信息。我确信有办法做到这一点,但这对我来说并不明显。

1 个答案:

答案 0 :(得分:4)

相关操作处于boto.ec2.connection级别 - 您可以使用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 位于的状态,而不是简单地通过modify_network_interface_attribute调用添加/删除SG ;如果你想要添加行为,首先获取当前的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 endpointBoto's parameters之间不存在请求参数的一对一映射,因此请务必在Boto文档中查看属性选项名称或{{ 3}}(请注意,您可能需要更改分支以匹配您的版本(可能还有链接的行号)。