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

san*_*nyi 19 python amazon-ec2 boto amazon-web-services

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

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

请求实例向导

如何实现该复选框功能boto

san*_*nyi 39

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

boto文档没有提供帮助,最近修复了相关的bug,请参阅: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
Run Code Online (Sandbox Code Playgroud)

  • 这样做的任何人都会收到此错误?`无法为具有ID的网络接口指定associatePublicIPAddress参数 (2认同)

bar*_*yku 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)
Run Code Online (Sandbox Code Playgroud)