我必须在一个给定的子网中启动ec2.run_instances
新机器,但也有一个公共IP自动分配(不固定弹性IP)。如何使用博托自动分配公共IP到EC2实例
当通过请求实例(实例详细信息)从亚马逊的web EC2管理器启动新机器时,会出现一个复选框将公共IP指定为自动分配公共IP。 看到它的屏幕截图强调:
我怎样才能实现与boto
该复选框功能?
我必须在一个给定的子网中启动ec2.run_instances
新机器,但也有一个公共IP自动分配(不固定弹性IP)。如何使用博托自动分配公共IP到EC2实例
当通过请求实例(实例详细信息)从亚马逊的web EC2管理器启动新机器时,会出现一个复选框将公共IP指定为自动分配公共IP。 看到它的屏幕截图强调:
我怎样才能实现与boto
该复选框功能?
有趣的是,似乎没有多少人有这个问题。对我来说能够做到这一点非常重要。如果没有这种功能,则无法通过启动到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_instances
调用有一个参数network_interfaces
。根据documentation你可以在那里提供IP地址详细信息。
事实上,人们必须使用network_interfaces,但遗憾的是文档没有帮助,我最终读了代码和amazon ec2 API。 – sanyi
boto3有您可以配置DeviceIndex = 0 NetworkInterfaces,以及子网和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)
任何人在执行此操作时遇到此错误? '不能为具有ID的网络接口指定associatePublicIPAddress参数。' – qwwqwwq
是的,显然,如果您需要公共IP,则无法再创建接口。我会为boto3添加一个反映这一点的答案。 [哦,等等,我不需要。见巴里库的] –