We need associate EIP for five hundred EC2 instances。
If you hava five hundred EC2 instances:
#!/usr/bin/env python
from boto.exception import BotoServerError
import boto
import boto.ec2
class Aws_Ec2_API(object):
def __init__(self, region):
self.region = region
self.conn = boto.ec2.connect_to_region(self.region)
def allocate_eip(self, instanceid):
eip = self.conn.allocate_address()
print instanceid, eip.public_ip
self.conn.associate_address(instance_id=instanceid, public_ip=eip.public_ip)
def close(self):
self.conn.close()
if __name__ == "__main__":
c = Aws_Ec2_API('xx-north-1')
### read ec2 instances from file
ec2_list = open('instances.txt').read().strip().split(',')
#######associate eip for ec2
for ec2_id in bench_list:
ec.allocate_eip(ec2_id)
c.close()
else:
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
####
about article:
http://stackoverflow.com/questions/19029588/how-to-auto-assign-public-ip-to-ec2-instance-with-boto
http://boto.readthedocs.org/en/latest/ref/ec2.html#boto.ec2.address.Address.associate