Debian Codegraph @

ansible_collections/community/aws/plugins/modules/elb_target_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: elb_target_group_info
10 version_added: 1.0.0
11 short_description: Gather information about ELB target groups in AWS
12 description:
13 - Gather information about ELB target groups in AWS
14 author:
15 - Rob White (@wimnat)
16 options:
17 load_balancer_arn:
18 description:
19 - The Amazon Resource Name (ARN) of the load balancer.
20 required: false
21 type: str
22 target_group_arns:
23 description:
24 - The Amazon Resource Names (ARN) of the target groups.
25 required: false
26 type: list
27 elements: str
28 names:
29 description:
30 - The names of the target groups.
31 required: false
32 type: list
33 elements: str
34 collect_targets_health:
35 description:
36 - When set to C(True), output contains targets health description
37 required: false
38 default: false
39 type: bool
40
41 extends_documentation_fragment:
42 - amazon.aws.common.modules
43 - amazon.aws.region.modules
44 - amazon.aws.boto3
45 """
46
47 EXAMPLES = r"""
48 # Note: These examples do not set authentication details, see the AWS Guide for details.
49
50 - name: Gather information about all target groups
51 community.aws.elb_target_group_info:
52
53 - name: Gather information about the target group attached to a particular ELB
54 community.aws.elb_target_group_info:
55 load_balancer_arn: "arn:aws:elasticloadbalancing:ap-southeast-2:123456789012:loadbalancer/app/my-elb/aabbccddeeff"
56
57 - name: Gather information about a target groups named 'tg1' and 'tg2'
58 community.aws.elb_target_group_info:
59 names:
60 - tg1
61 - tg2
62 """
63
64 RETURN = r"""
65 target_groups:
66 description: a list of target groups
67 returned: always
68 type: complex
69 contains:
70 deregistration_delay_timeout_seconds:
71 description: The amount time for Elastic Load Balancing to wait before changing the state of a deregistering target from draining to unused.
72 returned: always
73 type: int
74 sample: 300
75 health_check_interval_seconds:
76 description: The approximate amount of time, in seconds, between health checks of an individual target.
77 returned: always
78 type: int
79 sample: 30
80 health_check_path:
81 description: The destination for the health check request.
82 returned: always
83 type: str
84 sample: /index.html
85 health_check_port:
86 description: The port to use to connect with the target.
87 returned: always
88 type: str
89 sample: traffic-port
90 health_check_protocol:
91 description: The protocol to use to connect with the target.
92 returned: always
93 type: str
94 sample: HTTP
95 health_check_timeout_seconds:
96 description: The amount of time, in seconds, during which no response means a failed health check.
97 returned: always
98 type: int
99 sample: 5
100 healthy_threshold_count:
101 description: The number of consecutive health checks successes required before considering an unhealthy target healthy.
102 returned: always
103 type: int
104 sample: 5
105 load_balancer_arns:
106 description: The Amazon Resource Names (ARN) of the load balancers that route traffic to this target group.
107 returned: always
108 type: list
109 sample: []
110 matcher:
111 description: The HTTP codes to use when checking for a successful response from a target.
112 returned: always
113 type: dict
114 sample: {
115 "http_code": "200"
116 }
117 port:
118 description: The port on which the targets are listening.
119 returned: always
120 type: int
121 sample: 80
122 protocol:
123 description: The protocol to use for routing traffic to the targets.
124 returned: always
125 type: str
126 sample: HTTP
127 stickiness_enabled:
128 description: Indicates whether sticky sessions are enabled.
129 returned: always
130 type: bool
131 sample: true
132 stickiness_lb_cookie_duration_seconds:
133 description: Indicates whether sticky sessions are enabled.
134 returned: always
135 type: int
136 sample: 86400
137 stickiness_type:
138 description: The type of sticky sessions.
139 returned: always
140 type: str
141 sample: lb_cookie
142 tags:
143 description: The tags attached to the target group.
144 returned: always
145 type: dict
146 sample: "{
147 'Tag': 'Example'
148 }"
149 target_group_arn:
150 description: The Amazon Resource Name (ARN) of the target group.
151 returned: always
152 type: str
153 sample: "arn:aws:elasticloadbalancing:ap-southeast-2:123456789012:targetgroup/mytargetgroup/aabbccddee0044332211"
154 targets_health_description:
155 description: Targets health description.
156 returned: when collect_targets_health is enabled
157 type: complex
158 contains:
159 health_check_port:
160 description: The port to check target health.
161 returned: always
162 type: str
163 sample: '80'
164 target:
165 description: The target metadata.
166 returned: always
167 type: complex
168 contains:
169 id:
170 description: The ID of the target.
171 returned: always
172 type: str
173 sample: i-0123456789
174 port:
175 description: The port to use to connect with the target.
176 returned: always
177 type: int
178 sample: 80
179 target_health:
180 description: The target health status.
181 returned: always
182 type: complex
183 contains:
184 state:
185 description: The state of the target health.
186 returned: always
187 type: str
188 sample: healthy
189 target_group_name:
190 description: The name of the target group.
191 returned: always
192 type: str
193 sample: mytargetgroup
194 unhealthy_threshold_count:
195 description: The number of consecutive health check failures required before considering the target unhealthy.
196 returned: always
197 type: int
198 sample: 2
199 vpc_id:
200 description: The ID of the VPC for the targets.
201 returned: always
202 type: str
203 sample: vpc-0123456
204 """
205
206 try:
207 import botocore
208 except ImportError:
209 pass # Handled by AnsibleAWSModule
210
211 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
212
213 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
214 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
215 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
216
217 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
218
219
220 @AWSRetry.jittered_backoff(retries=10)
221 def get_paginator(**kwargs):
222 paginator = client.get_paginator("describe_target_groups")
223 return paginator.paginate(**kwargs).build_full_result()
224
225
226 def get_target_group_attributes(target_group_arn):
227 try:
228 target_group_attributes = boto3_tag_list_to_ansible_dict(
229 client.describe_target_group_attributes(TargetGroupArn=target_group_arn)["Attributes"]
230 )
231 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
232 module.fail_json_aws(e, msg="Failed to describe target group attributes")
233
234 # Replace '.' with '_' in attribute key names to make it more Ansibley
235 return dict((k.replace(".", "_"), v) for (k, v) in target_group_attributes.items())
236
237
238 def get_target_group_tags(target_group_arn):
239 try:
240 return boto3_tag_list_to_ansible_dict(
241 client.describe_tags(ResourceArns=[target_group_arn])["TagDescriptions"][0]["Tags"]
242 )
243 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
244 module.fail_json_aws(e, msg="Failed to describe group tags")
245
246
247 def get_target_group_targets_health(target_group_arn):
248 try:
249 return client.describe_target_health(TargetGroupArn=target_group_arn)["TargetHealthDescriptions"]
250 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
251 module.fail_json_aws(e, msg="Failed to get target health")
252
253
254 def list_target_groups():
255 load_balancer_arn = module.params.get("load_balancer_arn")
256 target_group_arns = module.params.get("target_group_arns")
257 names = module.params.get("names")
258 collect_targets_health = module.params.get("collect_targets_health")
259
260 try:
261 if not load_balancer_arn and not target_group_arns and not names:
262 target_groups = get_paginator()
263 if load_balancer_arn:
264 target_groups = get_paginator(LoadBalancerArn=load_balancer_arn)
265 if target_group_arns:
266 target_groups = get_paginator(TargetGroupArns=target_group_arns)
267 if names:
268 target_groups = get_paginator(Names=names)
269 except is_boto3_error_code("TargetGroupNotFound"):
270 module.exit_json(target_groups=[])
271 except (
272 botocore.exceptions.ClientError,
273 botocore.exceptions.BotoCoreError,
274 ) as e: # pylint: disable=duplicate-except
275 module.fail_json_aws(e, msg="Failed to list target groups")
276
277 # Get the attributes and tags for each target group
278 for target_group in target_groups["TargetGroups"]:
279 target_group.update(get_target_group_attributes(target_group["TargetGroupArn"]))
280
281 # Turn the boto3 result in to ansible_friendly_snaked_names
282 snaked_target_groups = [camel_dict_to_snake_dict(target_group) for target_group in target_groups["TargetGroups"]]
283
284 # Get tags for each target group
285 for snaked_target_group in snaked_target_groups:
286 snaked_target_group["tags"] = get_target_group_tags(snaked_target_group["target_group_arn"])
287 if collect_targets_health:
288 snaked_target_group["targets_health_description"] = [
289 camel_dict_to_snake_dict(target)
290 for target in get_target_group_targets_health(snaked_target_group["target_group_arn"])
291 ]
292
293 module.exit_json(target_groups=snaked_target_groups)
294
295
296 def main():
297 global module
298 global client
299
300 argument_spec = dict(
301 load_balancer_arn=dict(type="str"),
302 target_group_arns=dict(type="list", elements="str"),
303 names=dict(type="list", elements="str"),
304 collect_targets_health=dict(default=False, type="bool", required=False),
305 )
306
307 module = AnsibleAWSModule(
308 argument_spec=argument_spec,
309 mutually_exclusive=[["load_balancer_arn", "target_group_arns", "names"]],
310 supports_check_mode=True,
311 )
312
313 try:
314 client = module.client("elbv2", retry_decorator=AWSRetry.jittered_backoff(retries=10))
315 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
316 module.fail_json_aws(e, msg="Failed to connect to AWS")
317
318 list_target_groups()
319
320
321 if __name__ == "__main__":
322 main()