2013-04-30 03:40:17 +00:00
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = """
---
module: ec2_elb
2014-01-16 03:14:44 +00:00
short_description: De-registers or registers instances from EC2 ELBs
2013-04-30 03:40:17 +00:00
description:
2014-01-16 03:14:44 +00:00
- This module de-registers or registers an AWS EC2 instance from the ELBs
2013-04-30 03:40:17 +00:00
that it belongs to.
2013-05-03 10:55:06 +00:00
- Returns fact "ec2_elbs" which is a list of elbs attached to the instance
if state=absent is passed as an argument.
2013-04-30 13:03:31 +00:00
- Will be marked changed when called only if there are ELBs found to operate on.
2013-04-30 03:40:17 +00:00
version_added: "1.2"
author: John Jarvis
options:
2013-05-03 01:29:36 +00:00
state:
2013-04-30 03:40:17 +00:00
description:
- register or deregister the instance
required: true
2014-01-16 03:14:44 +00:00
choices: ['present', 'absent']
2013-04-30 03:40:17 +00:00
instance_id:
description:
- EC2 Instance ID
2013-04-30 13:00:10 +00:00
required: true
2013-05-03 01:29:36 +00:00
ec2_elbs:
2013-04-30 03:40:17 +00:00
description:
2013-05-03 10:55:06 +00:00
- List of ELB names, required for registration. The ec2_elbs fact should be used if there was a previous de-register.
2013-04-30 03:40:17 +00:00
required: false
default: None
2013-08-13 13:30:56 +00:00
region:
2013-08-01 20:50:01 +00:00
description:
2013-08-13 13:30:56 +00:00
- The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used.
2013-08-01 20:50:01 +00:00
required: false
2013-08-13 13:30:56 +00:00
aliases: ['aws_region', 'ec2_region']
2013-09-13 22:50:34 +00:00
enable_availability_zone:
description:
- Whether to enable the availability zone of the instance on the target ELB if the availability zone has not already
been enabled. If set to no, the task will fail if the availability zone is not enabled on the ELB.
required: false
default: yes
choices: [ "yes", "no" ]
2013-08-23 17:56:59 +00:00
wait:
description:
- Wait for instance registration or deregistration to complete successfully before returning.
required: false
default: yes
choices: [ "yes", "no" ]
2014-02-13 18:12:08 +00:00
validate_certs:
description:
- When set to "no", SSL certificates will not be validated for boto versions >= 2.6.0.
required: false
default: "yes"
choices: ["yes", "no"]
aliases: []
version_added: "1.5"
2014-02-14 20:16:58 +00:00
wait_timeout:
description:
- Number of seconds to wait for an instance to change state. If 0 then this module may return an error if a transient error occurs. If non-zero then any transient errors are ignored until the timeout is reached. Ignored when wait=no.
required: false
default: 0
2014-03-11 15:22:17 +00:00
version_added: "1.6"
2014-04-09 12:44:29 +00:00
extends_documentation_fragment: aws
2013-04-30 03:40:17 +00:00
"""
EXAMPLES = """
# basic pre_task and post_task example
pre_tasks:
- name: Gathering ec2 facts
ec2_facts:
- name: Instance De-register
local_action: ec2_elb
args:
instance_id: "{{ ansible_ec2_instance_id }}"
2013-05-03 01:29:36 +00:00
state: 'absent'
2013-04-30 03:40:17 +00:00
roles:
- myrole
post_tasks:
- name: Instance Register
local_action: ec2_elb
args:
instance_id: "{{ ansible_ec2_instance_id }}"
2013-09-03 21:13:25 +00:00
ec2_elbs: "{{ item }}"
2013-05-03 01:29:36 +00:00
state: 'present'
2013-09-03 21:13:25 +00:00
with_items: ec2_elbs
2013-04-30 03:40:17 +00:00
"""
import time
import sys
import os
try:
import boto
2013-09-13 22:50:34 +00:00
import boto.ec2
2013-08-01 20:50:01 +00:00
import boto.ec2.elb
from boto.regioninfo import RegionInfo
2013-04-30 03:40:17 +00:00
except ImportError:
print "failed=True msg='boto required for this module'"
sys.exit(1)
class ElbManager:
2013-04-30 13:00:10 +00:00
"""Handles EC2 instance ELB registration and de-registration"""
2013-04-30 03:40:17 +00:00
2013-05-03 01:29:36 +00:00
def __init__(self, module, instance_id=None, ec2_elbs=None,
2014-04-09 12:44:29 +00:00
region=None, **aws_connect_params):
2013-04-30 03:40:17 +00:00
self.module = module
self.instance_id = instance_id
2013-08-13 13:30:56 +00:00
self.region = region
2014-04-09 12:44:29 +00:00
self.aws_connect_params = aws_connect_params
2013-05-03 01:29:36 +00:00
self.lbs = self._get_instance_lbs(ec2_elbs)
2013-09-13 22:50:34 +00:00
self.changed = False
2013-04-30 03:40:17 +00:00
2014-02-14 20:16:58 +00:00
def deregister(self, wait, timeout):
2013-04-30 13:00:10 +00:00
"""De-register the instance from all ELBs and wait for the ELB
2013-04-30 03:40:17 +00:00
to report it out-of-service"""
for lb in self.lbs:
2013-12-12 21:09:40 +00:00
initial_state = self._get_instance_health(lb) if wait else None
2013-12-10 03:38:03 +00:00
if initial_state and initial_state.state == 'InService':
lb.deregister_instances([self.instance_id])
else:
return
2013-09-13 22:50:34 +00:00
if wait:
2014-02-14 20:16:58 +00:00
self._await_elb_instance_state(lb, 'OutOfService', initial_state, timeout)
2013-09-13 22:50:34 +00:00
else:
# We cannot assume no change was made if we don't wait
# to find out
self.changed = True
2013-04-30 03:40:17 +00:00
2014-02-14 20:16:58 +00:00
def register(self, wait, enable_availability_zone, timeout):
2013-04-30 03:40:17 +00:00
"""Register the instance for all ELBs and wait for the ELB
to report the instance in-service"""
for lb in self.lbs:
2014-03-30 04:47:11 +00:00
initial_state = self._get_instance_health(lb)
2013-12-10 03:38:03 +00:00
2013-09-13 22:50:34 +00:00
if enable_availability_zone:
self._enable_availailability_zone(lb)
2013-12-10 03:38:03 +00:00
2013-04-30 03:40:17 +00:00
lb.register_instances([self.instance_id])
2013-12-10 03:38:03 +00:00
2013-08-23 17:56:59 +00:00
if wait:
2014-02-14 20:16:58 +00:00
self._await_elb_instance_state(lb, 'InService', initial_state, timeout)
2013-09-13 22:50:34 +00:00
else:
# We cannot assume no change was made if we don't wait
# to find out
self.changed = True
2013-04-30 03:40:17 +00:00
2013-08-01 20:50:01 +00:00
def exists(self, lbtest):
""" Verify that the named ELB actually exists """
2013-12-10 03:38:03 +00:00
2013-08-01 20:50:01 +00:00
found = False
for lb in self.lbs:
if lb.name == lbtest:
found=True
break
return found
2013-09-13 22:50:34 +00:00
def _enable_availailability_zone(self, lb):
"""Enable the current instance's availability zone in the provided lb.
Returns True if the zone was enabled or False if no change was made.
lb: load balancer"""
instance = self._get_instance()
if instance.placement in lb.availability_zones:
return False
lb.enable_zones(zones=instance.placement)
# If successful, the new zone will have been added to
# lb.availability_zones
return instance.placement in lb.availability_zones
2013-08-01 20:50:01 +00:00
2014-02-14 20:16:58 +00:00
def _await_elb_instance_state(self, lb, awaited_state, initial_state, timeout):
2013-04-30 03:40:17 +00:00
"""Wait for an ELB to change state
lb: load balancer
awaited_state : state to poll for (string)"""
2014-02-14 20:16:58 +00:00
wait_timeout = time.time() + timeout
2013-04-30 03:40:17 +00:00
while True:
2013-12-10 03:38:03 +00:00
instance_state = self._get_instance_health(lb)
if not instance_state:
msg = ("The instance %s could not be put in service on %s."
" Reason: Invalid Instance")
self.module.fail_json(msg=msg % (self.instance_id, lb))
2013-09-13 22:50:34 +00:00
if instance_state.state == awaited_state:
# Check the current state agains the initial state, and only set
# changed if they are different.
2014-01-05 10:23:43 +00:00
if (initial_state is None) or (instance_state.state != initial_state.state):
2013-09-13 22:50:34 +00:00
self.changed = True
2013-04-30 03:40:17 +00:00
break
2013-12-10 03:38:03 +00:00
elif self._is_instance_state_pending(instance_state):
# If it's pending, we'll skip further checks andd continue waiting
pass
2013-09-13 22:50:34 +00:00
elif (awaited_state == 'InService'
2014-02-14 20:16:58 +00:00
and instance_state.reason_code == "Instance"
and time.time() >= wait_timeout):
2013-09-13 22:50:34 +00:00
# If the reason_code for the instance being out of service is
# "Instance" this indicates a failure state, e.g. the instance
# has failed a health check or the ELB does not have the
# instance's availabilty zone enabled. The exact reason why is
# described in InstantState.description.
msg = ("The instance %s could not be put in service on %s."
" Reason: %s")
self.module.fail_json(msg=msg % (self.instance_id,
lb,
instance_state.description))
2013-12-10 03:38:03 +00:00
time.sleep(1)
def _is_instance_state_pending(self, instance_state):
"""
Determines whether the instance_state is "pending", meaning there is
an operation under way to bring it in service.
"""
# This is messy, because AWS provides no way to distinguish between
# an instance that is is OutOfService because it's pending vs. OutOfService
# because it's failing health checks. So we're forced to analyze the
# description, which is likely to be brittle.
return (instance_state and 'pending' in instance_state.description)
def _get_instance_health(self, lb):
"""
Check instance health, should return status object or None under
certain error conditions.
"""
try:
status = lb.get_instance_health([self.instance_id])[0]
except boto.exception.BotoServerError, e:
if e.error_code == 'InvalidInstance':
return None
2013-04-30 03:40:17 +00:00
else:
2013-12-10 03:38:03 +00:00
raise
return status
2013-04-30 03:40:17 +00:00
2013-05-03 01:29:36 +00:00
def _get_instance_lbs(self, ec2_elbs=None):
2013-05-03 10:55:06 +00:00
"""Returns a list of ELBs attached to self.instance_id
ec2_elbs: an optional list of elb names that will be used
for elb lookup instead of returning what elbs
are attached to self.instance_id"""
2013-04-30 03:40:17 +00:00
try:
2014-04-09 12:44:29 +00:00
elb = connect_to_aws(boto.ec2.elb, self.region,
**self.aws_connect_params)
2013-04-30 03:40:17 +00:00
except boto.exception.NoAuthHandlerFound, e:
self.module.fail_json(msg=str(e))
2013-08-01 20:50:01 +00:00
2013-04-30 03:40:17 +00:00
elbs = elb.get_all_load_balancers()
2013-05-03 01:29:36 +00:00
if ec2_elbs:
lbs = sorted(lb for lb in elbs if lb.name in ec2_elbs)
2013-04-30 03:40:17 +00:00
else:
lbs = []
for lb in elbs:
for info in lb.instances:
if self.instance_id == info.id:
lbs.append(lb)
return lbs
2013-09-13 22:50:34 +00:00
def _get_instance(self):
"""Returns a boto.ec2.InstanceObject for self.instance_id"""
try:
2014-04-09 12:44:29 +00:00
ec2 = connect_to_aws(boto.ec2, self.region,
**self.aws_connect_params)
2013-09-13 22:50:34 +00:00
except boto.exception.NoAuthHandlerFound, e:
self.module.fail_json(msg=str(e))
2014-04-09 12:44:29 +00:00
return ec2.get_only_instances(instance_ids=[self.instance_id])[0]
2013-09-13 22:50:34 +00:00
2013-04-30 03:40:17 +00:00
def main():
2014-02-08 23:35:26 +00:00
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
2014-03-30 04:47:11 +00:00
state={'required': True},
2013-04-30 03:40:17 +00:00
instance_id={'required': True},
2013-08-23 17:56:59 +00:00
ec2_elbs={'default': None, 'required': False, 'type':'list'},
2014-03-28 15:41:35 +00:00
enable_availability_zone={'default': True, 'required': False, 'type': 'bool'},
wait={'required': False, 'default': True, 'type': 'bool'},
2014-02-14 20:16:58 +00:00
wait_timeout={'requred': False, 'default': 0, 'type': 'int'}
2013-04-30 03:40:17 +00:00
)
)
2014-02-08 23:35:26 +00:00
module = AnsibleModule(
argument_spec=argument_spec,
)
2014-04-09 12:44:29 +00:00
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if not region:
module.fail_json(msg="Region must be specified as a parameter, in EC2_REGION or AWS_REGION environment variables or in boto configuration file")
2013-11-01 15:59:24 +00:00
2013-05-03 01:29:36 +00:00
ec2_elbs = module.params['ec2_elbs']
2013-08-23 17:56:59 +00:00
wait = module.params['wait']
2013-09-13 22:50:34 +00:00
enable_availability_zone = module.params['enable_availability_zone']
2014-02-14 20:16:58 +00:00
timeout = module.params['wait_timeout']
2013-04-30 03:40:17 +00:00
2013-05-03 10:55:06 +00:00
if module.params['state'] == 'present' and 'ec2_elbs' not in module.params:
2013-04-30 03:40:17 +00:00
module.fail_json(msg="ELBs are required for registration")
instance_id = module.params['instance_id']
2014-04-09 12:44:29 +00:00
elb_man = ElbManager(module, instance_id, ec2_elbs,
region=region, **aws_connect_params)
2013-08-01 20:50:01 +00:00
2013-10-28 12:35:57 +00:00
if ec2_elbs is not None:
for elb in ec2_elbs:
if not elb_man.exists(elb):
msg="ELB %s does not exist" % elb
module.fail_json(msg=msg)
2013-04-30 03:40:17 +00:00
2013-05-03 10:55:06 +00:00
if module.params['state'] == 'present':
2014-02-14 20:16:58 +00:00
elb_man.register(wait, enable_availability_zone, timeout)
2013-05-03 10:55:06 +00:00
elif module.params['state'] == 'absent':
2014-02-14 20:16:58 +00:00
elb_man.deregister(wait, timeout)
2013-04-30 03:40:17 +00:00
ansible_facts = {'ec2_elbs': [lb.name for lb in elb_man.lbs]}
2013-04-30 13:00:10 +00:00
ec2_facts_result = dict(changed=elb_man.changed, ansible_facts=ansible_facts)
2013-04-30 03:40:17 +00:00
module.exit_json(**ec2_facts_result)
2013-11-01 15:59:24 +00:00
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
2013-04-30 03:40:17 +00:00
main()