Debian Codegraph @

ansible_collections/community/aws/plugins/modules/elb_instance.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: elb_instance
10 version_added: 1.0.0
11 short_description: De-registers or registers instances from EC2 ELBs
12 description:
13 - This module de-registers or registers an AWS EC2 instance from the ELBs
14 that it belongs to.
15 - Will be marked changed when called only if there are ELBs found to operate on.
16 author:
17 - "John Jarvis (@jarv)"
18 options:
19 state:
20 description:
21 - Register or deregister the instance.
22 required: true
23 choices: ['present', 'absent']
24 type: str
25 instance_id:
26 description:
27 - EC2 Instance ID.
28 required: true
29 type: str
30 ec2_elbs:
31 description:
32 - List of ELB names
33 - Required when I(state=present).
34 type: list
35 elements: str
36 enable_availability_zone:
37 description:
38 - Whether to enable the availability zone of the instance on the target ELB if the availability zone has not already
39 been enabled.
40 - If I(enable_availability_zone=no), the task will fail if the availability zone is not enabled on the ELB.
41 type: bool
42 default: true
43 wait:
44 description:
45 - Wait for instance registration or deregistration to complete successfully before returning.
46 type: bool
47 default: true
48 wait_timeout:
49 description:
50 - Number of seconds to wait for an instance to change state.
51 - If I(wait_timeout=0) then this module may return an error if a transient error occurs.
52 - If non-zero then any transient errors are ignored until the timeout is reached.
53 - Ignored when I(wait=no).
54 default: 0
55 type: int
56 notes:
57 - The ec2_elbs fact previously set by this module was deprecated in release 2.1.0 and since release
58 4.0.0 is no longer set.
59 extends_documentation_fragment:
60 - amazon.aws.common.modules
61 - amazon.aws.region.modules
62 - amazon.aws.boto3
63 """
64
65 EXAMPLES = r"""
66 # basic pre_task and post_task example
67 pre_tasks:
68 - name: Instance De-register
69 community.aws.elb_instance:
70 instance_id: "{{ ansible_ec2_instance_id }}"
71 state: absent
72 register: deregister_instances
73 delegate_to: localhost
74 roles:
75 - myrole
76 post_tasks:
77 - name: Instance Register
78 community.aws.elb_instance:
79 instance_id: "{{ ansible_ec2_instance_id }}"
80 ec2_elbs: "{{ deregister_instances.updated_elbs }}"
81 state: present
82 delegate_to: localhost
83 """
84
85 RETURN = r"""
86 updated_elbs:
87 description: A list of ELB names that the instance has been added to or removed from.
88 returned: always
89 type: list
90 elements: str
91 """
92
93 try:
94 import botocore
95 except ImportError:
96 pass # Handled by AnsibleAWSModule
97
98 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
99 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
100
101 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
102
103
104 class ElbManager:
105 """Handles EC2 instance ELB registration and de-registration"""
106
107 def __init__(self, module, instance_id=None, ec2_elbs=None):
108 retry_decorator = AWSRetry.jittered_backoff()
109 self.module = module
110 self.client_asg = module.client("autoscaling", retry_decorator=retry_decorator)
111 self.client_ec2 = module.client("ec2", retry_decorator=retry_decorator)
112 self.client_elb = module.client("elb", retry_decorator=retry_decorator)
113 self.instance_id = instance_id
114 self.lbs = self._get_instance_lbs(ec2_elbs)
115 self.changed = False
116 self.updated_elbs = set()
117
118 def deregister(self, wait, timeout):
119 """De-register the instance from all ELBs and wait for the ELB
120 to report it out-of-service"""
121
122 for lb in self.lbs:
123 instance_ids = [i["InstanceId"] for i in lb["Instances"]]
124 if self.instance_id not in instance_ids:
125 continue
126
127 self.updated_elbs.add(lb["LoadBalancerName"])
128
129 if self.module.check_mode:
130 self.changed = True
131 continue
132
133 try:
134 self.client_elb.deregister_instances_from_load_balancer(
135 aws_retry=True,
136 LoadBalancerName=lb["LoadBalancerName"],
137 Instances=[{"InstanceId": self.instance_id}],
138 )
139 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
140 self.module.fail_json_aws(
141 e, "Failed to deregister instance from load balancer", load_balancer=lb, instance=self.instance_id
142 )
143
144 # The ELB is changing state in some way. Either an instance that's
145 # InService is moving to OutOfService, or an instance that's
146 # already OutOfService is being deregistered.
147 self.changed = True
148
149 if wait:
150 for lb in self.lbs:
151 self._await_elb_instance_state(lb, "Deregistered", timeout)
152
153 def register(self, wait, enable_availability_zone, timeout):
154 """Register the instance for all ELBs and wait for the ELB
155 to report the instance in-service"""
156 for lb in self.lbs:
157 instance_ids = [i["InstanceId"] for i in lb["Instances"]]
158 if self.instance_id in instance_ids:
159 continue
160
161 self.updated_elbs.add(lb["LoadBalancerName"])
162
163 if enable_availability_zone:
164 self.changed |= self._enable_availailability_zone(lb)
165
166 if self.module.check_mode:
167 self.changed = True
168 continue
169
170 try:
171 self.client_elb.register_instances_with_load_balancer(
172 aws_retry=True,
173 LoadBalancerName=lb["LoadBalancerName"],
174 Instances=[{"InstanceId": self.instance_id}],
175 )
176 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
177 self.module.fail_json_aws(
178 e, "Failed to register instance with load balancer", load_balancer=lb, instance=self.instance_id
179 )
180
181 self.changed = True
182
183 if wait:
184 for lb in self.lbs:
185 self._await_elb_instance_state(lb, "InService", timeout)
186
187 @AWSRetry.jittered_backoff()
188 def _describe_elbs(self, **params):
189 paginator = self.client_elb.get_paginator("describe_load_balancers")
190 results = paginator.paginate(**params).build_full_result()
191 return results["LoadBalancerDescriptions"]
192
193 def exists(self, lbtest):
194 """Verify that the named ELB actually exists"""
195
196 found = False
197 for lb in self.lbs:
198 if lb["LoadBalancerName"] == lbtest:
199 found = True
200 break
201 return found
202
203 def _enable_availailability_zone(self, lb):
204 """Enable the current instance's availability zone in the provided lb.
205 Returns True if the zone was enabled or False if no change was made.
206 lb: load balancer"""
207 instance = self._get_instance()
208 desired_zone = instance["Placement"]["AvailabilityZone"]
209
210 if desired_zone in lb["AvailabilityZones"]:
211 return False
212
213 if self.module.check_mode:
214 return True
215
216 try:
217 self.client_elb.enable_availability_zones_for_load_balancer(
218 aws_retry=True,
219 LoadBalancerName=lb["LoadBalancerName"],
220 AvailabilityZones=[desired_zone],
221 )
222 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
223 self.module.fail_json_aws(e, "Failed to enable AZ on load balancers", load_balancer=lb, zone=desired_zone)
224
225 return True
226
227 def _await_elb_instance_state(self, lb, awaited_state, timeout):
228 """Wait for an ELB to change state"""
229 if self.module.check_mode:
230 return
231
232 initial_state = self._get_instance_health(lb)
233
234 if awaited_state == initial_state:
235 return
236
237 if awaited_state == "InService":
238 waiter = self.client_elb.get_waiter("instance_in_service")
239 elif awaited_state == "Deregistered":
240 waiter = self.client_elb.get_waiter("instance_deregistered")
241 elif awaited_state == "OutOfService":
242 waiter = self.client_elb.get_waiter("instance_deregistered")
243 else:
244 self.module.fail_json(msg="Could not wait for unknown state", awaited_state=awaited_state)
245
246 try:
247 waiter.wait(
248 LoadBalancerName=lb["LoadBalancerName"],
249 Instances=[{"InstanceId": self.instance_id}],
250 WaiterConfig={"Delay": 1, "MaxAttempts": timeout},
251 )
252 except botocore.exceptions.WaiterError as e:
253 self.module.fail_json_aws(
254 e, msg="Timeout waiting for instance to reach desired state", awaited_state=awaited_state
255 )
256 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
257 self.module.fail_json_aws(
258 e, msg="Error while waiting for instance to reach desired state", awaited_state=awaited_state
259 )
260
261 return
262
263 def _get_instance_health(self, lb):
264 """
265 Check instance health, should return status object or None under
266 certain error conditions.
267 """
268 try:
269 status = self.client_elb.describe_instance_health(
270 aws_retry=True,
271 LoadBalancerName=lb["LoadBalancerName"],
272 Instances=[{"InstanceId": self.instance_id}],
273 )["InstanceStates"]
274 except is_boto3_error_code("InvalidInstance"):
275 return None
276 except (
277 botocore.exceptions.ClientError,
278 botocore.exceptions.BotoCoreError,
279 ) as e: # pylint: disable=duplicate-except
280 self.module.fail_json_aws(e, msg="Failed to get instance health")
281
282 if not status:
283 return None
284
285 return status[0]["State"]
286
287 def _get_instance_lbs(self, ec2_elbs=None):
288 """Returns a list of ELBs attached to self.instance_id
289 ec2_elbs: an optional list of elb names that will be used
290 for elb lookup instead of returning what elbs
291 are attached to self.instance_id"""
292
293 list_params = dict()
294 if not ec2_elbs:
295 ec2_elbs = self._get_auto_scaling_group_lbs()
296
297 if ec2_elbs:
298 list_params["LoadBalancerNames"] = ec2_elbs
299
300 try:
301 elbs = self._describe_elbs(**list_params)
302 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
303 self.module.fail_json_aws(e, "Failed to describe load balancers")
304
305 if ec2_elbs:
306 return elbs
307
308 # If ec2_elbs wasn't specified, then filter out LBs we're not a member
309 # of.
310 lbs = []
311 for lb in elbs:
312 instance_ids = [i["InstanceId"] for i in lb["Instances"]]
313 if self.instance_id in instance_ids:
314 lbs.append(lb)
315
316 return lbs
317
318 def _get_auto_scaling_group_lbs(self):
319 """Returns a list of ELBs associated with self.instance_id
320 indirectly through its auto scaling group membership"""
321
322 try:
323 asg_instances = self.client_asg.describe_auto_scaling_instances(
324 aws_retry=True, InstanceIds=[self.instance_id]
325 )["AutoScalingInstances"]
326 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
327 self.module.fail_json_aws(e, msg="Failed to describe ASG Instance")
328
329 if len(asg_instances) > 1:
330 self.module.fail_json(msg="Illegal state, expected one auto scaling group instance.")
331
332 if not asg_instances:
333 # Instance isn't a member of an ASG
334 return []
335
336 asg_name = asg_instances[0]["AutoScalingGroupName"]
337
338 try:
339 asg_instances = self.client_asg.describe_auto_scaling_groups(
340 aws_retry=True, AutoScalingGroupNames=[asg_name]
341 )["AutoScalingGroups"]
342 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
343 self.module.fail_json_aws(e, msg="Failed to describe ASG Instance")
344
345 if len(asg_instances) != 1:
346 self.module.fail_json(msg="Illegal state, expected one auto scaling group.")
347
348 return asg_instances[0]["LoadBalancerNames"]
349
350 def _get_instance(self):
351 """Returns the description of an instance"""
352 try:
353 result = self.client_ec2.describe_instances(aws_retry=True, InstanceIds=[self.instance_id])
354 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
355 self.module.fail_json_aws(e, msg="Failed to describe ASG Instance")
356 return result["Reservations"][0]["Instances"][0]
357
358
359 def main():
360 argument_spec = dict(
361 state={"required": True, "choices": ["present", "absent"]},
362 instance_id={"required": True},
363 ec2_elbs={"default": None, "required": False, "type": "list", "elements": "str"},
364 enable_availability_zone={"default": True, "required": False, "type": "bool"},
365 wait={"required": False, "default": True, "type": "bool"},
366 wait_timeout={"required": False, "default": 0, "type": "int"},
367 )
368 required_if = [
369 ("state", "present", ["ec2_elbs"]),
370 ]
371
372 module = AnsibleAWSModule(
373 argument_spec=argument_spec,
374 required_if=required_if,
375 supports_check_mode=True,
376 )
377
378 ec2_elbs = module.params["ec2_elbs"]
379 wait = module.params["wait"]
380 enable_availability_zone = module.params["enable_availability_zone"]
381 timeout = module.params["wait_timeout"]
382 instance_id = module.params["instance_id"]
383
384 elb_man = ElbManager(module, instance_id, ec2_elbs)
385
386 if ec2_elbs is not None:
387 for elb in ec2_elbs:
388 if not elb_man.exists(elb):
389 module.fail_json(msg=f"ELB {elb} does not exist")
390
391 if module.params["state"] == "present":
392 elb_man.register(wait, enable_availability_zone, timeout)
393 elif module.params["state"] == "absent":
394 elb_man.deregister(wait, timeout)
395
396 module.exit_json(
397 changed=elb_man.changed,
398 updated_elbs=list(elb_man.updated_elbs),
399 )
400
401
402 if __name__ == "__main__":
403 main()