Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/autoscaling_group_info.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: autoscaling_group_info
10 version_added: 5.0.0
11 short_description: Gather information about EC2 Auto Scaling Groups (ASGs) in AWS
12 description:
13 - Gather information about EC2 Auto Scaling Groups (ASGs) in AWS.
14 - Prior to release 5.0.0 this module was called M(community.aws.ec2_asg_info).
15 The usage did not change.
16 - This module was originally added to C(community.aws) in release 1.0.0.
17 author:
18 - "Rob White (@wimnat)"
19 options:
20 name:
21 description:
22 - The prefix or name of the auto scaling group(s) you are searching for.
23 - "Note: This is a regular expression match with implicit '^' (beginning of string). Append '$' for a complete name match."
24 type: str
25 required: false
26 aliases: ["group_name"]
27 tags:
28 description:
29 - >
30 A dictionary/hash of tags in the format { tag1_name: 'tag1_value', tag2_name: 'tag2_value' } to match against the auto scaling
31 group(s) you are searching for.
32 required: false
33 type: dict
34 extends_documentation_fragment:
35 - amazon.aws.common.modules
36 - amazon.aws.region.modules
37 - amazon.aws.boto3
38 """
39
40 EXAMPLES = r"""
41 # Note: These examples do not set authentication details, see the AWS Guide for details.
42
43 - name: Find all groups
44 amazon.aws.autoscaling_group_info:
45 register: asgs
46
47 - name: Find a group with matching name/prefix
48 amazon.aws.autoscaling_group_info:
49 name: public-webserver-asg
50 register: asgs
51
52 - name: Find a group with matching tags
53 amazon.aws.autoscaling_group_info:
54 tags:
55 project: webapp
56 env: production
57 register: asgs
58
59 - name: Find a group with matching name/prefix and tags
60 amazon.aws.autoscaling_group_info:
61 name: myproject
62 tags:
63 env: production
64 register: asgs
65
66 - name: Fail if no groups are found
67 amazon.aws.autoscaling_group_info:
68 name: public-webserver-asg
69 register: asgs
70 failed_when: "{{ asgs.results | length == 0 }}"
71
72 - name: Fail if more than 1 group is found
73 amazon.aws.autoscaling_group_info:
74 name: public-webserver-asg
75 register: asgs
76 failed_when: "{{ asgs.results | length > 1 }}"
77 """
78
79 RETURN = r"""
80 results:
81 description: A list of Auto Scaling Groups.
82 returned: always
83 type: list
84 elements: dict
85 contains:
86 auto_scaling_group_arn:
87 description: The Amazon Resource Name of the ASG.
88 returned: success
89 type: str
90 sample: "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:10787c52-0bcb-427d-82ba-c8e4b008ed2e:autoScalingGroupName/dev11"
91 auto_scaling_group_name:
92 description: Name of autoscaling group.
93 returned: success
94 type: str
95 sample: "public-webapp-production-1"
96 availability_zones:
97 description: List of Availability Zones that are enabled for this ASG.
98 returned: success
99 type: list
100 sample: ["us-west-2a", "us-west-2b", "us-west-2a"]
101 created_time:
102 description: The date and time this ASG was created, in ISO 8601 format.
103 returned: success
104 type: str
105 sample: "2015-11-25T00:05:36.309Z"
106 default_cooldown:
107 description: The default cooldown time in seconds.
108 returned: success
109 type: int
110 sample: 300
111 desired_capacity:
112 description: The number of EC2 instances that should be running in this group.
113 returned: success
114 type: int
115 sample: 3
116 enabled_metrics:
117 description: The metrics enabled for the group.
118 returned: success
119 type: list
120 elements: dict
121 sample: [{
122 "granularity": "1Minute",
123 "metric": "GroupAndWarmPoolTotalCapacity"
124 }]
125 contains:
126 metric:
127 description: Name of the metric.
128 type: str
129 sample: "GroupAndWarmPoolTotalCapacity"
130 granularity:
131 description: The granularity of the metric. The only valid value is 1Minute.
132 type: str
133 sample: "1Minute"
134 health_check_grace_period:
135 description: Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health.
136 returned: success
137 type: int
138 sample: 300
139 health_check_type:
140 description: The service you want the health status from, one of "EC2" or "ELB".
141 returned: success
142 type: str
143 sample: "ELB"
144 instances:
145 description: List of EC2 instances associated with ASG and their status.
146 returned: success
147 type: list
148 elements: dict
149 sample: [
150 {
151 "availability_zone": "us-west-2a",
152 "health_status": "Healthy",
153 "instance_id": "i-es22ad25",
154 "launch_configuration_name": "public-webapp-production-1",
155 "launch_template": {
156 "launch_template_id": "lt-0b19eb00123456789",
157 "launch_template_name": "test-template",
158 "version": "1"
159 },
160 "lifecycle_state": "InService",
161 "protected_from_scale_in": "false"
162 }
163 ]
164 contains:
165 availability_zone:
166 description: The Availability Zone of the instance.
167 type: str
168 sample: "ap-southeast-2a"
169 health_status:
170 description: The last reported health status of the instance.
171 type: str
172 sample: "Healthy"
173 instance_id:
174 description: The ID of the instance.
175 type: str
176 sample: "i-012345678"
177 instance_type:
178 description: The instance type size of the running instance.
179 type: str
180 sample: "t2.micro"
181 launch_template:
182 description: The EC2 launch template to base instance configuration on.
183 type: dict
184 contains:
185 launch_template_id:
186 description: The ID of the launch template.
187 type: str
188 launch_template_name:
189 description: The name of the launch template.
190 type: str
191 version:
192 description: The specific version of the launch template to use.
193 type: int
194 lifecycle_state:
195 description: A description of the current lifecycle state.
196 type: str
197 protected_from_scale_in:
198 description: Indicates whether the instance is protected from termination by Amazon EC2 Auto Scaling when scaling in.
199 type: bool
200 launch_config_name:
201 description: >
202 Name of launch configuration associated with the ASG. Same as launch_configuration_name,
203 provided for compatibility with M(amazon.aws.autoscaling_group) module.
204 returned: success
205 type: str
206 sample: "public-webapp-production-1"
207 launch_configuration_name:
208 description: Name of launch configuration associated with the ASG.
209 returned: success
210 type: str
211 sample: "public-webapp-production-1"
212 lifecycle_hooks:
213 description: List of lifecycle hooks for the ASG.
214 returned: success
215 type: list
216 sample: [
217 {
218 "AutoScalingGroupName": "public-webapp-production-1",
219 "DefaultResult": "ABANDON",
220 "GlobalTimeout": 172800,
221 "HeartbeatTimeout": 3600,
222 "LifecycleHookName": "instance-launch",
223 "LifecycleTransition": "autoscaling:EC2_INSTANCE_LAUNCHING"
224 },
225 {
226 "AutoScalingGroupName": "public-webapp-production-1",
227 "DefaultResult": "ABANDON",
228 "GlobalTimeout": 172800,
229 "HeartbeatTimeout": 3600,
230 "LifecycleHookName": "instance-terminate",
231 "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING"
232 }
233 ]
234 load_balancer_names:
235 description: List of load balancers names attached to the ASG.
236 returned: success
237 type: list
238 sample: ["elb-webapp-prod"]
239 max_size:
240 description: Maximum size of group.
241 returned: success
242 type: int
243 sample: 3
244 min_size:
245 description: Minimum size of group.
246 returned: success
247 type: int
248 sample: 1
249 new_instances_protected_from_scale_in:
250 description: Whether or not new instances a protected from automatic scaling in.
251 returned: success
252 type: bool
253 sample: false
254 placement_group:
255 description: Placement group into which instances are launched, if any.
256 returned: success
257 type: str
258 sample: None
259 service_linked_role_arn:
260 description: The ARN of the service-linked role that the Auto Scaling group uses to call other Amazon Web Services on your behalf.
261 returned: success
262 type: str
263 sample: "arn:aws:iam::721234567890:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling"
264 suspended_processes:
265 description: The suspended processes associated with the group.
266 returned: success
267 type: list
268 elements: dict
269 sample: [{
270 "process_name": "AddToLoadBalancer",
271 "suspension_reason": "User suspended at 2018-08-30T14:11:58Z"
272 }]
273 contains:
274 process_name:
275 description: The name of the suspended process.
276 type: str
277 suspension_reason:
278 description: The reason that the process was suspended.
279 type: str
280 status:
281 description: The current state of the group when DeleteAutoScalingGroup is in progress.
282 returned: success
283 type: str
284 sample: None
285 tags:
286 description: List of tags for the ASG, and whether or not each tag propagates to instances at launch.
287 returned: success
288 type: list
289 sample: [
290 {
291 "key": "Name",
292 "value": "public-webapp-production-1",
293 "resource_id": "public-webapp-production-1",
294 "resource_type": "auto-scaling-group",
295 "propagate_at_launch": "true"
296 },
297 {
298 "key": "env",
299 "value": "production",
300 "resource_id": "public-webapp-production-1",
301 "resource_type": "auto-scaling-group",
302 "propagate_at_launch": "true"
303 }
304 ]
305 target_group_arns:
306 description: List of ARNs of the target groups that the ASG populates.
307 returned: success
308 type: list
309 sample: [
310 "arn:aws:elasticloadbalancing:ap-southeast-2:123456789012:targetgroup/target-group-host-hello/1a2b3c4d5e6f1a2b",
311 "arn:aws:elasticloadbalancing:ap-southeast-2:123456789012:targetgroup/target-group-path-world/abcd1234abcd1234"
312 ]
313 target_group_names:
314 description: List of names of the target groups that the ASG populates.
315 returned: success
316 type: list
317 sample: [
318 "target-group-host-hello",
319 "target-group-path-world"
320 ]
321 termination_policies:
322 description: A list of termination policies for the group.
323 returned: success
324 type: list
325 elements: str
326 sample: ["Default"]
327 traffic_sources:
328 description: The traffic sources associated with this Auto Scaling group.
329 returned: success
330 type: list
331 sample: [{
332 "identifier": "arn:aws:elasticloadbalancing:us-west-2:721234567890:targetgroup/Check-Exter-A4XXXXXXXXXX/8aXXXXXXXXXXXXXX",
333 "type": "elbv2"
334 }]
335 contains:
336 identifier:
337 description: Identifies the traffic source.
338 type: str
339 type:
340 description: Provides additional context for the value of Identifier.
341 type: str
342 vpc_zone_identifier:
343 description: One or more subnet IDs, if applicable, separated by commas.
344 returned: success
345 type: str
346 sample: "subnet-0352db1247ae60b40,subnet-01f266bb9928ddaee"
347 """
348
349 import re
350
351 try:
352 import botocore
353 except ImportError:
354 pass # caught by AnsibleAWSModule
355
356 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
357
358 from ansible_collections.amazon.aws.plugins.module_utils.elb_utils import AnsibleELBv2Error
359 from ansible_collections.amazon.aws.plugins.module_utils.elb_utils import describe_target_groups
360 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
361
362
363 def match_asg_tags(tags_to_match, asg):
364 for key, value in tags_to_match.items():
365 for tag in asg["Tags"]:
366 if key == tag["Key"] and value == tag["Value"]:
367 break
368 else:
369 return False
370 return True
371
372
373 def find_asgs(conn, module, name=None, tags=None):
374 """
375 Args:
376 conn (boto3.AutoScaling.Client): Valid Boto3 ASG client.
377 name (str): Optional name of the ASG you are looking for.
378 tags (dict): Optional dictionary of tags and values to search for.
379
380 Basic Usage:
381 >>> name = 'public-webapp-production'
382 >>> tags = { 'env': 'production' }
383 >>> conn = boto3.client('autoscaling', region_name='us-west-2')
384 >>> results = find_asgs(name, conn)
385
386 Returns:
387 List
388 [
389 {
390 "auto_scaling_group_arn": (
391 "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:58abc686-9783-4528-b338-3ad6f1cbbbaf:"
392 "autoScalingGroupName/public-webapp-production"
393 ),
394 "auto_scaling_group_name": "public-webapp-production",
395 "availability_zones": ["us-west-2c", "us-west-2b", "us-west-2a"],
396 "created_time": "2016-02-02T23:28:42.481000+00:00",
397 "default_cooldown": 300,
398 "desired_capacity": 2,
399 "enabled_metrics": [],
400 "health_check_grace_period": 300,
401 "health_check_type": "ELB",
402 "instances":
403 [
404 {
405 "availability_zone": "us-west-2c",
406 "health_status": "Healthy",
407 "instance_id": "i-047a12cb",
408 "launch_configuration_name": "public-webapp-production-1",
409 "lifecycle_state": "InService",
410 "protected_from_scale_in": false
411 },
412 {
413 "availability_zone": "us-west-2a",
414 "health_status": "Healthy",
415 "instance_id": "i-7a29df2c",
416 "launch_configuration_name": "public-webapp-production-1",
417 "lifecycle_state": "InService",
418 "protected_from_scale_in": false
419 }
420 ],
421 "launch_config_name": "public-webapp-production-1",
422 "launch_configuration_name": "public-webapp-production-1",
423 "lifecycle_hooks":
424 [
425 {
426 "AutoScalingGroupName": "public-webapp-production-1",
427 "DefaultResult": "ABANDON",
428 "GlobalTimeout": 172800,
429 "HeartbeatTimeout": 3600,
430 "LifecycleHookName": "instance-launch",
431 "LifecycleTransition": "autoscaling:EC2_INSTANCE_LAUNCHING"
432 },
433 {
434 "AutoScalingGroupName": "public-webapp-production-1",
435 "DefaultResult": "ABANDON",
436 "GlobalTimeout": 172800,
437 "HeartbeatTimeout": 3600,
438 "LifecycleHookName": "instance-terminate",
439 "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING"
440 }
441 ],
442 "load_balancer_names": ["public-webapp-production-lb"],
443 "max_size": 4,
444 "min_size": 2,
445 "new_instances_protected_from_scale_in": false,
446 "placement_group": None,
447 "status": None,
448 "suspended_processes": [],
449 "tags":
450 [
451 {
452 "key": "Name",
453 "propagate_at_launch": true,
454 "resource_id": "public-webapp-production",
455 "resource_type": "auto-scaling-group",
456 "value": "public-webapp-production"
457 },
458 {
459 "key": "env",
460 "propagate_at_launch": true,
461 "resource_id": "public-webapp-production",
462 "resource_type": "auto-scaling-group",
463 "value": "production"
464 }
465 ],
466 "target_group_names": [],
467 "target_group_arns": [],
468 "termination_policies":
469 [
470 "Default"
471 ],
472 "vpc_zone_identifier":
473 [
474 "subnet-a1b1c1d1",
475 "subnet-a2b2c2d2",
476 "subnet-a3b3c3d3"
477 ]
478 }
479 ]
480 """
481
482 try:
483 asgs_paginator = conn.get_paginator("describe_auto_scaling_groups")
484 asgs = asgs_paginator.paginate().build_full_result()
485 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
486 module.fail_json_aws(e, msg="Failed to describe AutoScalingGroups")
487
488 if not asgs:
489 return asgs
490
491 try:
492 elbv2 = module.client("elbv2")
493 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError):
494 # This is nice to have, not essential
495 elbv2 = None
496 matched_asgs = []
497
498 if name is not None:
499 # if the user didn't specify a name
500 name_prog = re.compile(r"^" + name)
501
502 for asg in asgs["AutoScalingGroups"]:
503 if name:
504 matched_name = name_prog.search(asg["AutoScalingGroupName"])
505 else:
506 matched_name = True
507
508 if tags:
509 matched_tags = match_asg_tags(tags, asg)
510 else:
511 matched_tags = True
512
513 if matched_name and matched_tags:
514 asg = camel_dict_to_snake_dict(asg)
515 # compatibility with autoscaling_group module
516 if "launch_configuration_name" in asg:
517 asg["launch_config_name"] = asg["launch_configuration_name"]
518 # workaround for https://github.com/ansible/ansible/pull/25015
519 if "target_group_ar_ns" in asg:
520 asg["target_group_arns"] = asg["target_group_ar_ns"]
521 del asg["target_group_ar_ns"]
522 if asg.get("target_group_arns"):
523 if elbv2:
524 try:
525 # Limit of 20 similar to https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeLoadBalancers.html
526 tg_chunk_size = 20
527 asg["target_group_names"] = []
528 tg_chunks = [
529 asg["target_group_arns"][i: i + tg_chunk_size]
530 for i in range(0, len(asg["target_group_arns"]), tg_chunk_size)
531 ] # fmt: skip
532 for chunk in tg_chunks:
533 asg["target_group_names"].extend(
534 [tg["TargetGroupName"] for tg in describe_target_groups(elbv2, TargetGroupArns=chunk)]
535 )
536 except AnsibleELBv2Error as e:
537 module.fail_json_aws(e, msg="Failed to describe Target Groups")
538 else:
539 asg["target_group_names"] = []
540 # get asg lifecycle hooks if any
541 try:
542 asg_lifecyclehooks = conn.describe_lifecycle_hooks(AutoScalingGroupName=asg["auto_scaling_group_name"])
543 asg["lifecycle_hooks"] = asg_lifecyclehooks["LifecycleHooks"]
544 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
545 module.fail_json_aws(e, msg="Failed to fetch information about ASG lifecycle hooks")
546 matched_asgs.append(asg)
547
548 return matched_asgs
549
550
551 def main():
552 argument_spec = dict(
553 name=dict(type="str", aliases=["group_name"]),
554 tags=dict(type="dict"),
555 )
556
557 module = AnsibleAWSModule(
558 argument_spec=argument_spec,
559 supports_check_mode=True,
560 )
561
562 asg_name = module.params.get("name")
563 asg_tags = module.params.get("tags")
564
565 autoscaling = module.client("autoscaling")
566
567 results = find_asgs(autoscaling, module, name=asg_name, tags=asg_tags)
568 module.exit_json(results=results)
569
570
571 if __name__ == "__main__":
572 main()