Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/elb_classic_lb_info.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 DOCUMENTATION = r"""
8 ---
9 module: elb_classic_lb_info
10 version_added: 1.0.0
11 version_added_collection: community.aws
12 short_description: Gather information about EC2 Classic Elastic Load Balancers in AWS
13 description:
14 - Gather information about EC2 Classic Elastic Load Balancers in AWS.
15 author:
16 - "Michael Schultz (@mjschultz)"
17 - "Fernando Jose Pando (@nand0p)"
18 options:
19 names:
20 description:
21 - List of ELB names to gather information about. Pass this option to gather information about a set of ELBs, otherwise, all ELBs are returned.
22 type: list
23 elements: str
24 default: []
25 extends_documentation_fragment:
26 - amazon.aws.common.modules
27 - amazon.aws.region.modules
28 - amazon.aws.boto3
29 """
30
31 EXAMPLES = r"""
32 # Note: These examples do not set authentication details, see the AWS Guide for details.
33 # Output format tries to match amazon.aws.elb_classic_lb module input parameters
34
35 - name: Gather information about all ELBs
36 amazon.aws.elb_classic_lb_info:
37 register: elb_info
38
39 - ansible.builtin.debug:
40 msg: "{{ item.dns_name }}"
41 loop: "{{ elb_info.elbs }}"
42
43 - name: Gather information about a particular ELB
44 amazon.aws.elb_classic_lb_info:
45 names: frontend-prod-elb
46 register: elb_info
47
48 - ansible.builtin.debug:
49 msg: "{{ elb_info.elbs.0.dns_name }}"
50
51 - name: Gather information about a set of ELBs
52 amazon.aws.elb_classic_lb_info:
53 names:
54 - frontend-prod-elb
55 - backend-prod-elb
56 register: elb_info
57
58 - ansible.builtin.debug:
59 msg: "{{ item.dns_name }}"
60 loop: "{{ elb_info.elbs }}"
61 """
62
63 RETURN = r"""
64 elbs:
65 description: A list of load balancers.
66 returned: always
67 type: list
68 elements: dict
69 contains:
70 attributes:
71 description: Information about the load balancer attributes.
72 returned: always
73 type: dict
74 contains:
75 access_log:
76 description: Information on whether access logs are enabled or not.
77 type: dict
78 sample: {
79 "enabled": false
80 }
81 additional_attributes:
82 description: Information about additional load balancer attributes.
83 type: list
84 elements: dict
85 sample: [
86 {
87 "key": "elb.http.desyncmitigationmode",
88 "value": "defensive"
89 }
90 ]
91 connection_draining:
92 description:
93 - Information on connection draining configuration of elastic load balancer.
94 type: dict
95 sample: {
96 "enabled": true,
97 "timeout": 300
98 }
99 contains:
100 enabled:
101 description: Whether connection draining is enabled.
102 type: bool
103 returned: always
104 timeout:
105 description: The maximum time, in seconds, to keep the existing connections open before deregistering the instances.
106 type: int
107 returned: always
108 connection_settings:
109 description: Information on connection settings.
110 type: dict
111 sample: {
112 "idle_timeout": 60
113 }
114 cross_zone_load_balancing:
115 description: Information on whether cross zone load balancing is enabled or not.
116 type: dict
117 sample: {
118 "enabled": true
119 }
120 availability_zones:
121 description: The Availability Zones for the load balancer.
122 type: list
123 elements: str
124 returned: always
125 sample: [
126 "us-west-2a"
127 ]
128 backend_server_descriptions:
129 description: Information about your EC2 instances.
130 type: list
131 elements: dict
132 returned: always
133 sample: [
134 {
135 instance_port: 8085,
136 policy_names: [
137 'MyPolicy1',
138 ]
139 },
140 ]
141 canonical_hosted_zone_name:
142 description: The DNS name of the load balancer.
143 type: str
144 returned: always
145 sample: "test-123456789.us-west-2.elb.amazonaws.com"
146 canonical_hosted_zone_name_id:
147 description: The ID of the Amazon Route 53 hosted zone for the load balancer.
148 type: str
149 returned: always
150 sample: "Z1Z1ZZ5HABSF5"
151 created_time:
152 description: The date and time the load balancer was created.
153 type: str
154 returned: always
155 sample: "2024-09-04T17:52:22.270000+00:00"
156 dns_name:
157 description: The DNS name of the load balancer.
158 type: str
159 returned: "always"
160 sample: "test-123456789.us-west-2.elb.amazonaws.com"
161 health_check:
162 description: Information about the health checks conducted on the load balancer.
163 type: dict
164 returned: always
165 sample: {
166 "healthy_threshold": 10,
167 "interval": 5,
168 "target": "HTTP:80/index.html",
169 "timeout": 2,
170 "unhealthy_threshold": 2
171 }
172 contains:
173 healthy_threshold:
174 description: The number of consecutive health checks successes required before moving the instance to the Healthy state.
175 type: int
176 returned: always
177 interval:
178 description: The approximate interval, in seconds, between health checks of an individual instance.
179 type: int
180 returned: always
181 target:
182 description: The instance being checked. The protocol is either TCP, HTTP, HTTPS, or SSL. The range of valid ports is one (1) through 65535.
183 type: str
184 returned: always
185 timeout:
186 description: The amount of time, in seconds, during which no response means a failed health check.
187 type: int
188 returned: always
189 unhealthy_threshold:
190 description: The number of consecutive health checks successes required before moving the instance to the Unhealthy state.
191 type: int
192 returned: always
193 instances:
194 description: The IDs of the instances for the load balancer.
195 type: list
196 elements: dict
197 returned: always
198 sample: [
199 {
200 "instance_id": "i-11d1f111ea111111b"
201 }
202 ]
203 instances_inservice:
204 description: Information about instances for load balancer in state "InService".
205 type: list
206 returned: always
207 sample: [
208 "i-11d1f111ea111111b"
209 ]
210 instances_inservice_count:
211 description: Total number of instances for load balancer with state "InService".
212 type: int
213 returned: always
214 sample: 1
215 instances_outofservice:
216 description: Information about instances for load balancer in state "OutOfService".
217 type: list
218 returned: always
219 sample: [
220 "i-11d1f111ea111111b"
221 ]
222 instances_outofservice_count:
223 description: Total number of instances for load balancer with state "OutOfService".
224 type: int
225 returned: always
226 sample: 0
227 instances_unknownservice:
228 description: Information about instances for load balancer in state "Unknown".
229 type: list
230 returned: always
231 sample: [
232 "i-11d1f111ea111111b"
233 ]
234 instances_unknownservice_count:
235 description: Total number of instances for load balancer with state "Unknown".
236 type: int
237 returned: always
238 sample: 1
239 listener_descriptions:
240 description: Information about the listeners for the load balancer.
241 type: list
242 elements: dict
243 returned: always
244 sample: [
245 {
246 "listener": {
247 "instance_port": 80,
248 "instance_protocol": "HTTP",
249 "load_balancer_port": 80,
250 "protocol": "HTTP"
251 },
252 "policy_names": []
253 }
254 ]
255 load_balancer_name:
256 description: The name of the elastic load balancer.
257 type: str
258 returned: always
259 sample: "MyLoadBalancer"
260 policies:
261 description: Information about the policies defined for the load balancer.
262 type: dict
263 returned: always
264 sample: {
265 "app_cookie_stickiness_policies": [],
266 "lb_cookie_stickiness_policies": [],
267 "other_policies": []
268 }
269 contains:
270 app_cookie_stickiness_policies:
271 description: The stickiness policies created using CreateAppCookieStickinessPolicy.
272 type: list
273 returned: always
274 lb_cookie_stickiness_policies:
275 description: The stickiness policies created using CreateLBCookieStickinessPolicy.
276 type: list
277 returned: always
278 other_policies:
279 description: The policies other than the stickiness policies.
280 type: list
281 returned: always
282 scheme:
283 description: The type of load balancer.
284 type: str
285 returned: always
286 sample: "internet-facing"
287 security_groups:
288 description: The security groups for the load balancer.
289 type: list
290 returned: always
291 sample: [
292 "sg-111111af1111cb111"
293 ]
294 source_security_group:
295 description:
296 - The security group for the load balancer,
297 which are used as part of inbound rules for registered instances.
298 type: dict
299 returned: always
300 sample: {
301 "group_name": "default",
302 "owner_alias": "721111111111"
303 }
304 contains:
305 group_name:
306 description: The name of the security group.
307 type: str
308 returned: always
309 owner_alias:
310 description: The owner of the security group.
311 type: str
312 returned: always
313 subnets:
314 description: The IDs of the subnets for the load balancer.
315 type: list
316 returned: always
317 sample: [
318 "subnet-111111af1111cb111"
319 ]
320 tags:
321 description: The tags associated with a load balancer.
322 type: dict
323 returned: always
324 sample: {
325 "Env": "Dev",
326 "Owner": "Dev001"
327 }
328 vpc_id:
329 description: The ID of the VPC for the load balancer.
330 type: str
331 returned: always
332 sample: "vpc-0cc28c9e20d111111"
333 """
334
335 from typing import Any
336 from typing import Dict
337 from typing import List
338 from typing import Tuple
339 from typing import Union
340
341 try:
342 import botocore
343 except ImportError:
344 pass # caught by AnsibleAWSModule
345
346 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
347
348 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
349 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
350 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
351 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
352
353
354 def list_elbs(connection: Any, load_balancer_names: List[str]) -> List[Dict]:
355 """
356 List Elastic Load Balancers (ELBs) and their detailed information.
357
358 Parameters:
359 connection (boto3.client): The Boto3 ELB client object.
360 load_balancer_names (List[str]): List of ELB names to gather information about.
361
362 Returns:
363 A list of dictionaries where each dictionary contains informtion about one ELB.
364 """
365 results = []
366
367 if not load_balancer_names:
368 for lb in get_all_lb(connection):
369 results.append(describe_elb(connection, lb))
370
371 for load_balancer_name in load_balancer_names:
372 lb = get_lb(connection, load_balancer_name)
373 if not lb:
374 continue
375 results.append(describe_elb(connection, lb))
376 return results
377
378
379 def describe_elb(connection: Any, lb: Dict[str, Any]) -> Dict[str, Any]:
380 """
381 Describes an Elastic Load Balancer (ELB).
382
383 Parameters:
384 connection (boto3.client): The Boto3 ELB client object.
385 lb (Dict): Dictionary containing ELB .
386
387 Returns:
388 A dictionary with detailed information of the ELB.
389 """
390 description = camel_dict_to_snake_dict(lb)
391 name = lb["LoadBalancerName"]
392 instances = lb.get("Instances", [])
393 description["tags"] = get_tags(connection, name)
394 description["instances_inservice"], description["instances_inservice_count"] = lb_instance_health(
395 connection, name, instances, "InService"
396 )
397 description["instances_outofservice"], description["instances_outofservice_count"] = lb_instance_health(
398 connection, name, instances, "OutOfService"
399 )
400 description["instances_unknownservice"], description["instances_unknownservice_count"] = lb_instance_health(
401 connection, name, instances, "Unknown"
402 )
403 description["attributes"] = get_lb_attributes(connection, name)
404 return description
405
406
407 @AWSRetry.jittered_backoff()
408 def get_all_lb(connection: Any) -> List:
409 """
410 Get paginated result for information of all Elastic Load Balancers.
411
412 Parameters:
413 connection (boto3.client): The Boto3 ELB client object.
414
415 Returns:
416 A list of dictionaries containing descriptions of all ELBs.
417 """
418 paginator = connection.get_paginator("describe_load_balancers")
419 return paginator.paginate().build_full_result()["LoadBalancerDescriptions"]
420
421
422 def get_lb(connection: Any, load_balancer_name: str) -> Union[Dict[str, Any], List]:
423 """
424 Describes a specific Elastic Load Balancer (ELB) by name.
425
426 Parameters:
427 connection (boto3.client): The Boto3 ELB client object.
428 load_balancer_name (str): Name of the ELB to gather information about.
429
430 Returns:
431 A dictionary with detailed information of the specified ELB.
432 """
433 try:
434 return connection.describe_load_balancers(aws_retry=True, LoadBalancerNames=[load_balancer_name])[
435 "LoadBalancerDescriptions"
436 ][0]
437 except is_boto3_error_code("LoadBalancerNotFound"):
438 return []
439
440
441 def get_lb_attributes(connection: Any, load_balancer_name: str) -> Dict[str, Any]:
442 """
443 Retrieves attributes of specific Elastic Load Balancer (ELB) by name.
444
445 Parameters:
446 connection (boto3.client): The Boto3 ELB client object.
447 load_balancer_name (str): Name of the ELB to gather information about.
448
449 Returns:
450 A dictionary with detailed information of the attributes of specified ELB.
451 """
452 attributes = connection.describe_load_balancer_attributes(aws_retry=True, LoadBalancerName=load_balancer_name).get(
453 "LoadBalancerAttributes", {}
454 )
455 return camel_dict_to_snake_dict(attributes)
456
457
458 def get_tags(connection: Any, load_balancer_name: str) -> Dict[str, Any]:
459 """
460 Retrieves tags of specific Elastic Load Balancer (ELB) by name.
461
462 Parameters:
463 connection (boto3.client): The Boto3 ELB client object.
464 load_balancer_name (str): Name of the ELB to gather information about.
465
466 Returns:
467 A dictionary of tags associated with the specified ELB.
468 """
469 tags = connection.describe_tags(aws_retry=True, LoadBalancerNames=[load_balancer_name])["TagDescriptions"]
470 if not tags:
471 return {}
472 return boto3_tag_list_to_ansible_dict(tags[0]["Tags"])
473
474
475 def lb_instance_health(
476 connection: Any, load_balancer_name: str, instances: List[Dict[str, Any]], state: str
477 ) -> Tuple[List[str], int]:
478 """
479 Describes the health status of instances associated with a specific Elastic Load Balancer (ELB).
480
481 Parameters:
482 connection (Any): The Boto3 client object for ELB.
483 load_balancer_name (str): The name of the ELB.
484 instances (List[Dict]): List of dictionaries containing instances associated with the ELB.
485 state (str): The health state to filter by (e.g., "InService", "OutOfService", "Unknown").
486
487 Returns:
488 Tuple[List, int]: A tuple containing a list of instance IDs matching state and the count of matching instances.
489 """
490 instance_states = connection.describe_instance_health(LoadBalancerName=load_balancer_name, Instances=instances).get(
491 "InstanceStates", []
492 )
493 instate = [instance["InstanceId"] for instance in instance_states if instance["State"] == state]
494 return instate, len(instate)
495
496
497 def main():
498 argument_spec = dict(
499 names=dict(default=[], type="list", elements="str"),
500 )
501 module = AnsibleAWSModule(
502 argument_spec=argument_spec,
503 supports_check_mode=True,
504 )
505
506 connection = module.client("elb", retry_decorator=AWSRetry.jittered_backoff(retries=5, delay=5))
507
508 try:
509 elbs = list_elbs(connection, module.params.get("names"))
510 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
511 module.fail_json_aws(e, msg="Failed to get load balancer information.")
512
513 module.exit_json(elbs=elbs)
514
515
516 if __name__ == "__main__":
517 main()