How to auto assign public ip to EC2 instance with boto

sanyi picture sanyi · Sep 26, 2013 · Viewed 11.8k times · Source

I have to start a new machine with ec2.run_instances in a given subnet but also to have a public ip auto assigned (not fixed elastic ip).

When one starts a new machine from the Amazon's web EC2 Manager via the Request Instance (Instance details) there is a check-box called Assign Public IP to Auto-assign Public IP. See it highlighted in the screenshot:

Request Instance wizard

How can I achieve that check-box functionality with boto?

Answer

sanyi picture sanyi · Sep 27, 2013

Interestingly enough, seems that not many people had this problem. For me was very important to be able to do this right. Without this functionality one is not able to reach out to the internet from instances that are launched into a nondefault subnet.

The boto documentation provided no help, there was a related bug recently fixed, see at: https://github.com/boto/boto/pull/1705.

It's important to note that the subnet_id and the security groups have to be provided to the network interface NetworkInterfaceSpecification instead of 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