2013-09-26 77 views
19

我必須在一個給定的子網中啓動ec2.run_instances新機器,但也有一個公共IP自動分配(不固定彈性IP)。如何使用博託自動分配公共IP到EC2實例

當通過請求實例(實例詳細信息)從亞馬遜的web EC2管理器啓動新機器時,會出現一個複選框將公共IP指定爲自動分配公共IP。 看到它的屏幕截圖強調:

Request Instance wizard

我怎樣才能實現與boto該複選框功能?

回答

38

有趣的是,似乎沒有多少人有這個問題。對我來說能夠做到這一點非常重要。如果沒有這種功能,則無法通過啓動到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 
+2

任何人在執行此操作時遇到此錯誤? '不能爲具有ID的網絡接口指定associatePublicIPAddress參數。' – qwwqwwq

+0

是的,顯然,如果您需要公共IP,則無法再創建接口。我會爲boto3添加一個反映這一點的答案。 [哦,等等,我不需要。見巴里庫的] –

0

從來沒有使用過此功能,但run_instances調用有一個參數network_interfaces。根據documentation你可以在那裏提供IP地址詳細信息。

+0

事實上,人們必須使用network_interfaces,但遺憾的是文檔沒有幫助,我最終讀了代碼和amazon ec2 API。 – sanyi

6

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) 
相關問題