19

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

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

请求实例向导

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

4

3 回答 3

39

有趣的是,似乎没有多少人有这个问题。对我来说,能够正确地做到这一点非常重要。如果没有此功能,则无法从启动到nondefault subnet.

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

请务必注意,必须为网络接口提供subnet_id和安全性,而不是.groupsNetworkInterfaceSpecificationrun_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
于 2013-09-27T12:27:25.860 回答
8

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)
于 2016-06-16T19:53:48.740 回答
0

我自己从未使用过此功能,但该run_instances调用有一个名为network_interfaces. 根据文档,您可以在那里提供 IP 地址详细信息。

于 2013-09-26T13:55:44.050 回答