Refactoring of ec2_eip module.

This commit is contained in:
Robert Estelle 2014-11-13 23:05:49 -05:00
parent 17c1fa0872
commit c36e8947bc

View file

@ -100,114 +100,72 @@ try:
except ImportError: except ImportError:
HAS_BOTO = False HAS_BOTO = False
wait_timeout = 0
class EIPException(Exception):
pass
def associate_ip_and_instance(ec2, address, instance_id, module): def associate_ip_and_instance(ec2, address, instance_id, check_mode):
if ip_is_associated_with_instance( if address_is_associated_with_instance(ec2, address, instance_id):
ec2, address.public_ip, instance_id, module): return {'changed': False}
module.exit_json(changed=False, public_ip=address.public_ip)
# If we're in check mode, nothing else to do # If we're in check mode, nothing else to do
if module.check_mode: if not check_mode:
module.exit_json(changed=True)
try:
if address.domain == 'vpc': if address.domain == 'vpc':
res = ec2.associate_address(instance_id, res = ec2.associate_address(instance_id,
allocation_id=address.allocation_id) allocation_id=address.allocation_id)
else: else:
res = ec2.associate_address(instance_id, res = ec2.associate_address(instance_id,
public_ip=address.public_ip) public_ip=address.public_ip)
except boto.exception.EC2ResponseError, e: if not res:
module.fail_json(msg=str(e)) raise EIPException('association failed')
if res: return {'changed': True}
module.exit_json(changed=True, public_ip=address.public_ip)
module.fail_json(msg='association failed')
def disassociate_ip_and_instance(ec2, address, instance_id, module): def disassociate_ip_and_instance(ec2, address, instance_id, check_mode):
if not ip_is_associated_with_instance( if not address_is_associated_with_instance(ec2, address, instance_id):
ec2, address.public_ip, instance_id, module): return {'changed': False}
module.exit_json(changed=False, public_ip=address.public_ip)
# If we're in check mode, nothing else to do # If we're in check mode, nothing else to do
if module.check_mode: if not check_mode:
module.exit_json(changed=True) if address.domain == 'vpc':
try:
if address.domain == "vpc":
res = ec2.disassociate_address( res = ec2.disassociate_address(
association_id=address.association_id) association_id=address.association_id)
else: else:
res = ec2.disassociate_address(public_ip=address.public_ip) res = ec2.disassociate_address(public_ip=address.public_ip)
except boto.exception.EC2ResponseError, e:
module.fail_json(msg=str(e))
if res: if not res:
module.exit_json(changed=True) raise EIPException('disassociation failed')
else:
module.fail_json(msg="disassociation failed") return {'changed': True}
def find_address(ec2, public_ip, module, fail_on_not_found=True): def find_address(ec2, public_ip, wait_timeout):
""" Find an existing Elastic IP address """ """ Find an existing Elastic IP address """
if wait_timeout != 0: deadline = time.time() + wait_timeout
timeout = time.time() + wait_timeout while True:
while timeout > time.time():
try: try:
addresses = ec2.get_all_addresses([public_ip]) return ec2.get_all_addresses([public_ip])[0]
break except boto.exception.EC2ResponseError as e:
except boto.exception.EC2ResponseError, e: if "Address '{}' not found.".format(public_ip) not in e.message:
if "Address '%s' not found." % public_ip in e.message: raise
if not fail_on_not_found:
return None if time.time() >= deadline:
else: raise EIPException('wait for EIPs timeout on {}'
module.fail_json(msg=str(e.message)) .format(time.asctime()))
time.sleep(5) time.sleep(5)
if timeout <= time.time():
module.fail_json(msg="wait for EIPs timeout on %s" %
time.asctime())
else:
try:
addresses = ec2.get_all_addresses([public_ip])
except boto.exception.EC2ResponseError, e:
if "Address '%s' not found." % public_ip in e.message:
if not fail_on_not_found:
return None
module.fail_json(msg=str(e.message))
return addresses[0] def address_is_associated_with_instance(ec2, address, instance_id):
def ip_is_associated_with_instance(ec2, public_ip, instance_id, module):
""" Check if the elastic IP is currently associated with the instance """ """ Check if the elastic IP is currently associated with the instance """
address = find_address(ec2, public_ip, module)
if address: if address:
return address.instance_id == instance_id return address and address.instance_id == instance_id
return False return False
def instance_is_associated(ec2, instance, module): def allocate_address(ec2, domain, reuse_existing_ip_allowed):
"""
Check if the given instance object is already associated with an
elastic IP
"""
instance_ip = instance.ip_address
if not instance_ip:
return False
eip = find_address(ec2, instance_ip, module, fail_on_not_found=False)
return (eip and (eip.public_ip == instance_ip))
def allocate_address(ec2, domain, module, reuse_existing_ip_allowed):
""" Allocate a new elastic IP address (when needed) and return it """ """ Allocate a new elastic IP address (when needed) and return it """
# If we're in check mode, nothing else to do
if module.check_mode:
module.exit_json(change=True)
if reuse_existing_ip_allowed: if reuse_existing_ip_allowed:
domain_filter = {'domain': domain or 'standard'} domain_filter = {'domain': domain or 'standard'}
all_addresses = ec2.get_all_addresses(filters=domain_filter) all_addresses = ec2.get_all_addresses(filters=domain_filter)
@ -220,45 +178,67 @@ def allocate_address(ec2, domain, module, reuse_existing_ip_allowed):
return ec2.allocate_address(domain=domain) return ec2.allocate_address(domain=domain)
def release_address(ec2, public_ip, module): def release_address(ec2, address, check_mode):
""" Release a previously allocated elastic IP address """ """ Release a previously allocated elastic IP address """
address = find_address(ec2, public_ip, module)
# If we're in check mode, nothing else to do # If we're in check mode, nothing else to do
if module.check_mode: if not check_mode:
module.exit_json(change=True) if not address.release():
EIPException('release failed')
res = address.release() return {'changed': True}
if res:
module.exit_json(changed=True)
else:
module.fail_json(msg="release failed")
def find_instance(ec2, instance_id, module): def find_instance(ec2, instance_id):
""" Attempt to find the EC2 instance and return it """ """ Attempt to find the EC2 instance and return it """
try:
reservations = ec2.get_all_reservations(instance_ids=[instance_id]) reservations = ec2.get_all_reservations(instance_ids=[instance_id])
except boto.exception.EC2ResponseError, e:
module.fail_json(msg=str(e))
if len(reservations) == 1: if len(reservations) == 1:
instances = reservations[0].instances instances = reservations[0].instances
if len(instances) == 1: if len(instances) == 1:
return instances[0] return instances[0]
module.fail_json(msg="could not find instance" + instance_id) raise EIPException("could not find instance" + instance_id)
def allocate_eip(ec2, eip_domain, module, reuse_existing_ip_allowed, new_eip_timeout): def ensure_present(ec2, domain, address, instance_id,
# Allocate a new elastic IP reuse_existing_ip_allowed, check_mode):
address = allocate_address(ec2, eip_domain, module, reuse_existing_ip_allowed) changed = False
# overriding the timeout since this is a a newly provisioned ip
global wait_timeout # Return the EIP object since we've been given a public IP
wait_timeout = new_eip_timeout if not address:
return address if check_mode:
return {'changed': True}
address = allocate_address(ec2, domain, reuse_existing_ip_allowed)
changed = True
if instance_id:
# Allocate an IP for instance since no public_ip was provided
instance = find_instance(ec2, instance_id)
if instance.vpc_id:
domain = 'vpc'
# Associate address object (provided or allocated) with instance
assoc_result = associate_ip_and_instance(ec2, address, instance_id,
check_mode)
changed = changed or assoc_result['changed']
return {'changed': changed, 'public_ip': address.public_ip}
def ensure_absent(ec2, domain, address, check_mode):
if not address:
return {'changed': False}
# disassociating address from instance
if instance_id:
return disassociate_ip_and_instance(ec2, address, instance_id,
check_mode)
# releasing address
else:
return release_address(ec2, address, check_mode)
def main(): def main():
@ -290,48 +270,22 @@ def main():
in_vpc = module.params.get('in_vpc') in_vpc = module.params.get('in_vpc')
domain = 'vpc' if in_vpc else None domain = 'vpc' if in_vpc else None
reuse_existing_ip_allowed = module.params.get('reuse_existing_ip_allowed') reuse_existing_ip_allowed = module.params.get('reuse_existing_ip_allowed')
new_eip_timeout = int(module.params.get('wait_timeout')) wait_timeout = int(module.params.get('wait_timeout'))
try:
if public_ip:
address = find_address(ec2, public_ip, wait_timeout)
if state == 'present': if state == 'present':
# If both instance_id and public_ip are not specified, allocate a new result = ensure_present(ec2, domain, address, instance_id,
# elastic IP, and exit. reuse_existing_ip_allowed,
if not instance_id and not public_ip: module.check_mode)
address = allocate_eip(ec2, domain, module,
reuse_existing_ip_allowed, new_eip_timeout)
module.exit_json(changed=True, public_ip=address.public_ip)
# Return the EIP object since we've been given a public IP
if public_ip:
address = find_address(ec2, public_ip, module)
# Allocate an IP for instance since no public_ip was provided
if instance_id and not public_ip:
instance = find_instance(ec2, instance_id, module)
if instance.vpc_id:
domain = "vpc"
# Do nothing if the instance is already associated with an
# elastic IP.
if instance_is_associated(ec2, instance, module):
module.exit_json(changed=False, public_ip=instance.ip_address)
# If the instance is not already associated with an elastic IP,
# allocate a new one.
address = allocate_eip(
ec2, domain, module, reuse_existing_ip_allowed, new_eip_timeout)
# Associate address object (provided or allocated) with instance
associate_ip_and_instance(ec2, address, instance_id, module)
else: else:
# disassociating address from instance result = ensure_absent(ec2, domain, address, module.check_mode)
if instance_id: except (boto.exception.EC2ResponseError, EIPException) as e:
address = find_address(ec2, public_ip, module) module.fail_json(msg=str(e))
disassociate_ip_and_instance(ec2, address, instance_id, module)
# releasing address module.exit_json(**result)
else:
release_address(ec2, public_ip, module)
# import module snippets # import module snippets