Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/autoscaling_instance.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the Ansible project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 ---
11 module: autoscaling_instance
12 version_added: 9.0.0
13 short_description: manage instances associated with AWS AutoScaling Groups (ASGs)
14 description:
15 - Manage instances associated with AWS AutoScaling Groups (ASGs).
16 author:
17 - "Mark Chappell (@tremble)"
18 options:
19 group_name:
20 description:
21 - Name of the AutoScaling Group to manage.
22 type: str
23 required: True
24 state:
25 description:
26 - The expected state of the instances.
27 - V(present) - The instance(s) should be attached to the AutoScaling Group and in service.
28 - V(attached) - The instance(s) should be attached to the AutoScaling Group.
29 Instances in Standby will remain in standby.
30 - V(standby) - The instance(s) should be placed into standby.
31 Instances must already be part of the AutoScaling Group.
32 - V(detached) - The instance(s) will be detached from the AutoScaling Group.
33 - V(terminated) - The instance(s) will be terminated.
34 By default terminated instances will be replaced with new instances, to reduce the desired
35 capacity at the same time as terminating instances set O(decrement_desired_capacity=True).
36 - B(Note:) When adding instances to an AutoScaling Group or returning instances to service
37 from standby, the desired capacity is B(always) incremented. If the total number of
38 instances would exceed the maximum size of the group then the operation will fail.
39 choices: ['present', 'attached', 'terminated', 'detached', 'standby']
40 default: present
41 type: str
42 instance_ids:
43 description:
44 - The IDs of the EC2 instances.
45 - Required if O(state) is one of V(standby), V(detached), V(terminated).
46 type: list
47 elements: str
48 purge_instances:
49 description:
50 - Ignored unless O(state=present) or O(state=attached).
51 - If O(purge_instances=True), any instances not in O(instance_ids) will be scheduled for B(termination).
52 - B(Note:) Instances will be scheduled for termination B(after) any new instances are added to
53 the AutoScaling Group and, if O(wait=True) and they will be terminated B(after) the new instances
54 have reached the expected state.
55 default: false
56 type: bool
57 decrement_desired_capacity:
58 description:
59 - When O(decrement_desired_capacity=True), detaching instances, terminating instances, or
60 placing instances in standby mode will decrement the desired capacity of the AutoScaling Group
61 default: false
62 type: bool
63 health:
64 description:
65 - Sets the health of an instance to a specific state.
66 type: str
67 choices: ["Healthy", "Unhealthy"]
68 respect_grace_period:
69 description:
70 - Set O(respect_grace_period=False) to ignore the grace period associated with the AutoScaling
71 group when modifying the O(health).
72 - Ignored unless O(health) is set.
73 - AWS defaults to respecting the grace period when modifying the health state of an instance.
74 type: bool
75 default: True
76 protection:
77 description:
78 - Sets the scale-in protection attribute.
79 type: bool
80 wait:
81 description:
82 - When O(wait=True) will wait for instances to reach the requested state before returning.
83 type: bool
84 default: True
85 wait_timeout:
86 description:
87 - Maximum time to wait for instances to reach the desired state.
88 type: int
89 default: 120
90 extends_documentation_fragment:
91 - amazon.aws.common.modules
92 - amazon.aws.region.modules
93 - amazon.aws.boto3
94 """
95
96 EXAMPLES = r"""
97 """
98
99 RETURN = r"""
100 auto_scaling_instances:
101 description: A description of the EC2 instances attached to an Auto Scaling group.
102 returned: always
103 type: list
104 contains:
105 availability_zone:
106 description: The availability zone that the instance is in.
107 returned: always
108 type: str
109 sample: "us-east-1a"
110 health_status:
111 description: The last reported health status of the instance.
112 returned: always
113 type: str
114 sample: "Healthy"
115 instance_id:
116 description: The ID of the instance.
117 returned: always
118 type: str
119 sample: "i-123456789abcdef01"
120 instance_type:
121 description: The instance type of the instance.
122 returned: always
123 type: str
124 sample: "t3.micro"
125 launch_configuration_name:
126 description: The name of the launch configuration used when launching the instance.
127 returned: When the instance was launched using an Auto Scaling launch configuration.
128 type: str
129 sample: "ansible-test-49630214-mchappel-thinkpadt14gen3-asg-instance-1"
130 launch_template:
131 description: A description of the launch template used when launching the instance.
132 returned: When the instance was launched using an Auto Scaling launch template.
133 type: dict
134 contains:
135 launch_template_id:
136 description: The ID of the launch template used when launching the instance.
137 returned: always
138 type: str
139 sample: "12345678-abcd-ef12-2345-6789abcdef01"
140 launch_template_name:
141 description: The name of the launch template used when launching the instance.
142 returned: always
143 type: str
144 sample: "example-launch-configuration"
145 version:
146 description: The version of the launch template used when launching the instance.
147 returned: always
148 type: str
149 sample: "$Default"
150 lifecycle_state:
151 description: The lifecycle state of the instance.
152 returned: always
153 type: str
154 sample: "InService"
155 protected_from_scale_in:
156 description: Whether the instance is protected from termination when the Auto Scaling group is scaled in.
157 returned: always
158 type: bool
159 sample: false
160 """
161
162 import typing
163 from copy import deepcopy
164
165 from ansible_collections.amazon.aws.plugins.module_utils.autoscaling import WAITER_MAP
166 from ansible_collections.amazon.aws.plugins.module_utils.autoscaling import AnsibleAutoScalingError
167 from ansible_collections.amazon.aws.plugins.module_utils.autoscaling import AutoScalingErrorHandler
168 from ansible_collections.amazon.aws.plugins.module_utils.autoscaling import get_autoscaling_instances
169 from ansible_collections.amazon.aws.plugins.module_utils.autoscaling import get_autoscaling_waiter
170 from ansible_collections.amazon.aws.plugins.module_utils.errors import AnsibleAWSError
171 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
172 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
173 from ansible_collections.amazon.aws.plugins.module_utils.waiter import custom_waiter_config
174
175 if typing.TYPE_CHECKING:
176 from typing import Any
177 from typing import Dict
178 from typing import List
179 from typing import Optional
180 from typing import Set
181 from typing import Tuple
182
183 from ansible_collections.amazon.aws.plugins.module_utils.retries import RetryingBotoClientWrapper
184 from ansible_collections.amazon.aws.plugins.module_utils.transformations import AnsibleAWSResourceList
185
186
187 # There's also a number of "Warmed" states that we could support with relatively minimal effort, but
188 # we can't test them (currently)
189 STATE_MAP = {
190 "pending": ["Pending", "Pending:Proceed", "Pending:Wait"],
191 "stable": ["InService", "Standby"],
192 "entering": ["EnteringStandby"],
193 "entering+": ["EnteringStandby", "Standby"],
194 "detaching": ["Detaching"],
195 "detaching+": ["Detaching", "Detached"],
196 "terminating": ["Terminating", "Terminating:Wait", "Terminating:Proceed"],
197 "terminating+": ["Terminating", "Terminating:Wait", "Terminating:Proceed", "Terminated"],
198 }
199
200
201 def _all_instance_ids(instances: List) -> Set[str]:
202 return {i.get("instance_id") for i in instances}
203
204
205 def _instance_ids_with_health(instances: List, health: str) -> Set[str]:
206 health = health.lower()
207 return {i.get("instance_id") for i in instances if i.get("health_status", "").lower() == health}
208
209
210 def _instance_ids_with_protection(instances: List, protection: bool) -> Set[str]:
211 return {i.get("instance_id") for i in instances if i.get("protected_from_scale_in", False) == protection}
212
213
214 def _instance_ids_in_states(instances: List, states: List[str]) -> Set[str]:
215 states = [s.lower() for s in states]
216 return {i.get("instance_id") for i in instances if i.get("lifecycle_state", "").lower() in states}
217
218
219 def _token_instance(instance_id, group_name):
220 # Returns the minimum information we need for a new instance when adding a new node in check mode
221 return dict(
222 instance_id=instance_id,
223 auto_scaling_group_name=group_name,
224 health_status="Healthy",
225 )
226
227
228 @AutoScalingErrorHandler.common_error_handler("set instance health")
229 @AWSRetry.jittered_backoff()
230 def _set_instance_health(client: RetryingBotoClientWrapper, instance_id: str, health: str, respect_grace: bool):
231 return client.set_instance_health(
232 InstanceId=instance_id,
233 HealthStatus=health,
234 ShouldRespectGracePeriod=respect_grace,
235 )
236
237
238 @AutoScalingErrorHandler.common_error_handler("set instance protection")
239 @AWSRetry.jittered_backoff()
240 def _set_instance_protection(
241 client: RetryingBotoClientWrapper, instance_ids: Set[str], group_name: str, protected: bool
242 ):
243 return client.set_instance_protection(
244 InstanceIds=list(instance_ids),
245 AutoScalingGroupName=group_name,
246 ProtectedFromScaleIn=protected,
247 )
248
249
250 @AutoScalingErrorHandler.common_error_handler("detach auto scaling instances from group")
251 @AWSRetry.jittered_backoff()
252 def _detach_instances(
253 client: RetryingBotoClientWrapper, instance_ids: Set[str], group_name: str, decrement_capacity: bool
254 ):
255 return client.detach_instances(
256 InstanceIds=list(instance_ids),
257 AutoScalingGroupName=group_name,
258 ShouldDecrementDesiredCapacity=decrement_capacity,
259 )
260
261
262 @AutoScalingErrorHandler.common_error_handler("attach auto scaling instances to group")
263 @AWSRetry.jittered_backoff()
264 def _attach_instances(client: RetryingBotoClientWrapper, instance_ids: Set[str], group_name: str):
265 return client.attach_instances(
266 InstanceIds=list(instance_ids),
267 AutoScalingGroupName=group_name,
268 )
269
270
271 @AutoScalingErrorHandler.common_error_handler("terminate auto scaling instances")
272 @AWSRetry.jittered_backoff()
273 def _terminate_instances(client: RetryingBotoClientWrapper, instance_ids: Set[str], decrement_capacity: bool):
274 responses = []
275 for instance_id in instance_ids:
276 responses += client.terminate_instance_in_auto_scaling_group(
277 InstanceId=instance_id,
278 ShouldDecrementDesiredCapacity=decrement_capacity,
279 )
280 return responses
281
282
283 @AutoScalingErrorHandler.common_error_handler("place auto scaling instances into standby")
284 @AWSRetry.jittered_backoff()
285 def _enter_standby(
286 client: RetryingBotoClientWrapper, instance_ids: Set[str], group_name: str, decrement_capacity: bool
287 ):
288 return client.enter_standby(
289 InstanceIds=list(instance_ids),
290 AutoScalingGroupName=group_name,
291 ShouldDecrementDesiredCapacity=decrement_capacity,
292 )
293
294
295 @AutoScalingErrorHandler.common_error_handler("return auto scaling instances to group from standby")
296 @AWSRetry.jittered_backoff()
297 def _leave_standby(client: RetryingBotoClientWrapper, instance_ids: Set[str], group_name: str):
298 return client.exit_standby(
299 InstanceIds=list(instance_ids),
300 AutoScalingGroupName=group_name,
301 )
302
303
304 def wait_instance_state(
305 client: RetryingBotoClientWrapper,
306 state: str,
307 check_mode: bool,
308 group_name: str,
309 instance_ids: Set[str],
310 wait: bool,
311 wait_timeout: int,
312 ) -> None:
313 if not wait:
314 return
315 if check_mode:
316 return
317 if not instance_ids:
318 return
319
320 waiter_config = custom_waiter_config(timeout=wait_timeout, default_pause=10)
321
322 waiter = get_autoscaling_waiter(client, WAITER_MAP[state])
323 AutoScalingErrorHandler.common_error_handler(f"wait for instances to reach {state}")(waiter.wait)(
324 InstanceIds=list(instance_ids),
325 WaiterConfig=waiter_config,
326 )
327
328 return
329
330
331 def _inject_instances(instances, group_name, missing_ids):
332 if not missing_ids:
333 return instances
334 for instance in list(missing_ids):
335 instances.append(_token_instance(instance, group_name))
336 instances = sorted(instances, key=lambda d: d.get("instance_id", None))
337 return instances
338
339
340 def _change_instances(instances, group_name, change_ids, state=None, health=None, protection=None):
341 for instance in instances:
342 if instance.get("instance_id") in change_ids:
343 if state is not None:
344 instance["lifecycle_state"] = state
345 if health is not None:
346 instance["health_status"] = health
347 if protection is not None:
348 instance["protected_from_scale_in"] = protection
349 return instances
350
351
352 def ensure_instance_terminated(
353 client: RetryingBotoClientWrapper,
354 check_mode: bool,
355 instances_start: AnsibleAWSResourceList,
356 group_name: str,
357 instance_ids: List[str],
358 decrement_desired_capacity: bool,
359 wait: bool,
360 wait_timeout: int,
361 ) -> Tuple[bool, AnsibleAWSResourceList]:
362 instance_ids = set(instance_ids)
363
364 # We don't need to change these instances, we may need to wait for them
365 terminating_ids = _instance_ids_in_states(instances_start, STATE_MAP["terminating+"]) & instance_ids
366
367 # We'll need to wait for the in-progress changes to complete
368 detaching_ids = _instance_ids_in_states(instances_start, STATE_MAP["detaching"]) & instance_ids
369 pending_ids = _instance_ids_in_states(instances_start, STATE_MAP["pending"]) & instance_ids
370 entering_ids = _instance_ids_in_states(instances_start, STATE_MAP["entering"]) & instance_ids
371 # These instances are ready to terminate
372 ready_ids = _instance_ids_in_states(instances_start, STATE_MAP["stable"]) & instance_ids
373
374 if check_mode:
375 change_ids = detaching_ids | pending_ids | entering_ids | ready_ids | terminating_ids
376 instances_changed = _change_instances(deepcopy(instances_start), group_name, change_ids, state="Terminated")
377 return bool(change_ids - terminating_ids), instances_changed
378
379 # We have to wait for instances to transition to their stable states before changing them
380 if entering_ids:
381 wait_instance_state(client, "Standby", check_mode, group_name, entering_ids, wait, wait_timeout)
382 if pending_ids:
383 wait_instance_state(client, "InService", check_mode, group_name, pending_ids, wait, wait_timeout)
384 ready_ids |= entering_ids | pending_ids
385
386 if ready_ids:
387 _terminate_instances(client, ready_ids, decrement_desired_capacity)
388
389 terminating_ids |= ready_ids
390 wait_instance_state(client, "Terminated", check_mode, group_name, terminating_ids, wait, wait_timeout)
391
392 instances_complete = get_autoscaling_instances(client, group_name=group_name)
393 return bool(ready_ids), instances_complete
394
395
396 def ensure_instance_absent(
397 client: RetryingBotoClientWrapper,
398 check_mode: bool,
399 instances_start: AnsibleAWSResourceList,
400 group_name: str,
401 instance_ids: List[str],
402 decrement_desired_capacity: bool,
403 wait: bool,
404 wait_timeout: int,
405 ) -> Tuple[bool, AnsibleAWSResourceList]:
406 instance_ids = set(instance_ids)
407
408 # We don't need to change these instances, we may need to wait for them
409 detaching_ids = _instance_ids_in_states(instances_start, STATE_MAP["detaching+"]) & instance_ids
410 # On the basis of "be conservative in what you do, be liberal in what you accept from others"
411 # We'll treat instances that someone else has terminated, as "detached" from the ASG, since
412 # they won't be attached to the ASG.
413 terminating_ids = _instance_ids_in_states(instances_start, STATE_MAP["terminating+"]) & instance_ids
414
415 # We'll need to wait for the in-progress changes to complete
416 pending_ids = _instance_ids_in_states(instances_start, STATE_MAP["pending"]) & instance_ids
417 entering_ids = _instance_ids_in_states(instances_start, STATE_MAP["entering"]) & instance_ids
418 # These instances are ready to detach
419 ready_ids = _instance_ids_in_states(instances_start, STATE_MAP["stable"]) & instance_ids
420
421 if check_mode:
422 change_ids = pending_ids | entering_ids | ready_ids | detaching_ids
423 instances_changed = _change_instances(deepcopy(instances_start), group_name, change_ids, state="Detached")
424 return bool(change_ids - detaching_ids), instances_changed
425
426 # We have to wait for instances to transition to their stable state before changing them
427 if entering_ids:
428 wait_instance_state(client, "Standby", check_mode, group_name, entering_ids, wait, wait_timeout)
429 if pending_ids:
430 wait_instance_state(client, "InService", check_mode, group_name, pending_ids, wait, wait_timeout)
431
432 ready_ids |= entering_ids | pending_ids
433 if ready_ids:
434 _detach_instances(client, ready_ids, group_name, decrement_desired_capacity)
435 detaching_ids |= ready_ids
436
437 if terminating_ids:
438 wait_instance_state(client, "Terminated", check_mode, group_name, terminating_ids, wait, wait_timeout)
439 if detaching_ids:
440 wait_instance_state(client, "Detached", check_mode, group_name, detaching_ids, wait, wait_timeout)
441
442 instances_complete = get_autoscaling_instances(client, group_name=group_name)
443 return bool(ready_ids), instances_complete
444
445
446 def ensure_instance_attached(
447 client: RetryingBotoClientWrapper,
448 check_mode: bool,
449 instances_start: AnsibleAWSResourceList,
450 group_name: str,
451 instance_ids: List[str],
452 decrement_desired_capacity: bool,
453 purge: bool,
454 wait: bool,
455 wait_timeout: int,
456 ) -> Tuple[bool, AnsibleAWSResourceList]:
457 instance_ids = set(instance_ids)
458 all_ids = _all_instance_ids(instances_start)
459
460 # These instances need to be attached
461 missing_ids = instance_ids - all_ids
462 missing_ids |= _instance_ids_in_states(instances_start, ["Detached"]) & instance_ids
463 detaching_ids = _instance_ids_in_states(instances_start, STATE_MAP["detaching"]) & instance_ids
464 pending_ids = _instance_ids_in_states(instances_start, STATE_MAP["pending"]) & instance_ids
465 terminating_ids = _instance_ids_in_states(instances_start, STATE_MAP["terminating+"]) & instance_ids
466 # Ids that need to be removed
467 purge_ids = (all_ids - instance_ids) if purge else set()
468
469 if check_mode:
470 instances_changed = _inject_instances(deepcopy(instances_start), group_name, missing_ids)
471 missing_ids |= detaching_ids
472 instances_changed = _change_instances(instances_changed, group_name, missing_ids, state="InService")
473 instances_changed = _change_instances(instances_changed, group_name, purge_ids, state="Terminated")
474 return bool(missing_ids | purge_ids), instances_changed
475
476 if detaching_ids:
477 # We have to wait for instances to transition to Detached before we can re-attach them
478 wait_instance_state(client, "Detached", check_mode, group_name, detaching_ids, wait, wait_timeout)
479 missing_ids |= detaching_ids
480
481 if missing_ids:
482 _attach_instances(client, missing_ids, group_name)
483 pending_ids |= missing_ids
484
485 # This includes potentially waiting for instances which were Pending when we started
486 wait_instance_state(client, "InService", check_mode, group_name, pending_ids, wait, wait_timeout)
487
488 # While, in theory, we could make the ordering of Add/Remove configurable, the logic becomes
489 # difficult to test. As such we're going to hard code the order of operations.
490 # Add/Wait/Terminate is the order least likely to result in 0 available
491 # instances, so we do any termination after ensuring instances are InService.
492 if purge_ids:
493 _terminate_instances(client, purge_ids, decrement_desired_capacity)
494 terminating_ids |= purge_ids
495 wait_instance_state(client, "Terminated", check_mode, group_name, terminating_ids, wait, wait_timeout)
496
497 instances_complete = get_autoscaling_instances(client, group_name=group_name)
498 return bool(purge_ids | missing_ids), instances_complete
499
500
501 def ensure_instance_present(
502 client: RetryingBotoClientWrapper,
503 check_mode: bool,
504 instances_start: AnsibleAWSResourceList,
505 group_name: str,
506 instance_ids: List[str],
507 decrement_desired_capacity: bool,
508 purge: bool,
509 wait: bool,
510 wait_timeout: int,
511 ) -> Tuple[bool, AnsibleAWSResourceList]:
512 instance_ids = set(instance_ids)
513 all_ids = _all_instance_ids(instances_start)
514
515 # We just need to wait for these
516 pending_ids = _instance_ids_in_states(instances_start, STATE_MAP["pending"]) & instance_ids
517 # We need to wait for these before we can attach/re-activate them
518 detaching_ids = _instance_ids_in_states(instances_start, STATE_MAP["detaching+"]) & instance_ids
519 entering_ids = _instance_ids_in_states(instances_start, STATE_MAP["entering"]) & instance_ids
520 # These instances need to be brought out of standby
521 standby_ids = _instance_ids_in_states(instances_start, ["Standby"]) & instance_ids
522 # These instances need to be attached
523 missing_ids = instance_ids - all_ids
524
525 # Ids that need to be removed
526 purge_ids = (all_ids - instance_ids) if purge else set()
527
528 if check_mode:
529 change_ids = detaching_ids | entering_ids | standby_ids | missing_ids
530 instances_changed = _inject_instances(deepcopy(instances_start), group_name, missing_ids)
531 instances_changed = _change_instances(
532 instances_changed, group_name, change_ids | pending_ids, state="InService"
533 )
534 instances_changed = _change_instances(instances_changed, group_name, purge_ids, state="Terminated")
535 return bool(change_ids | purge_ids), instances_changed
536
537 if detaching_ids:
538 wait_instance_state(client, "Detached", check_mode, group_name, detaching_ids, wait, wait_timeout)
539 missing_ids |= detaching_ids - purge_ids
540 # They've left the ASG of their own accord, we'll leave them be...
541 purge_ids = purge_ids - detaching_ids
542
543 if missing_ids:
544 _attach_instances(client, missing_ids, group_name)
545
546 if entering_ids:
547 wait_instance_state(client, "Standby", check_mode, group_name, entering_ids, wait, wait_timeout)
548 standby_ids |= entering_ids - purge_ids
549
550 if standby_ids:
551 _leave_standby(client, standby_ids, group_name)
552
553 # This includes potentially waiting for instances which were Pending when we started
554 wait_instance_state(client, "InService", check_mode, group_name, instance_ids, wait, wait_timeout)
555
556 # While, in theory, we could make the ordering of Add/Remove configurable, the logic becomes
557 # difficult to test. As such we're going to hard code the order of operations.
558 # Add/Wait/Terminate is the order least likely to result in 0 available
559 # instances, so we do any termination after ensuring instances are InService.
560 if purge_ids:
561 _terminate_instances(client, purge_ids, decrement_desired_capacity)
562 wait_instance_state(client, "Terminated", check_mode, group_name, detaching_ids, wait, wait_timeout)
563
564 instances_complete = get_autoscaling_instances(client, group_name=group_name)
565 return bool(purge_ids | standby_ids | missing_ids), instances_complete
566
567
568 def ensure_instance_standby(
569 client: RetryingBotoClientWrapper,
570 check_mode: bool,
571 instances_start: AnsibleAWSResourceList,
572 group_name: str,
573 instance_ids: List[str],
574 decrement_desired_capacity: bool,
575 wait: bool,
576 wait_timeout: int,
577 ) -> Tuple[bool, AnsibleAWSResourceList]:
578 instance_ids = set(instance_ids)
579
580 # We need to wait for these instances to enter "InService" before we can do anything with them
581 pending_ids = _instance_ids_in_states(instances_start, STATE_MAP["pending"]) & instance_ids
582 # These instances are ready to move to Standby
583 ready_ids = _instance_ids_in_states(instances_start, ["InService"]) & instance_ids
584 # These instances are moving into Standby
585 entering_ids = _instance_ids_in_states(instances_start, STATE_MAP["entering"]) & instance_ids
586
587 if check_mode:
588 change_ids = pending_ids | ready_ids
589 instances_changed = _change_instances(deepcopy(instances_start), group_name, change_ids, state="Standby")
590 return bool(ready_ids), instances_changed
591
592 if pending_ids:
593 # We have to wait for instances to transition to InService
594 wait_instance_state(client, "InService", check_mode, group_name, pending_ids, wait, wait_timeout)
595 ready_ids |= pending_ids
596
597 if ready_ids:
598 _enter_standby(client, ready_ids, group_name, decrement_desired_capacity)
599 entering_ids |= ready_ids
600
601 # This includes potentially waiting for instances which were "Entering" Standby when we started
602 wait_instance_state(client, "Standby", check_mode, group_name, entering_ids, wait, wait_timeout)
603
604 instances_complete = get_autoscaling_instances(client, group_name=group_name)
605 return bool(ready_ids), instances_complete
606
607
608 def ensure_instance_health(
609 client: RetryingBotoClientWrapper,
610 check_mode: bool,
611 instances_start: AnsibleAWSResourceList,
612 group_name: str,
613 health: Optional[str],
614 instance_ids: List[str],
615 respect_grace_period: bool,
616 wait: bool,
617 wait_timeout: int,
618 ) -> Tuple[bool, AnsibleAWSResourceList]:
619 # nb. With Health the API documentation's inconsistent:
620 # it appears to want Capitalized for set(), but spits out UPPERCASE for get()
621 if health is None:
622 return False, instances_start
623 if instance_ids is None:
624 instance_ids = _all_instance_ids(instances_start)
625 else:
626 instance_ids = set(instance_ids)
627
628 ready_ids = _instance_ids_with_health(instances_start, health) & instance_ids
629 changed_ids = instance_ids - ready_ids
630
631 if not changed_ids:
632 return False, instances_start
633
634 if check_mode:
635 health = health.upper()
636 changed_instances = _change_instances(deepcopy(instances_start), group_name, changed_ids, health=health)
637 return True, changed_instances
638
639 for instance_id in changed_ids:
640 _set_instance_health(client, instance_id, health, respect_grace_period)
641 health = health.upper()
642 wait_instance_state(client, health.upper(), check_mode, group_name, changed_ids, wait, wait_timeout)
643
644 instances_complete = get_autoscaling_instances(client, group_name=group_name)
645 return True, instances_complete
646
647
648 def ensure_instance_protection(
649 client: RetryingBotoClientWrapper,
650 check_mode: bool,
651 instances_start: AnsibleAWSResourceList,
652 group_name: str,
653 protection: Optional[bool],
654 instance_ids: List[str],
655 wait: bool,
656 wait_timeout: int,
657 ) -> Tuple[bool, AnsibleAWSResourceList]:
658 if protection is None:
659 return False, instances_start
660 if instance_ids is None:
661 instance_ids = _all_instance_ids(instances_start)
662 else:
663 instance_ids = set(instance_ids)
664
665 ready_ids = _instance_ids_with_protection(instances_start, protection) & instance_ids
666 changed_ids = instance_ids - ready_ids
667
668 if not changed_ids:
669 return False, instances_start
670
671 if check_mode:
672 changed_instances = _change_instances(deepcopy(instances_start), group_name, changed_ids, protection=protection)
673 return True, changed_instances
674
675 _set_instance_protection(client, changed_ids, group_name, protection)
676
677 state = "Protected" if protection else "NotProtected"
678
679 wait_instance_state(client, state, check_mode, group_name, changed_ids, wait, wait_timeout)
680
681 instances_complete = get_autoscaling_instances(client, group_name=group_name)
682 return True, instances_complete
683
684
685 def ensure_instance_pool(
686 client: RetryingBotoClientWrapper,
687 check_mode: bool,
688 instances_start: AnsibleAWSResourceList,
689 group_name: str,
690 state: str,
691 instance_ids: List[str],
692 purge_instances: bool,
693 decrement_desired_capacity: bool,
694 wait: bool,
695 wait_timeout: int,
696 ) -> Tuple[bool, AnsibleAWSResourceList]:
697 if state == "standby":
698 return ensure_instance_standby(
699 client,
700 check_mode,
701 instances_start,
702 group_name,
703 instance_ids or [],
704 decrement_desired_capacity,
705 wait,
706 wait_timeout,
707 )
708 if state == "detached":
709 return ensure_instance_absent(
710 client,
711 check_mode,
712 instances_start,
713 group_name,
714 instance_ids or [],
715 decrement_desired_capacity,
716 wait,
717 wait_timeout,
718 )
719
720 # Not valid for standby/terminated/detached
721 if instance_ids is None:
722 instance_ids = _all_instance_ids(instances_start)
723
724 if state == "attached":
725 return ensure_instance_attached(
726 client,
727 check_mode,
728 instances_start,
729 group_name,
730 instance_ids,
731 decrement_desired_capacity,
732 purge_instances,
733 wait,
734 wait_timeout,
735 )
736 if state == "present":
737 return ensure_instance_present(
738 client,
739 check_mode,
740 instances_start,
741 group_name,
742 instance_ids,
743 decrement_desired_capacity,
744 purge_instances,
745 wait,
746 wait_timeout,
747 )
748
749 if state == "terminated":
750 return ensure_instance_terminated(
751 client,
752 check_mode,
753 instances_start,
754 group_name,
755 instance_ids,
756 decrement_desired_capacity,
757 wait,
758 wait_timeout,
759 )
760
761 return False, instances_start
762
763
764 def _validate_standby_conditions(params: Dict[str, Any], instances: AnsibleAWSResourceList) -> None:
765 instance_ids = set(params.get("instance_ids"))
766 all_ids = _all_instance_ids(instances)
767
768 missing_ids = instance_ids - all_ids
769 if missing_ids:
770 raise AnsibleAutoScalingError(
771 message=f"Unable to place instance(s) ({missing_ids}) into Standby - instances not attached to AutoScaling Group ({params['group_name']})",
772 )
773
774 # We don't need to change these instances, we may need to wait for them
775 standby_ids = _instance_ids_in_states(instances, STATE_MAP["entering+"])
776 # We need to wait for these instances to enter "InService" before we can do anything with them
777 pending_ids = _instance_ids_in_states(instances, STATE_MAP["pending"])
778 # These instances are ready to move to Standby
779 ready_ids = _instance_ids_in_states(instances, ["InService"])
780
781 bad_ids = all_ids - standby_ids - pending_ids - ready_ids
782 if bad_ids:
783 raise AnsibleAutoScalingError(
784 message=f"Unable to place instance(s) ({bad_ids}) into Standby - instances not in a state that can transition to Standby or InService",
785 )
786
787 if pending_ids and not params.get("wait"):
788 raise AnsibleAutoScalingError(
789 message=f"Unable to plance instances ({pending_ids}) into Standby - currently in a pending state and wait is disabled",
790 )
791
792 return
793
794
795 def _validate_remove_conditions(params: Dict[str, Any], instances: AnsibleAWSResourceList) -> None:
796 target_verb = {"detached": "detach", "terminated": "terminate"}[params["state"]]
797
798 if params["health"] is not None:
799 raise AnsibleAutoScalingError(message=f"Unable to set instance health when state is {params['state']}")
800
801 instance_ids = set(params.get("instance_ids"))
802 pending_ids = _instance_ids_in_states(instances, STATE_MAP["pending"] + STATE_MAP["entering"])
803
804 if (pending_ids & instance_ids) and not params.get("wait"):
805 raise AnsibleAutoScalingError(
806 message=f"Unable to {target_verb} instances ({pending_ids & instance_ids}) currently in a pending state and wait is disabled",
807 )
808
809 return
810
811
812 def _validate_attach_conditions(params: Dict[str, Any], instances: AnsibleAWSResourceList) -> None:
813 instance_ids = set(params.get("instance_ids") or [])
814
815 # These instances are terminating, we can't do anything with them.
816 terminating_ids = _instance_ids_in_states(instances, STATE_MAP["terminating+"]) & instance_ids
817 # We need to wait for these instances to enter "InService" or "Standby" before we can do anything with them
818 pending_ids = _instance_ids_in_states(instances, STATE_MAP["entering"]) & instance_ids
819 detaching_ids = _instance_ids_in_states(instances, STATE_MAP["detaching"]) & instance_ids
820
821 if terminating_ids:
822 raise AnsibleAutoScalingError(
823 message=f"Unable to attach instances ({terminating_ids}) to AutoScaling group - instances not in a state that can transition to InService",
824 )
825
826 if not params.get("wait"):
827 if pending_ids and params.get("state") == "present":
828 raise AnsibleAutoScalingError(
829 message=f"Unable to plance instances ({pending_ids}) into Service - currently entering standby and wait is disabled",
830 )
831 if detaching_ids:
832 raise AnsibleAutoScalingError(
833 message=f"Unable to attach instances ({pending_ids}) to AutoScaling group - currently detaching and wait is disabled",
834 )
835
836
837 def validate_params(params: Dict[str, Any], instances: AnsibleAWSResourceList) -> None:
838 if params["state"] in ["terminated", "detached"]:
839 _validate_remove_conditions(params, instances)
840 if params["state"] == "standby":
841 _validate_standby_conditions(params, instances)
842 if params["state"] in ["attached", "present"]:
843 _validate_attach_conditions(params, instances)
844
845 return
846
847
848 def do(module):
849 client = module.client("autoscaling", retry_decorator=AWSRetry.jittered_backoff())
850
851 instances_start = get_autoscaling_instances(client, group_name=module.params["group_name"])
852 validate_params(module.params, instances_start)
853
854 instances = deepcopy(instances_start)
855
856 changed_pool, instances = ensure_instance_pool(
857 client,
858 check_mode=module.check_mode,
859 instances_start=instances,
860 group_name=module.params["group_name"],
861 state=module.params["state"],
862 instance_ids=module.params["instance_ids"],
863 purge_instances=module.params["purge_instances"],
864 decrement_desired_capacity=module.params["decrement_desired_capacity"],
865 wait=module.params["wait"],
866 wait_timeout=module.params["wait_timeout"],
867 )
868
869 changed_protection, instances = ensure_instance_protection(
870 client,
871 check_mode=module.check_mode,
872 instances_start=instances,
873 group_name=module.params["group_name"],
874 protection=module.params["protection"],
875 instance_ids=module.params["instance_ids"],
876 wait=module.params["wait"],
877 wait_timeout=module.params["wait_timeout"],
878 )
879
880 changed_health, instances = ensure_instance_health(
881 client,
882 check_mode=module.check_mode,
883 instances_start=instances,
884 group_name=module.params["group_name"],
885 health=module.params["health"],
886 instance_ids=module.params["instance_ids"],
887 respect_grace_period=module.params["respect_grace_period"],
888 wait=module.params["wait"],
889 wait_timeout=module.params["wait_timeout"],
890 )
891
892 changed = changed_pool or changed_protection or changed_health
893
894 result = {"changed": changed, "auto_scaling_instances": instances}
895
896 if module._diff: # pylint: disable=protected-access
897 result["diff"] = dict(
898 before=dict(auto_scaling_instances=instances_start),
899 after=dict(auto_scaling_instances=instances),
900 )
901
902 result["changed_pool"] = changed_pool
903 result["changed_protection"] = changed_protection
904 result["changed_health"] = changed_health
905
906 module.exit_json(**result)
907
908
909 def main():
910 argument_spec = dict(
911 group_name=dict(type="str", required=True),
912 state=dict(type="str", choices=["present", "attached", "terminated", "detached", "standby"], default="present"),
913 instance_ids=dict(type="list", elements="str"),
914 purge_instances=dict(type="bool", default=False),
915 decrement_desired_capacity=dict(type="bool", default=False),
916 health=dict(type="str", choices=["Healthy", "Unhealthy"]),
917 respect_grace_period=dict(type="bool", default=True),
918 protection=dict(type="bool"),
919 wait=dict(type="bool", default=True),
920 wait_timeout=dict(type="int", default=120),
921 )
922
923 required_if = [
924 ["state", "terminated", ["instance_ids"]],
925 ["state", "detached", ["instance_ids"]],
926 ["state", "standby", ["instance_ids"]],
927 ]
928
929 module = AnsibleAWSModule(
930 argument_spec=argument_spec,
931 supports_check_mode=True,
932 required_if=required_if,
933 )
934
935 try:
936 do(module)
937 except AnsibleAWSError as e:
938 module.fail_json_aws_error(e)
939
940
941 if __name__ == "__main__":
942 main()