如何使用boto自动将公共IP分配给EC2实例

时间:2013-09-26 13:24:44

标签: python amazon-web-services amazon-ec2 boto

我必须在给定的子网中启动一台ec2.run_instances的新机器,但也要自动分配公共IP(不是固定的弹性IP)。

当通过请求实例(实例详细信息)从Amazon的Web EC2 Manager启动新计算机时,会出现一个名为分配公共IP 的复选框以自动分配公共IP。 在屏幕截图中突出显示:

Request Instance wizard

如何使用boto实现该复选框功能?

3 个答案:

答案 0 :(得分:39)

有趣的是,似乎没有多少人遇到过这个问题。对我而言,能够做到这一点非常重要。如果没有此功能,则无法通过启动到nondefault subnet的实例与互联网联系。

boto文档没有提供任何帮助,最近修复了相关的错误,请参阅:https://github.com/boto/boto/pull/1705

值得注意的是,必须将subnet_id和安全groups提供给网络接口NetworkInterfaceSpecification,而不是run_instance

import time
import boto
import boto.ec2.networkinterface

from settings.settings import AWS_ACCESS_GENERIC

ec2 = boto.connect_ec2(*AWS_ACCESS_GENERIC)

interface = boto.ec2.networkinterface.NetworkInterfaceSpecification(subnet_id='subnet-11d02d71',
                                                                    groups=['sg-0365c56d'],
                                                                    associate_public_ip_address=True)
interfaces = boto.ec2.networkinterface.NetworkInterfaceCollection(interface)

reservation = ec2.run_instances(image_id='ami-a1074dc8',
                                instance_type='t1.micro',
                                #the following two arguments are provided in the network_interface
                                #instead at the global level !!
                                #'security_group_ids': ['sg-0365c56d'],
                                #'subnet_id': 'subnet-11d02d71',
                                network_interfaces=interfaces,
                                key_name='keyPairName')

instance = reservation.instances[0]
instance.update()
while instance.state == "pending":
    print instance, instance.state
    time.sleep(5)
    instance.update()

instance.add_tag("Name", "some name")

print "done", instance

答案 1 :(得分:7)

boto3具有可以为DeviceIndex = 0配置的NetworkInterfaces,而Subnet和SecurityGroupIds应该从实例级别移动到此块。这是我的工作版本,

def launch_instance(ami_id, name, type, size, ec2):
   rc = ec2.create_instances(
    ImageId=ami_id,
    MinCount=1,
    MaxCount=1,
    KeyName=key_name,
    InstanceType=size,
    NetworkInterfaces=[
        {
            'DeviceIndex': 0,
            'SubnetId': subnet,
            'AssociatePublicIpAddress': True,
            'Groups': sg
        },
    ]
   )

   instance_id = rc[0].id
   instance_name = name + '-' + type
   ec2.create_tags(
    Resources = [instance_id],
    Tags = [{'Key': 'Name', 'Value': instance_name}]
   )

   return (instance_id, instance_name)

答案 2 :(得分:0)

我自己从未使用此功能,但run_instances调用有一个名为network_interfaces的参数。根据{{​​3}},您可以在那里提供IP地址详细信息。