Debian Codegraph @

ansible_collections/amazon/aws/plugins/module_utils/elbv2.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2017 Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 import traceback
7 from copy import deepcopy
8
9 try:
10 from botocore.exceptions import BotoCoreError
11 from botocore.exceptions import ClientError
12 except ImportError:
13 pass
14
15 from typing import Any
16 from typing import Dict
17 from typing import List
18 from typing import Optional
19 from typing import Tuple
20
21 # Not intended for general re-use / re-import
22 from ._elbv2 import transformations as _transformations
23 from .ec2 import get_ec2_security_group_ids_from_names
24 from .elb_utils import AnsibleELBv2Error
25 from .elb_utils import add_listener_certificates
26 from .elb_utils import add_tags
27 from .elb_utils import convert_tg_name_to_arn
28 from .elb_utils import create_listener
29 from .elb_utils import create_load_balancer
30 from .elb_utils import create_rule
31 from .elb_utils import delete_listener
32 from .elb_utils import delete_load_balancer
33 from .elb_utils import delete_rule
34 from .elb_utils import describe_listeners
35 from .elb_utils import describe_load_balancer_attributes
36 from .elb_utils import describe_rules
37 from .elb_utils import describe_tags
38 from .elb_utils import get_elb
39 from .elb_utils import modify_listener
40 from .elb_utils import modify_load_balancer_attributes
41 from .elb_utils import modify_rule
42 from .elb_utils import remove_tags
43 from .elb_utils import set_ip_address_type
44 from .elb_utils import set_rule_priorities
45 from .elb_utils import set_security_groups
46 from .elb_utils import set_subnets
47 from .modules import AnsibleAWSModule
48 from .retries import AWSRetry
49 from .tagging import ansible_dict_to_boto3_tag_list
50 from .tagging import boto3_tag_list_to_ansible_dict
51 from .transformation import scrub_none_parameters
52 from .waiters import get_waiter
53
54 # Expose transformation functions
55 normalize_application_load_balancer = _transformations.normalize_application_load_balancer
56
57
58 def build_application_load_balancer_description(
59 connection: Any,
60 load_balancer: Dict[str, Any],
61 include_attributes: bool = True,
62 include_listeners: bool = True,
63 include_listener_rules: bool = True,
64 ) -> Dict[str, Any]:
65 """
66 Build a complete ALB description with optional attributes, listeners, and rules.
67
68 Takes a base load balancer dict from describe_load_balancers and enriches it with
69 additional information based on the include_* parameters, then normalizes the result.
70
71 Args:
72 connection: boto3 elbv2 connection
73 load_balancer: Base ALB dict from describe_load_balancers (in CamelCase boto3 format)
74 include_attributes: Whether to fetch and attach load balancer attributes
75 include_listeners: Whether to fetch and attach listeners
76 include_listener_rules: Whether to fetch and attach rules to each listener
77
78 Returns:
79 Normalized ALB dict in snake_case Ansible format
80
81 Note:
82 This function does not fetch tags. Tags should be handled separately by the caller
83 as they require a separate API call and may be added before or after normalization
84 depending on the use case.
85 """
86 # Make a copy to avoid modifying the original
87 alb = load_balancer.copy()
88
89 # Optionally add attributes (in raw boto3 format, normalization will convert them)
90 if include_attributes:
91 alb["Attributes"] = describe_load_balancer_attributes(connection, alb["LoadBalancerArn"])
92
93 # Optionally add listeners
94 if include_listeners or include_listener_rules:
95 alb["Listeners"] = describe_listeners(connection, load_balancer_arn=alb["LoadBalancerArn"])
96
97 # Optionally add rules to each listener
98 if include_listener_rules:
99 for listener in alb["Listeners"]:
100 listener["Rules"] = describe_rules(connection, ListenerArn=listener["ListenerArn"])
101
102 # Normalize the entire ALB object (convert to snake_case, sort rules, convert tags)
103 return normalize_application_load_balancer(alb)
104
105
106 def _simple_forward_config_arn(config: Dict[str, Any], parent_arn: Optional[str]) -> Optional[str]:
107 config = deepcopy(config)
108
109 stickiness = config.pop("TargetGroupStickinessConfig", {"Enabled": False})
110 # Stickiness options set, non default value
111 if stickiness != {"Enabled": False}:
112 return None
113
114 target_groups = config.pop("TargetGroups", [])
115
116 # non-default config left over, probably invalid
117 if config:
118 return None
119 # Multiple TGS, not simple
120 if len(target_groups) > 1:
121 return None
122
123 if not target_groups:
124 # with no TGs defined, but an ARN set, this is one of the minimum possible configs
125 return parent_arn
126
127 target_group = target_groups[0]
128 # We don't care about the weight with a single TG
129 target_group.pop("Weight", None)
130
131 target_group_arn = target_group.pop("TargetGroupArn", None)
132
133 # non-default config left over
134 if target_group:
135 return None
136
137 # We didn't find an ARN
138 if not (target_group_arn or parent_arn):
139 return None
140
141 # Only one
142 if not parent_arn:
143 return target_group_arn
144 if not target_group_arn:
145 return parent_arn
146
147 if parent_arn != target_group_arn:
148 return None
149
150 return target_group_arn
151
152
153 # ForwardConfig may be optional if we've got a single TargetGroupArn entry
154 def _prune_ForwardConfig(action: Dict[str, Any]) -> Dict[str, Any]:
155 """
156 Drops a redundant ForwardConfig where TargetGroupARN has already been set.
157 (So we can perform comparisons)
158 """
159 if action.get("Type", "") != "forward":
160 return action
161 if "ForwardConfig" not in action:
162 return action
163
164 parent_arn = action.get("TargetGroupArn", None)
165 arn = _simple_forward_config_arn(action["ForwardConfig"], parent_arn)
166 if not arn:
167 return action
168
169 # Remove the redundant ForwardConfig
170 newAction = action.copy()
171 del newAction["ForwardConfig"]
172 newAction["TargetGroupArn"] = arn
173 return newAction
174
175
176 # remove the client secret if UseExistingClientSecret, because aws won't return it
177 # add default values when they are not requested
178 def _prune_secret(action: Dict[str, Any]) -> Dict[str, Any]:
179 if action["Type"] != "authenticate-oidc":
180 return action
181
182 if not action["AuthenticateOidcConfig"].get("Scope", False):
183 action["AuthenticateOidcConfig"]["Scope"] = "openid"
184
185 if not action["AuthenticateOidcConfig"].get("SessionTimeout", False):
186 action["AuthenticateOidcConfig"]["SessionTimeout"] = 604800
187
188 if action["AuthenticateOidcConfig"].get("UseExistingClientSecret", False):
189 action["AuthenticateOidcConfig"].pop("ClientSecret", None)
190
191 if not action["AuthenticateOidcConfig"].get("OnUnauthenticatedRequest", False):
192 action["AuthenticateOidcConfig"]["OnUnauthenticatedRequest"] = "authenticate"
193
194 if not action["AuthenticateOidcConfig"].get("SessionCookieName", False):
195 action["AuthenticateOidcConfig"]["SessionCookieName"] = "AWSELBAuthSessionCookie"
196
197 return action
198
199
200 # while AWS api also won't return UseExistingClientSecret key
201 # it must be added, because it's requested and compared
202 def _append_use_existing_client_secretn(action: Dict[str, Any]) -> Dict[str, Any]:
203 if action["Type"] != "authenticate-oidc":
204 return action
205
206 action["AuthenticateOidcConfig"]["UseExistingClientSecret"] = True
207
208 return action
209
210
211 class ElasticLoadBalancerV2:
212 def __init__(self, connection: Any, module: AnsibleAWSModule) -> None:
213 self.connection = connection
214 self.module = module
215 self.changed = False
216 self.new_load_balancer = False
217 self.scheme = module.params.get("scheme")
218 self.name = module.params.get("name")
219 self.type: str
220 self.subnet_mappings = module.params.get("subnet_mappings")
221 self.subnets = module.params.get("subnets")
222 self.deletion_protection = module.params.get("deletion_protection")
223 self.elb_ip_addr_type = module.params.get("ip_address_type")
224 self.wait = module.params.get("wait")
225
226 if module.params.get("tags") is not None:
227 self.tags = ansible_dict_to_boto3_tag_list(module.params.get("tags"))
228 else:
229 self.tags = None
230
231 self.purge_tags = module.params.get("purge_tags")
232
233 self.elb = get_elb(connection, module, self.name)
234 self.elb_attributes = {}
235 if self.elb is not None:
236 self.elb_attributes = self.get_elb_attributes()
237 self.elb_ip_addr_type = self.get_elb_ip_address_type()
238 self.elb["tags"] = self.get_elb_tags()
239 self.check_mode = module.check_mode
240 self.exit_json = module.exit_json
241 self.fail_json = module.fail_json
242 self.fail_json_aws = module.fail_json_aws
243 self.fail_json_aws_error = module.fail_json_aws_error
244 self.params = module.params
245
246 def wait_for_ip_type(self, elb_arn: str, ip_type: str) -> None:
247 """
248 Wait for load balancer to reach 'active' status
249
250 :param elb_arn: The load balancer ARN
251 :return:
252 """
253
254 if not self.wait:
255 return
256
257 waiter_names = {
258 "ipv4": "load_balancer_ip_address_type_ipv4",
259 "dualstack": "load_balancer_ip_address_type_dualstack",
260 }
261 if ip_type not in waiter_names:
262 return
263
264 try:
265 waiter = get_waiter(self.connection, waiter_names.get(ip_type))
266 waiter.wait(LoadBalancerArns=[elb_arn])
267 except (BotoCoreError, ClientError) as e:
268 self.module.fail_json_aws(e)
269
270 def wait_for_status(self, elb_arn: str) -> None:
271 """
272 Wait for load balancer to reach 'active' status
273
274 :param elb_arn: The load balancer ARN
275 :return:
276 """
277
278 if not self.wait:
279 return
280
281 try:
282 waiter = get_waiter(self.connection, "load_balancer_available")
283 waiter.wait(LoadBalancerArns=[elb_arn])
284 except (BotoCoreError, ClientError) as e:
285 self.module.fail_json_aws(e)
286
287 def wait_for_deletion(self, elb_arn: str) -> None:
288 """
289 Wait for load balancer to reach 'active' status
290
291 :param elb_arn: The load balancer ARN
292 :return:
293 """
294
295 if self.wait:
296 try:
297 waiter = get_waiter(self.connection, "load_balancers_deleted")
298 waiter.wait(LoadBalancerArns=[elb_arn])
299 except (BotoCoreError, ClientError) as e:
300 self.module.fail_json_aws(e)
301
302 def get_elb_attributes(self) -> Dict[str, Any]:
303 """
304 Get load balancer attributes
305
306 :return:
307 """
308
309 elb_attributes = boto3_tag_list_to_ansible_dict(
310 describe_load_balancer_attributes(self.connection, self.elb["LoadBalancerArn"])
311 )
312
313 # Replace '.' with '_' in attribute key names to make it more Ansibley
314 return dict((k.replace(".", "_"), v) for k, v in elb_attributes.items())
315
316 def get_elb_ip_address_type(self) -> Optional[str]:
317 """
318 Retrieve load balancer ip address type using describe_load_balancers
319
320 :return:
321 """
322
323 return self.elb.get("IpAddressType", None)
324
325 def update_elb_attributes(self) -> None:
326 """
327 Update the elb_attributes parameter
328 :return:
329 """
330 self.elb_attributes = self.get_elb_attributes()
331
332 def get_elb_tags(self) -> Dict[str, str]:
333 """
334 Get load balancer tags
335
336 :return:
337 """
338
339 try:
340 elb_tags = describe_tags(self.connection, resource_arns=[self.elb["LoadBalancerArn"]])[0]["Tags"]
341 except AnsibleELBv2Error as e:
342 self.module.fail_json_aws(e)
343 return elb_tags
344
345 def delete_tags(self, tags_to_delete: List[str]) -> None:
346 """
347 Delete elb tags
348
349 :return:
350 """
351
352 try:
353 self.changed = remove_tags(self.connection, [self.elb["LoadBalancerArn"]], tags_to_delete)
354 except AnsibleELBv2Error as e:
355 self.module.fail_json_aws(e)
356
357 def modify_tags(self) -> None:
358 """
359 Modify elb tags
360
361 :return:
362 """
363
364 try:
365 self.changed = add_tags(self.connection, [self.elb["LoadBalancerArn"]], self.tags)
366 except AnsibleELBv2Error as e:
367 self.module.fail_json_aws(e)
368
369 def delete(self) -> None:
370 """
371 Delete elb
372 :return:
373 """
374
375 try:
376 self.changed = delete_load_balancer(self.connection, self.elb["LoadBalancerArn"])
377 except AnsibleELBv2Error as e:
378 self.module.fail_json_aws(e)
379 if self.changed:
380 self.wait_for_deletion(self.elb["LoadBalancerArn"])
381
382 def compare_subnets(self) -> bool:
383 """
384 Compare user subnets with current ELB subnets
385
386 :return: bool True if they match otherwise False
387 """
388
389 subnet_mapping_id_list = []
390 subnet_mappings = []
391
392 # Check if we're dealing with subnets or subnet_mappings
393 if self.subnets is not None:
394 # Convert subnets to subnet_mappings format for comparison
395 for subnet in self.subnets:
396 subnet_mappings.append({"SubnetId": subnet})
397
398 if self.subnet_mappings is not None:
399 # Use this directly since we're comparing as a mapping
400 subnet_mappings = self.subnet_mappings
401
402 # Build a subnet_mapping style struture of what's currently
403 # on the load balancer
404 for subnet in self.elb["AvailabilityZones"]:
405 this_mapping = {"SubnetId": subnet["SubnetId"]}
406 for address in subnet.get("LoadBalancerAddresses", []):
407 if "AllocationId" in address:
408 this_mapping["AllocationId"] = address["AllocationId"]
409 break
410
411 subnet_mapping_id_list.append(this_mapping)
412
413 return set(frozenset(mapping.items()) for mapping in subnet_mapping_id_list) == set(
414 frozenset(mapping.items()) for mapping in subnet_mappings
415 )
416
417 def modify_subnets(self) -> None:
418 """
419 Modify elb subnets to match module parameters
420 :return:
421 """
422 set_subnets(self.connection, self.elb["LoadBalancerArn"], Subnets=self.subnets)
423 self.changed = True
424
425 def update(self) -> None:
426 """
427 Update the elb from AWS
428 :return:
429 """
430
431 self.elb = get_elb(self.connection, self.module, self.module.params.get("name"))
432 self.elb["tags"] = self.get_elb_tags()
433
434 def modify_ip_address_type(self, ip_addr_type) -> None:
435 """
436 Modify ELB ip address type
437 :return:
438 """
439 if ip_addr_type is None:
440 return
441 if self.elb_ip_addr_type == ip_addr_type:
442 return
443
444 set_ip_address_type(self.connection, self.elb["LoadBalancerArn"], ip_addr_type)
445
446 self.changed = True
447 self.wait_for_ip_type(self.elb["LoadBalancerArn"], ip_addr_type)
448
449 def _elb_create_params(self) -> Dict[str, Any]:
450 # Required parameters
451 params = dict()
452 params["Name"] = self.name
453 params["Type"] = self.type
454
455 # Other parameters
456 if self.elb_ip_addr_type is not None:
457 params["IpAddressType"] = self.elb_ip_addr_type
458 if self.subnets is not None:
459 params["Subnets"] = self.subnets
460 if self.subnet_mappings is not None:
461 params["SubnetMappings"] = self.subnet_mappings
462 if self.tags:
463 params["Tags"] = self.tags
464 # Scheme isn't supported for GatewayLBs, so we won't add it here, even though we don't
465 # support them yet.
466
467 return params
468
469 def create_elb(self) -> None:
470 """
471 Create a load balancer
472 :return:
473 """
474
475 params = self._elb_create_params()
476
477 name = params.pop("Name")
478 self.elb = create_load_balancer(self.connection, name, **params)[0]
479 self.changed = True
480 self.new_load_balancer = True
481 self.wait_for_status(self.elb["LoadBalancerArn"])
482
483
484 class ApplicationLoadBalancer(ElasticLoadBalancerV2):
485 def __init__(self, connection: Any, connection_ec2: Any, module: AnsibleAWSModule) -> None:
486 """
487
488 :param connection: boto3 connection
489 :param module: Ansible module
490 """
491 super().__init__(connection, module)
492
493 self.connection_ec2 = connection_ec2
494
495 # Ansible module parameters specific to ALBs
496 self.type = "application"
497 if module.params.get("security_groups") is not None:
498 try:
499 self.security_groups = AWSRetry.jittered_backoff()(get_ec2_security_group_ids_from_names)(
500 module.params.get("security_groups"), self.connection_ec2
501 )
502 except ValueError as e:
503 self.fail_json(msg=str(e), exception=traceback.format_exc())
504 except (BotoCoreError, ClientError) as e:
505 self.fail_json_aws(e)
506 else:
507 self.security_groups = module.params.get("security_groups")
508 self.access_logs_enabled = module.params.get("access_logs_enabled")
509 self.access_logs_s3_bucket = module.params.get("access_logs_s3_bucket")
510 self.access_logs_s3_prefix = module.params.get("access_logs_s3_prefix")
511 self.idle_timeout = module.params.get("idle_timeout")
512 self.http2 = module.params.get("http2")
513 self.http_desync_mitigation_mode = module.params.get("http_desync_mitigation_mode")
514 self.http_drop_invalid_header_fields = module.params.get("http_drop_invalid_header_fields")
515 self.http_x_amzn_tls_version_and_cipher_suite = module.params.get("http_x_amzn_tls_version_and_cipher_suite")
516 self.http_xff_client_port = module.params.get("http_xff_client_port")
517 self.waf_fail_open = module.params.get("waf_fail_open")
518
519 if self.elb is not None and self.elb["Type"] != "application":
520 self.fail_json(
521 msg="The load balancer type you are trying to manage is not application. Try elb_network_lb module instead.",
522 )
523
524 def _elb_create_params(self) -> Dict[str, Any]:
525 params = super()._elb_create_params()
526
527 if self.security_groups is not None:
528 params["SecurityGroups"] = self.security_groups
529 params["Scheme"] = self.scheme
530
531 return params
532
533 def compare_elb_attributes(self) -> bool:
534 """
535 Compare user attributes with current ELB attributes
536 :return: bool True if they match otherwise False
537 """
538
539 update_attributes = []
540 if (
541 self.access_logs_enabled is not None
542 and str(self.access_logs_enabled).lower() != self.elb_attributes["access_logs_s3_enabled"]
543 ):
544 update_attributes.append({"Key": "access_logs.s3.enabled", "Value": str(self.access_logs_enabled).lower()})
545 if (
546 self.access_logs_s3_bucket is not None
547 and self.access_logs_s3_bucket != self.elb_attributes["access_logs_s3_bucket"]
548 ):
549 update_attributes.append({"Key": "access_logs.s3.bucket", "Value": self.access_logs_s3_bucket})
550 if (
551 self.access_logs_s3_prefix is not None
552 and self.access_logs_s3_prefix != self.elb_attributes["access_logs_s3_prefix"]
553 ):
554 update_attributes.append({"Key": "access_logs.s3.prefix", "Value": self.access_logs_s3_prefix})
555 if (
556 self.deletion_protection is not None
557 and str(self.deletion_protection).lower() != self.elb_attributes["deletion_protection_enabled"]
558 ):
559 update_attributes.append(
560 {"Key": "deletion_protection.enabled", "Value": str(self.deletion_protection).lower()}
561 )
562 if (
563 self.idle_timeout is not None
564 and str(self.idle_timeout) != self.elb_attributes["idle_timeout_timeout_seconds"]
565 ):
566 update_attributes.append({"Key": "idle_timeout.timeout_seconds", "Value": str(self.idle_timeout)})
567 if self.http2 is not None and str(self.http2).lower() != self.elb_attributes["routing_http2_enabled"]:
568 update_attributes.append({"Key": "routing.http2.enabled", "Value": str(self.http2).lower()})
569 if (
570 self.http_desync_mitigation_mode is not None
571 and str(self.http_desync_mitigation_mode).lower()
572 != self.elb_attributes["routing_http_desync_mitigation_mode"]
573 ):
574 update_attributes.append(
575 {"Key": "routing.http.desync_mitigation_mode", "Value": str(self.http_desync_mitigation_mode).lower()}
576 )
577 if (
578 self.http_drop_invalid_header_fields is not None
579 and str(self.http_drop_invalid_header_fields).lower()
580 != self.elb_attributes["routing_http_drop_invalid_header_fields_enabled"]
581 ):
582 update_attributes.append(
583 {
584 "Key": "routing.http.drop_invalid_header_fields.enabled",
585 "Value": str(self.http_drop_invalid_header_fields).lower(),
586 }
587 )
588 if (
589 self.http_x_amzn_tls_version_and_cipher_suite is not None
590 and str(self.http_x_amzn_tls_version_and_cipher_suite).lower()
591 != self.elb_attributes["routing_http_x_amzn_tls_version_and_cipher_suite_enabled"]
592 ):
593 update_attributes.append(
594 {
595 "Key": "routing.http.x_amzn_tls_version_and_cipher_suite.enabled",
596 "Value": str(self.http_x_amzn_tls_version_and_cipher_suite).lower(),
597 }
598 )
599 if (
600 self.http_xff_client_port is not None
601 and str(self.http_xff_client_port).lower() != self.elb_attributes["routing_http_xff_client_port_enabled"]
602 ):
603 update_attributes.append(
604 {"Key": "routing.http.xff_client_port.enabled", "Value": str(self.http_xff_client_port).lower()}
605 )
606 if (
607 self.waf_fail_open is not None
608 and str(self.waf_fail_open).lower() != self.elb_attributes["waf_fail_open_enabled"]
609 ):
610 update_attributes.append({"Key": "waf.fail_open.enabled", "Value": str(self.waf_fail_open).lower()})
611
612 return not update_attributes
613
614 def modify_elb_attributes(self) -> None:
615 """
616 Update Application ELB attributes if required
617
618 :return:
619 """
620
621 update_attributes = []
622
623 if (
624 self.access_logs_enabled is not None
625 and str(self.access_logs_enabled).lower() != self.elb_attributes["access_logs_s3_enabled"]
626 ):
627 update_attributes.append({"Key": "access_logs.s3.enabled", "Value": str(self.access_logs_enabled).lower()})
628 if (
629 self.access_logs_s3_bucket is not None
630 and self.access_logs_s3_bucket != self.elb_attributes["access_logs_s3_bucket"]
631 ):
632 update_attributes.append({"Key": "access_logs.s3.bucket", "Value": self.access_logs_s3_bucket})
633 if (
634 self.access_logs_s3_prefix is not None
635 and self.access_logs_s3_prefix != self.elb_attributes["access_logs_s3_prefix"]
636 ):
637 update_attributes.append({"Key": "access_logs.s3.prefix", "Value": self.access_logs_s3_prefix})
638 if (
639 self.deletion_protection is not None
640 and str(self.deletion_protection).lower() != self.elb_attributes["deletion_protection_enabled"]
641 ):
642 update_attributes.append(
643 {"Key": "deletion_protection.enabled", "Value": str(self.deletion_protection).lower()}
644 )
645 if (
646 self.idle_timeout is not None
647 and str(self.idle_timeout) != self.elb_attributes["idle_timeout_timeout_seconds"]
648 ):
649 update_attributes.append({"Key": "idle_timeout.timeout_seconds", "Value": str(self.idle_timeout)})
650 if self.http2 is not None and str(self.http2).lower() != self.elb_attributes["routing_http2_enabled"]:
651 update_attributes.append({"Key": "routing.http2.enabled", "Value": str(self.http2).lower()})
652 if (
653 self.http_desync_mitigation_mode is not None
654 and str(self.http_desync_mitigation_mode).lower()
655 != self.elb_attributes["routing_http_desync_mitigation_mode"]
656 ):
657 update_attributes.append(
658 {"Key": "routing.http.desync_mitigation_mode", "Value": str(self.http_desync_mitigation_mode).lower()}
659 )
660 if (
661 self.http_drop_invalid_header_fields is not None
662 and str(self.http_drop_invalid_header_fields).lower()
663 != self.elb_attributes["routing_http_drop_invalid_header_fields_enabled"]
664 ):
665 update_attributes.append(
666 {
667 "Key": "routing.http.drop_invalid_header_fields.enabled",
668 "Value": str(self.http_drop_invalid_header_fields).lower(),
669 }
670 )
671 if (
672 self.http_x_amzn_tls_version_and_cipher_suite is not None
673 and str(self.http_x_amzn_tls_version_and_cipher_suite).lower()
674 != self.elb_attributes["routing_http_x_amzn_tls_version_and_cipher_suite_enabled"]
675 ):
676 update_attributes.append(
677 {
678 "Key": "routing.http.x_amzn_tls_version_and_cipher_suite.enabled",
679 "Value": str(self.http_x_amzn_tls_version_and_cipher_suite).lower(),
680 }
681 )
682 if (
683 self.http_xff_client_port is not None
684 and str(self.http_xff_client_port).lower() != self.elb_attributes["routing_http_xff_client_port_enabled"]
685 ):
686 update_attributes.append(
687 {"Key": "routing.http.xff_client_port.enabled", "Value": str(self.http_xff_client_port).lower()}
688 )
689 if (
690 self.waf_fail_open is not None
691 and str(self.waf_fail_open).lower() != self.elb_attributes["waf_fail_open_enabled"]
692 ):
693 update_attributes.append({"Key": "waf.fail_open.enabled", "Value": str(self.waf_fail_open).lower()})
694
695 if update_attributes:
696 try:
697 modify_load_balancer_attributes(self.connection, self.elb["LoadBalancerArn"], update_attributes)
698 self.changed = True
699 except AnsibleELBv2Error as e:
700 # Something went wrong setting attributes. If this ELB was created during this task, delete it to leave a consistent state
701 if self.new_load_balancer:
702 delete_load_balancer(self.connection, self.elb["LoadBalancerArn"])
703 self.fail_json_aws(e)
704
705 def compare_security_groups(self) -> bool:
706 """
707 Compare user security groups with current ELB security groups
708
709 :return: bool True if they match otherwise False
710 """
711
712 if set(self.elb["SecurityGroups"]) != set(self.security_groups):
713 return False
714 return True
715
716 def modify_security_groups(self) -> None:
717 """
718 Modify elb security groups to match module parameters
719 :return:
720 """
721 set_security_groups(self.connection, self.elb["LoadBalancerArn"], self.security_groups)
722 self.changed = True
723
724
725 class NetworkLoadBalancer(ElasticLoadBalancerV2):
726 def __init__(self, connection: Any, connection_ec2: Any, module: AnsibleAWSModule) -> None:
727 """
728
729 :param connection: boto3 connection
730 :param module: Ansible module
731 """
732 super().__init__(connection, module)
733
734 self.connection_ec2 = connection_ec2
735
736 # Ansible module parameters specific to NLBs
737 self.type = "network"
738 self.cross_zone_load_balancing = module.params.get("cross_zone_load_balancing")
739
740 if self.elb is not None and self.elb["Type"] != "network":
741 self.fail_json(
742 msg="The load balancer type you are trying to manage is not network. Try elb_application_lb module instead.",
743 )
744
745 def _elb_create_params(self) -> Dict[str, Any]:
746 params = super()._elb_create_params()
747
748 params["Scheme"] = self.scheme
749
750 return params
751
752 def modify_elb_attributes(self) -> None:
753 """
754 Update Network ELB attributes if required
755
756 :return:
757 """
758
759 update_attributes = []
760
761 if (
762 self.cross_zone_load_balancing is not None
763 and str(self.cross_zone_load_balancing).lower() != self.elb_attributes["load_balancing_cross_zone_enabled"]
764 ):
765 update_attributes.append(
766 {"Key": "load_balancing.cross_zone.enabled", "Value": str(self.cross_zone_load_balancing).lower()}
767 )
768 if (
769 self.deletion_protection is not None
770 and str(self.deletion_protection).lower() != self.elb_attributes["deletion_protection_enabled"]
771 ):
772 update_attributes.append(
773 {"Key": "deletion_protection.enabled", "Value": str(self.deletion_protection).lower()}
774 )
775
776 if update_attributes:
777 try:
778 modify_load_balancer_attributes(self.connection, self.elb["LoadBalancerArn"], update_attributes)
779 self.changed = True
780 except AnsibleELBv2Error as e:
781 # Something went wrong setting attributes. If this ELB was created during this task, delete it to leave a consistent state
782 if self.new_load_balancer:
783 delete_load_balancer(self.connection, LoadBalancerArn=self.elb["LoadBalancerArn"])
784 self.fail_json_aws(e)
785
786 def modify_subnets(self):
787 """
788 Modify elb subnets to match module parameters (unsupported for NLB)
789 :return:
790 """
791
792 self.fail_json(msg="Modifying subnets and elastic IPs is not supported for Network Load Balancer")
793
794
795 def _compare_listener(current_listener: Dict[str, Any], new_listener: Dict[str, Any]) -> Optional[Dict[str, Any]]:
796 """
797 Compare two listeners. We do not check the port as the function is expecting that
798 the two listeners are passed with the same port value.
799
800 :param current_listener: The current listener attributes as stored into AWS
801 :param new_listener: The listener as defined into module parameters
802 :return: A dict containing the resulting update to perform on the current listener
803 """
804
805 modified_listener = {}
806
807 # Protocol
808 current_protocol = current_listener["Protocol"]
809 new_protocol = new_listener["Protocol"]
810 if current_protocol != new_protocol:
811 modified_listener["Protocol"] = new_protocol
812
813 # SslPolicy and Certificates are compared if the new listener protocol is
814 # one of the following 'HTTPS', 'TLS'
815 if new_protocol in ("HTTPS", "TLS"):
816 # SslPolicy
817 current_ssl_policy = current_listener.get("SslPolicy")
818 new_ssl_policy = new_listener.get("SslPolicy")
819 if new_ssl_policy and any(
820 (not current_ssl_policy, current_ssl_policy and current_ssl_policy != new_ssl_policy)
821 ):
822 modified_listener["SslPolicy"] = new_ssl_policy
823
824 # Certificates
825 new_certificates = new_listener.get("Certificates")
826 current_certificates = current_listener.get("Certificates")
827 if new_certificates and any(
828 (
829 not current_certificates,
830 current_certificates
831 and current_certificates[0]["CertificateArn"] != new_certificates[0]["CertificateArn"],
832 )
833 ):
834 modified_listener["Certificates"] = [{"CertificateArn": new_certificates[0]["CertificateArn"]}]
835
836 # Default actions
837 # If the lengths of the actions are the same, we'll have to verify that the
838 # contents of those actions are the same
839 current_default_actions = current_listener.get("DefaultActions")
840 new_default_actions = new_listener.get("DefaultActions")
841 if new_default_actions:
842 if current_default_actions and len(current_default_actions) == len(new_default_actions):
843 # Use the same comparison logic as _compare_rule_actions for consistency
844 if not _compare_rule_actions(current_default_actions, new_default_actions):
845 modified_listener["DefaultActions"] = new_default_actions
846 # If the action lengths are different, then replace with the new actions
847 else:
848 modified_listener["DefaultActions"] = new_default_actions
849
850 # AlpnPolicy
851 new_alpn_policy = new_listener.get("AlpnPolicy")
852 if new_alpn_policy and new_protocol == "TLS":
853 current_alpn_policy = current_listener.get("AlpnPolicy")
854 if current_listener["Protocol"] != "TLS" or (
855 current_listener["Protocol"] == "TLS"
856 and (not current_alpn_policy or current_alpn_policy[0] != new_alpn_policy[0])
857 ):
858 modified_listener["AlpnPolicy"] = new_alpn_policy
859
860 return modified_listener
861
862
863 def _group_listeners(
864 current_listeners: List[Dict[str, Any]], new_listeners: List[Dict[str, Any]]
865 ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]:
866 """
867 This function groups listeners.
868 - listeners to add: any new listener from module parameters not present of the current listeners stored in AWS resource.
869 - listeners to delete: any listener currently stored in AWS resource and not present of the module parameters.
870 - listeners to modify: any listener present in both list but with different properties.
871 The listener key is the Port value.
872
873 :param current_listeners: The current listeners stored into AWS.
874 :param new_listeners: The listeners as defined into module parameters.
875 :return: A dict containing 3 lists of listeners groups.
876 """
877 listeners_to_modify = []
878 listeners_to_delete = []
879 listeners_to_add = deepcopy(new_listeners)
880
881 # Check each current listener port to see if it's been passed to the module
882 for current_listener in current_listeners:
883 idx = next(
884 (i for i, listener in enumerate(listeners_to_add) if int(listener["Port"]) == current_listener["Port"]), -1
885 )
886 if idx == -1:
887 # The current listener is not present in new_listeners
888 listeners_to_delete.append(current_listener["ListenerArn"])
889 continue
890 # Remove what we match so that what is left can be marked as 'to be added'
891 m_listener = listeners_to_add.pop(idx)
892 # Now compare the 2 listeners with the same Port value
893 modified_listener = _compare_listener(current_listener, m_listener)
894 if modified_listener:
895 modified_listener.update({"Port": current_listener["Port"], "ListenerArn": current_listener["ListenerArn"]})
896 listeners_to_modify.append(modified_listener)
897
898 return listeners_to_add, listeners_to_modify, listeners_to_delete
899
900
901 def _prepare_listeners(
902 connection, module: AnsibleAWSModule, listeners: Optional[List[Dict[str, Any]]]
903 ) -> List[Dict[str, Any]]:
904 # This functions prepare listener defined in module parameters
905 # 1. Remove None elements from listener attribute
906 # 2. Tranform AlpnPolicy, value is set as string but API is expected a list
907 # 3. For listener defining Target group name, replaced them with the corresponding Target group ARN
908 updated_listeners = []
909 if not listeners:
910 return updated_listeners
911 target_group_mapping = {}
912 for item in listeners:
913 listener = deepcopy(item)
914 # Remove suboption argspec defaults of None from each listener
915 listener = scrub_none_parameters(listener, descend_into_lists=False)
916 # Converts 'AlpnPolicy' attribute of listener from string type to list
917 if "AlpnPolicy" in listener:
918 listener["AlpnPolicy"] = [listener["AlpnPolicy"]]
919 # If a listener DefaultAction has been passed with a Target Group Name instead of ARN,
920 # lookup the ARN and replace the name.
921 for action in listener["DefaultActions"]:
922 tg_name = action.pop("TargetGroupName", None)
923 if tg_name:
924 if tg_name not in target_group_mapping:
925 target_group_mapping[tg_name] = convert_tg_name_to_arn(connection, module, tg_name)
926 action["TargetGroupArn"] = target_group_mapping[tg_name]
927 updated_listeners.append(listener)
928 return updated_listeners
929
930
931 class ELBListeners:
932 def __init__(self, connection: Any, module: AnsibleAWSModule, elb_arn: str) -> None:
933 self.connection = connection
934 self.module = module
935 self.elb_arn = elb_arn
936 self.listeners = _prepare_listeners(connection, module, module.params.get("listeners"))
937 self.update()
938 self.purge_listeners = module.params.get("purge_listeners")
939 self.changed = False
940
941 def update(self) -> None:
942 """
943 Update the listeners for the ELB
944
945 :return:
946 """
947 self.current_listeners = describe_listeners(self.connection, load_balancer_arn=self.elb_arn)
948
949 def get_listener_arn_from_listener_port(self, listener_port: int) -> Optional[str]:
950 listener_arn = None
951 for listener in self.current_listeners:
952 if listener["Port"] == listener_port:
953 listener_arn = listener["ListenerArn"]
954 break
955 return listener_arn
956
957 def compare_listeners(self) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]:
958 """This function call the _group_listeners method and update the listeners
959 to delete depending on the value set on `purge_listeners` parameter.
960 """
961 listeners_to_add, listeners_to_modify, listeners_to_delete = _group_listeners(
962 self.current_listeners, self.listeners
963 )
964 # Prepare listeners to add/modify, Remove the key 'Rules' from attributes
965 # 'Rules' is not a valid attribute for 'create_listener' and 'modify_listener'
966 for listener in listeners_to_add + listeners_to_modify:
967 listener.pop("Rules", None)
968 # If `purge_listeners` is set to False, we empty the list of listeners to delete
969 listeners_to_delete = listeners_to_delete if self.purge_listeners else []
970 return listeners_to_add, listeners_to_modify, listeners_to_delete
971
972
973 class ELBListener:
974 def __init__(self, connection: Any, module: AnsibleAWSModule, listener: Dict[str, Any], elb_arn: str) -> None:
975 """
976
977 :param connection:
978 :param module:
979 :param listener:
980 :param elb_arn:
981 """
982
983 self.connection = connection
984 self.module = module
985 self.listener = listener
986 self.elb_arn = elb_arn
987
988 def create_listener(self) -> str:
989 return create_listener(self.connection, self.elb_arn, **self.listener)[0]["ListenerArn"]
990
991 def add(self) -> None:
992 # handle multiple certs by adding only 1 cert during listener creation and make calls to add_listener_certificates to add other certs
993 listener_certificates = self.listener.get("Certificates", [])
994 first_certificate, other_certs = [], []
995 if len(listener_certificates) > 0:
996 first_certificate, other_certs = listener_certificates[0], listener_certificates[1:]
997 self.listener["Certificates"] = [first_certificate]
998 # create listener
999 listener_arn = self.create_listener()
1000 # only one cert can be specified per call to add_listener_certificates
1001 for cert in other_certs:
1002 add_listener_certificates(self.connection, listener_arn=listener_arn, certificates=[cert])
1003
1004 def modify(self) -> None:
1005 listener_arn = self.listener.pop("ListenerArn")
1006 modify_listener(self.connection, listener_arn=listener_arn, **self.listener)
1007
1008 def delete(self) -> None:
1009 delete_listener(self.connection, self.listener)
1010
1011
1012 def _check_rule_condition(current_conditions: List[Dict[str, Any]], condition: Dict[str, Any]) -> bool:
1013 """This function checks if the condition is part of the list of current condition
1014
1015 Parameters:
1016 current_conditions: The list of conditions
1017 condition: The condition we are trying to find into the list
1018
1019 Returns:
1020 True if the condition is part of the list, False if not.
1021 """
1022
1023 condition_found = False
1024 compare_keys = (
1025 "HostHeaderConfig",
1026 "HttpHeaderConfig",
1027 "HttpRequestMethodConfig",
1028 "SourceIpConfig",
1029 "PathPatternConfig",
1030 )
1031 # Do an initial sorting of condition keys
1032 s_condition = deepcopy(condition)
1033 for key in compare_keys:
1034 if key in s_condition:
1035 s_condition[key]["Values"] = sorted(s_condition[key]["Values"])
1036 if "Values" in s_condition:
1037 s_condition["Values"] = sorted(s_condition["Values"])
1038
1039 for current_condition in current_conditions:
1040 # 'Field' should match for the conditions to be equal, compare it once at the begining
1041 if current_condition["Field"] != s_condition["Field"]:
1042 continue
1043 # host-header: current_condition includes both HostHeaderConfig AND Values while
1044 # condition can be defined with either HostHeaderConfig OR Values. Only use
1045 # HostHeaderConfig['Values'] comparison if both conditions includes HostHeaderConfig.
1046 if current_condition.get("HostHeaderConfig") and s_condition.get("HostHeaderConfig"):
1047 if sorted(current_condition["HostHeaderConfig"]["Values"]) == s_condition["HostHeaderConfig"]["Values"]:
1048 condition_found = True
1049 break
1050 elif current_condition.get("HttpHeaderConfig"):
1051 if (
1052 sorted(current_condition["HttpHeaderConfig"]["Values"]) == s_condition["HttpHeaderConfig"]["Values"]
1053 and current_condition["HttpHeaderConfig"]["HttpHeaderName"]
1054 == s_condition["HttpHeaderConfig"]["HttpHeaderName"]
1055 ):
1056 condition_found = True
1057 break
1058 elif current_condition.get("HttpRequestMethodConfig"):
1059 if (
1060 sorted(current_condition["HttpRequestMethodConfig"]["Values"])
1061 == s_condition["HttpRequestMethodConfig"]["Values"]
1062 ):
1063 condition_found = True
1064 break
1065 # path-pattern: current_condition includes both PathPatternConfig AND Values while
1066 # condition can be defined with either PathPatternConfig OR Values. Only use
1067 # PathPatternConfig['Values'] comparison if both conditions includes PathPatternConfig.
1068 elif current_condition.get("PathPatternConfig") and s_condition.get("PathPatternConfig"):
1069 if sorted(current_condition["PathPatternConfig"]["Values"]) == s_condition["PathPatternConfig"]["Values"]:
1070 condition_found = True
1071 break
1072 elif current_condition.get("QueryStringConfig"):
1073 # QueryString Values is not sorted as it is the only list of dicts (not strings).
1074 if current_condition["QueryStringConfig"]["Values"] == s_condition["QueryStringConfig"]["Values"]:
1075 condition_found = True
1076 break
1077 elif current_condition.get("SourceIpConfig"):
1078 if sorted(current_condition["SourceIpConfig"]["Values"]) == s_condition["SourceIpConfig"]["Values"]:
1079 condition_found = True
1080 break
1081 # Not all fields are required to have Values list nested within a *Config dict
1082 # e.g. fields host-header/path-pattern can directly list Values
1083 elif sorted(current_condition["Values"]) == s_condition["Values"]:
1084 condition_found = True
1085 break
1086
1087 return condition_found
1088
1089
1090 def _compare_rule_actions(current_actions: List[Dict[str, Any]], new_actions: List[Dict[str, Any]]) -> bool:
1091 """This function compares current_actions with new_actions.
1092 Bfore to the comparison, the function will set the default values for some attributes of the new actions
1093 as these are not part of the module parameters.
1094
1095 Parameters:
1096 current_actions: The current AWS rule actions
1097 new_actions: The rule actions from module parameters.
1098
1099 Returns:
1100 True if the current_actions and new_actions are equal, False if not.
1101 """
1102 # If the lengths of the actions are the same, we'll have to verify that the
1103 # contents of those actions are the same
1104 if len(current_actions) != len(new_actions):
1105 return False
1106
1107 # if actions have just one element, compare the contents and then update if
1108 # they're different
1109 current_actions_sorted = _transformations._sort_actions(current_actions)
1110 new_actions_sorted = _transformations._sort_actions(deepcopy(new_actions))
1111
1112 new_current_actions_sorted = [_append_use_existing_client_secretn(i) for i in current_actions_sorted]
1113 new_actions_sorted_no_secret = [_prune_secret(i) for i in new_actions_sorted]
1114
1115 return [_prune_ForwardConfig(i) for i in new_current_actions_sorted] == [
1116 _prune_ForwardConfig(i) for i in new_actions_sorted_no_secret
1117 ]
1118
1119
1120 def _compare_rule(current_rule: Dict[str, Any], new_rule: Dict[str, Any]) -> Dict[str, Any]:
1121 """This function compares rule_a with rule_b and returns differences
1122 between the two rules as a dictionnary
1123
1124 Parameters:
1125 current_rule: The current listener rule stored in AWS.
1126 new_rule: The new listener rule.
1127
1128 Returns:
1129 A dictionnary containing the modified attributes.
1130 """
1131
1132 modified_rule = {}
1133
1134 # Priority
1135 if int(current_rule["Priority"]) != int(new_rule["Priority"]):
1136 modified_rule["Priority"] = new_rule["Priority"]
1137
1138 # Actions
1139 actions_match = _compare_rule_actions(current_rule["Actions"], new_rule["Actions"])
1140 if not actions_match:
1141 modified_rule["Actions"] = new_rule["Actions"]
1142
1143 # Conditions
1144 modified_conditions = [
1145 c for c in new_rule["Conditions"] if not _check_rule_condition(current_rule["Conditions"], c)
1146 ]
1147 if modified_conditions:
1148 modified_rule["Conditions"] = modified_conditions
1149
1150 return modified_rule
1151
1152
1153 def _group_rules(
1154 current_rules: List[Dict[str, Any]], rules: List[Dict[str, Any]]
1155 ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]], List[str]]:
1156 """This function compares listener rules from AWS with module provided listener rules and a matrix with the
1157 following:
1158 - Rules to add: a rule is added when it is part of the module parameters and not currently stored on AWS
1159 - Rules to set priority: Any rule with unchanged attributes but with a different priority value
1160 - Rules to modify: Any rule on which one the following attribute has changed 'Actions', 'Conditions'
1161 - Rules to delete: Any rule currently stored on AWS and not defined in module parameters.
1162
1163 Parameters:
1164 current_rules: The current listener rules stored in AWS.
1165 rules: The new listener rules.
1166
1167 Returns:
1168 A tuple with a list of rules to add, a list of rules to set priority, a list of rules to modify and a list of rules to delete
1169 """
1170
1171 rules_to_modify = []
1172 rules_to_delete = []
1173 rules_to_add = deepcopy(rules)
1174 rules_to_set_priority = []
1175
1176 # List rules to update priority, 'Actions' and 'Conditions' remain the same
1177 # only the 'Priority' has changed
1178 _current_rules = deepcopy(current_rules)
1179 remaining_rules = []
1180 while _current_rules:
1181 current_rule = _current_rules.pop(0)
1182 # Skip the default rule, this one can't be modified
1183 if current_rule.get("IsDefault", False):
1184 continue
1185 to_keep = True
1186 for new_rule in rules_to_add:
1187 modified_rule = _compare_rule(current_rule, new_rule)
1188 if not modified_rule:
1189 # The current rule has been passed with the same properties to the module
1190 # Remove it for later comparison
1191 rules_to_add.remove(new_rule)
1192 to_keep = False
1193 break
1194 if modified_rule and list(modified_rule.keys()) == ["Priority"]:
1195 # if only the Priority has changed
1196 modified_rule["Priority"] = int(new_rule["Priority"])
1197 modified_rule["RuleArn"] = current_rule["RuleArn"]
1198
1199 rules_to_set_priority.append(modified_rule)
1200 to_keep = False
1201 rules_to_add.remove(new_rule)
1202 break
1203 if to_keep:
1204 remaining_rules.append(current_rule)
1205
1206 for current_rule in remaining_rules:
1207 current_rule_passed_to_module = False
1208 for new_rule in rules_to_add:
1209 if current_rule["Priority"] == str(new_rule["Priority"]):
1210 current_rule_passed_to_module = True
1211 # Remove what we match so that what is left can be marked as 'to be added'
1212 rules_to_add.remove(new_rule)
1213 modified_rule = _compare_rule(current_rule, new_rule)
1214 if modified_rule:
1215 modified_rule["Priority"] = int(current_rule["Priority"])
1216 modified_rule["RuleArn"] = current_rule["RuleArn"]
1217 modified_rule["Actions"] = new_rule["Actions"]
1218 modified_rule["Conditions"] = new_rule["Conditions"]
1219 # You cannot both specify a client secret and set UseExistingClientSecret to true
1220 for action in modified_rule.get("Actions", []):
1221 if action.get("AuthenticateOidcConfig", {}).get("ClientSecret", False):
1222 action["AuthenticateOidcConfig"]["UseExistingClientSecret"] = False
1223 rules_to_modify.append(modified_rule)
1224 break
1225
1226 # If the current rule was not matched against passed rules, mark for removal
1227 if not current_rule_passed_to_module and not current_rule.get("IsDefault", False):
1228 rules_to_delete.append(current_rule["RuleArn"])
1229
1230 return rules_to_add, rules_to_set_priority, rules_to_modify, rules_to_delete
1231
1232
1233 class ELBListenerRules:
1234 def __init__(
1235 self,
1236 connection: Any,
1237 module: AnsibleAWSModule,
1238 listener_arn: Optional[str],
1239 listener_rules: List[Dict[str, Any]],
1240 ) -> None:
1241 self.connection = connection
1242 self.module = module
1243 self.rules = self._ensure_rules_action_has_arn(listener_rules)
1244 self.changed = False
1245
1246 self.listener_arn = listener_arn
1247 self.current_rules = describe_rules(self.connection, ListenerArn=listener_arn)
1248
1249 def _ensure_rules_action_has_arn(self, rules: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
1250 """
1251 If a rule Action has been passed with a Target Group Name instead of ARN, lookup the ARN and
1252 replace the name.
1253
1254 :param rules: a list of rule dicts
1255 :return: the same list of dicts ensuring that each rule Actions dict has TargetGroupArn key. If a TargetGroupName key exists, it is removed.
1256 """
1257
1258 fixed_rules = []
1259 for rule in rules:
1260 fixed_actions = []
1261 for action in rule["Actions"]:
1262 if "TargetGroupName" in action:
1263 action["TargetGroupArn"] = convert_tg_name_to_arn(
1264 self.connection, self.module, action["TargetGroupName"]
1265 )
1266 del action["TargetGroupName"]
1267 fixed_actions.append(action)
1268 rule["Actions"] = fixed_actions
1269 fixed_rules.append(rule)
1270
1271 return fixed_rules
1272
1273 def compare_rules(
1274 self,
1275 ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]], List[str]]:
1276 """This function creates the rule matrix (to add, to set priority, to modify, to delete)
1277 and prepare them to be ready for AWS API call.
1278
1279 Returns:
1280 A tuple with a list of rules to add, a list of rules to set priority, a list of rules to modify and a list of rules to delete
1281 """
1282 rules_to_add, rules_to_set_priority, rules_to_modify, rules_to_delete = _group_rules(
1283 self.current_rules, self.rules
1284 )
1285
1286 # Prepare Rule to create (to add)
1287 # For rules to create 'UseExistingClientSecret' should be set to False, The 'Priority' need
1288 # To be an int value and the ListenerArn need to be set
1289 for rule in rules_to_add:
1290 for action in rule.get("Actions", []):
1291 if action.get("AuthenticateOidcConfig", {}).get("UseExistingClientSecret", False):
1292 action["AuthenticateOidcConfig"]["UseExistingClientSecret"] = False
1293 rule["ListenerArn"] = self.listener_arn
1294 rule["Priority"] = int(rule["Priority"])
1295
1296 # Prepare Rule to modify: We need to remove the 'Priority' key
1297 for rule in rules_to_modify:
1298 del rule["Priority"]
1299
1300 return rules_to_add, rules_to_set_priority, rules_to_modify, rules_to_delete
1301
1302
1303 class ELBListenerRule:
1304 def __init__(self, connection, module) -> None:
1305 self.connection = connection
1306 self.module = module
1307
1308 def create(self, rule: Dict[str, Any]) -> None:
1309 """
1310 Create a listener rule
1311
1312 :return:
1313 """
1314 listener_arn = rule.pop("ListenerArn")
1315 conditions = rule.pop("Conditions")
1316 priority = rule.pop("Priority")
1317 actions = rule.pop("Actions")
1318 tags = rule.pop("Tags", None)
1319 create_rule(
1320 self.connection,
1321 listener_arn=listener_arn,
1322 conditions=conditions,
1323 actions=actions,
1324 tags=tags,
1325 priority=priority,
1326 )
1327
1328 def modify(self, rule: Dict[str, Any]) -> None:
1329 """
1330 Modify a listener rule
1331
1332 :return:
1333 """
1334 rule_arn = rule.pop("RuleArn")
1335 modify_rule(self.connection, rule_arn=rule_arn, **rule)
1336
1337 def delete(self, rule_arn: str) -> None:
1338 """
1339 Delete a listener rule
1340
1341 :return:
1342 """
1343 delete_rule(self.connection, rule_arn)
1344
1345 def set_rule_priorities(self, rules: List[Dict[str, Any]]) -> None:
1346 """
1347 Sets the priorities of the specified rules.
1348
1349 :return:
1350 """
1351 set_rule_priorities(
1352 self.connection, [{"RuleArn": rule["RuleArn"], "Priority": rule["Priority"]} for rule in rules]
1353 )
1354
1355 def process_rules(
1356 self,
1357 rules_to_create: List[Dict[str, Any]],
1358 rules_to_set_priority: List[Dict[str, Any]],
1359 rules_to_modify: List[Dict[str, Any]],
1360 rules_to_delete: List[str],
1361 ) -> bool:
1362 changed = False
1363 if rules_to_set_priority:
1364 self.set_rule_priorities(rules_to_set_priority)
1365 changed = True
1366 if self.module.params["purge_rules"]:
1367 for arn in rules_to_delete:
1368 self.delete(arn)
1369 changed = True
1370 for rule in rules_to_create:
1371 self.create(rule)
1372 changed = True
1373 for rule in rules_to_modify:
1374 self.modify(rule)
1375 changed = True
1376 return changed