Created
March 23, 2016 17:44
-
-
Save AMeng/35cae10ab7fb1851c068 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import time | |
import os | |
from boto import utils, connect_ec2 | |
ELASTIC_IPS = os.environ['ELASTIC_IPS'].split(', ') | |
NUMBER_OF_TRIES = 5 | |
metadata = utils.get_instance_metadata() | |
instance_id = metadata['instance-id'] | |
connection = connect_ec2() | |
connection.get_all_instances(instance_ids=instance_id)[0].instances[0] | |
addresses = connection.get_all_addresses(addresses=ELASTIC_IPS) | |
for address in addresses: | |
if instance_id == address.instance_id: | |
print "Instance already associated with EIP {}.".format(address.public_ip) | |
exit(0) | |
for attempt in range(NUMBER_OF_TRIES): | |
""" | |
Try multiple times to associate each unused address from the list. Do | |
this incase multiple nodes try to use the same address at the same time. | |
""" | |
if attempt != 0: | |
print "Waiting 2 seconds before trying again..." | |
time.sleep(2) | |
unused_addresses = [a for a in addresses if not a.instance_id] | |
if not unused_addresses: | |
print "No unused EIP's found. Are there enough EIPs for the ASG?" | |
continue | |
for address in unused_addresses: | |
try: | |
print "Associating EIP {}".format(address.public_ip) | |
connection.associate_address(instance_id=instance_id, public_ip=None, allocation_id=address.allocation_id) | |
except Exception as e: | |
print "Failed to associate EIP {}. Error was:\n{}".format(address.public_ip, e) | |
continue | |
else: | |
print "Successfully associated EIP {}.".format(address.public_ip) | |
exit(0) | |
print "Failed to associate any EIP after {} tries".format(NUMBER_OF_TRIES) | |
exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment