Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/elb_application_lb.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_application_lb
10 version_added: 5.0.0
11 short_description: Manage an Application Load Balancer
12 description:
13 - Manage an AWS Application Elastic Load Balancer. See U(https://aws.amazon.com/blogs/aws/new-aws-application-load-balancer/) for details.
14 - This module was originally added to C(community.aws) in release 1.0.0.
15 author:
16 - "Rob White (@wimnat)"
17 options:
18 access_logs_enabled:
19 description:
20 - Whether or not to enable access logs.
21 - When set, O(access_logs_s3_bucket) must also be set.
22 type: bool
23 access_logs_s3_bucket:
24 description:
25 - The name of the S3 bucket for the access logs.
26 - The bucket must exist in the same
27 region as the load balancer and have a bucket policy that grants Elastic Load Balancing permission to write to the bucket.
28 - Required if access logs in Amazon S3 are enabled.
29 - When set, O(access_logs_enabled) must also be set.
30 type: str
31 access_logs_s3_prefix:
32 description:
33 - The prefix for the log location in the S3 bucket.
34 - If you don't specify a prefix, the access logs are stored in the root of the bucket.
35 - Cannot begin or end with a slash.
36 type: str
37 deletion_protection:
38 description:
39 - Indicates whether deletion protection for the ALB is enabled.
40 - Defaults to V(false).
41 type: bool
42 http2:
43 description:
44 - Indicates whether to enable HTTP2 routing.
45 - Defaults to V(True).
46 type: bool
47 http_desync_mitigation_mode:
48 description:
49 - Determines how the load balancer handles requests that might pose a security risk to an application.
50 - Defaults to V(defensive).
51 type: str
52 choices: ['monitor', 'defensive', 'strictest']
53 version_added: 3.2.0
54 version_added_collection: community.aws
55 http_drop_invalid_header_fields:
56 description:
57 - Indicates whether HTTP headers with invalid header fields are removed by the load balancer V(true) or routed to targets V(false).
58 - Defaults to V(false).
59 type: bool
60 version_added: 3.2.0
61 version_added_collection: community.aws
62 http_x_amzn_tls_version_and_cipher_suite:
63 description:
64 - Indicates whether the two headers are added to the client request before sending it to the target.
65 - Defaults to V(false).
66 type: bool
67 version_added: 3.2.0
68 version_added_collection: community.aws
69 http_xff_client_port:
70 description:
71 - Indicates whether the X-Forwarded-For header should preserve the source port that the client used to connect to the load balancer.
72 - Defaults to V(false).
73 type: bool
74 version_added: 3.2.0
75 version_added_collection: community.aws
76 idle_timeout:
77 description:
78 - The number of seconds to wait before an idle connection is closed.
79 type: int
80 listeners:
81 description:
82 - A list of dicts containing listeners to attach to the ALB. See examples for detail of the dict required. Note that listener keys
83 are CamelCased.
84 type: list
85 elements: dict
86 suboptions:
87 Port:
88 description: The port on which the load balancer is listening.
89 required: true
90 type: int
91 Protocol:
92 description: The protocol for connections from clients to the load balancer.
93 required: true
94 type: str
95 Certificates:
96 description: The SSL server certificate.
97 type: list
98 elements: dict
99 suboptions:
100 CertificateArn:
101 description: The Amazon Resource Name (ARN) of the certificate.
102 type: str
103 SslPolicy:
104 description: The security policy that defines which ciphers and protocols are supported.
105 type: str
106 DefaultActions:
107 description: The default actions for the listener.
108 required: true
109 type: list
110 elements: dict
111 suboptions:
112 Type:
113 description: The type of action.
114 type: str
115 TargetGroupArn:
116 description:
117 - The Amazon Resource Name (ARN) of the target group.
118 - Mutually exclusive with O(listeners.DefaultActions.TargetGroupName).
119 type: str
120 TargetGroupName:
121 description:
122 - The name of the target group.
123 - Mutually exclusive with O(listeners.DefaultActions.TargetGroupArn).
124 Rules:
125 type: list
126 elements: dict
127 description:
128 - A list of ALB Listener Rules.
129 - 'For the complete documentation of possible Conditions and Actions please see the boto3 documentation:'
130 - 'U(https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.create_rule)'
131 - >
132 Keep in mind that AWS uses default values for parameters that are not requested. For example for V(Scope)
133 and V(SessionTimeout) when the action type is V(authenticate-oidc).
134 suboptions:
135 Conditions:
136 type: list
137 description: Conditions which must be met for the actions to be applied.
138 elements: dict
139 Priority:
140 type: int
141 description: The rule priority.
142 Actions:
143 type: list
144 description: Actions to apply if all of the rule's conditions are met.
145 elements: dict
146 name:
147 description:
148 - The name of the load balancer. This name must be unique within your AWS account, can have a maximum of 32 characters, must contain only alphanumeric
149 characters or hyphens, and must not begin or end with a hyphen.
150 required: true
151 type: str
152 purge_listeners:
153 description:
154 - If V(true), existing listeners will be purged from the ALB to match exactly what is defined by O(listeners) parameter.
155 - If the O(listeners) parameter is not set then listeners will not be modified.
156 default: true
157 type: bool
158 subnets:
159 description:
160 - A list of the IDs of the subnets to attach to the load balancer. You can specify only one subnet per Availability Zone. You must specify subnets from
161 at least two Availability Zones.
162 - Required if O(state=present).
163 type: list
164 elements: str
165 security_groups:
166 description:
167 - A list of the names or IDs of the security groups to assign to the load balancer.
168 - Required if O(state=present).
169 - If V([]), the VPC's default security group will be used.
170 type: list
171 elements: str
172 scheme:
173 description:
174 - Internet-facing or internal load balancer. An ALB scheme can not be modified after creation.
175 default: internet-facing
176 choices: [ 'internet-facing', 'internal' ]
177 type: str
178 state:
179 description:
180 - Create or destroy the load balancer.
181 default: present
182 choices: [ 'present', 'absent' ]
183 type: str
184 wait:
185 description:
186 - Wait for the load balancer to have a state of 'active' before completing. A status check is
187 performed every 15 seconds until a successful state is reached. An error is returned after 40 failed checks.
188 default: false
189 type: bool
190 wait_timeout:
191 description:
192 - The time in seconds to use in conjunction with O(wait).
193 type: int
194 purge_rules:
195 description:
196 - When set to V(false), keep the existing load balancer rules in place. Will modify and add, but will not delete.
197 default: true
198 type: bool
199 ip_address_type:
200 description:
201 - Sets the type of IP addresses used by the subnets of the specified Application Load Balancer.
202 choices: [ 'ipv4', 'dualstack' ]
203 type: str
204 waf_fail_open:
205 description:
206 - Indicates whether to allow a AWS WAF-enabled load balancer to route requests to targets if it is unable to forward the request to AWS WAF.
207 - Defaults to V(false).
208 type: bool
209 version_added: 3.2.0
210 version_added_collection: community.aws
211 extends_documentation_fragment:
212 - amazon.aws.common.modules
213 - amazon.aws.region.modules
214 - amazon.aws.tags
215 - amazon.aws.boto3
216
217 notes:
218 - Listeners are matched based on port. If a listener's port is changed then a new listener will be created.
219 - Listener rules are matched based on priority. If a rule's priority is changed then a new rule will be created.
220 """
221
222 EXAMPLES = r"""
223 # Note: These examples do not set authentication details, see the AWS Guide for details.
224
225 # Create an ALB and attach a listener
226 - amazon.aws.elb_application_lb:
227 name: myalb
228 security_groups:
229 - sg-12345678
230 - my-sec-group
231 subnets:
232 - subnet-012345678
233 - subnet-abcdef000
234 listeners:
235 - Protocol: HTTP # Required. The protocol for connections from clients to the load balancer (HTTP or HTTPS) (case-sensitive).
236 Port: 80 # Required. The port on which the load balancer is listening.
237 # The security policy that defines which ciphers and protocols are supported. The default is the current predefined security policy.
238 SslPolicy: ELBSecurityPolicy-2015-05
239 Certificates: # The ARN of the certificate
240 - CertificateArn: arn:aws:iam::123456789012:server-certificate/test.domain.com
241 DefaultActions:
242 - Type: forward # Required.
243 TargetGroupName: # Required. The name of the target group
244 state: present
245
246 # Create an ALB and attach a listener with logging enabled
247 - amazon.aws.elb_application_lb:
248 access_logs_enabled: true
249 access_logs_s3_bucket: mybucket
250 access_logs_s3_prefix: "logs"
251 name: myalb
252 security_groups:
253 - sg-12345678
254 - my-sec-group
255 subnets:
256 - subnet-012345678
257 - subnet-abcdef000
258 listeners:
259 - Protocol: HTTP # Required. The protocol for connections from clients to the load balancer (HTTP or HTTPS) (case-sensitive).
260 Port: 80 # Required. The port on which the load balancer is listening.
261 # The security policy that defines which ciphers and protocols are supported. The default is the current predefined security policy.
262 SslPolicy: ELBSecurityPolicy-2015-05
263 Certificates: # The ARN of the certificate
264 - CertificateArn: arn:aws:iam::123456789012:server-certificate/test.domain.com
265 DefaultActions:
266 - Type: forward # Required.
267 TargetGroupName: # Required. The name of the target group
268 state: present
269
270 # Create an ALB with listeners and rules
271 - amazon.aws.elb_application_lb:
272 name: test-alb
273 subnets:
274 - subnet-12345678
275 - subnet-87654321
276 security_groups:
277 - sg-12345678
278 scheme: internal
279 listeners:
280 - Protocol: HTTPS
281 Port: 443
282 DefaultActions:
283 - Type: forward
284 TargetGroupName: test-target-group
285 Certificates:
286 - CertificateArn: arn:aws:iam::123456789012:server-certificate/test.domain.com
287 SslPolicy: ELBSecurityPolicy-2015-05
288 Rules:
289 - Conditions:
290 - Field: path-pattern
291 Values:
292 - '/test'
293 Priority: '1'
294 Actions:
295 - TargetGroupName: test-target-group
296 Type: forward
297 - Conditions:
298 - Field: path-pattern
299 Values:
300 - "/redirect-path/*"
301 Priority: '2'
302 Actions:
303 - Type: redirect
304 RedirectConfig:
305 Host: "#{host}"
306 Path: "/example/redir" # or /#{path}
307 Port: "#{port}"
308 Protocol: "#{protocol}"
309 Query: "#{query}"
310 StatusCode: "HTTP_302" # or HTTP_301
311 - Conditions:
312 - Field: path-pattern
313 Values:
314 - "/fixed-response-path/"
315 Priority: '3'
316 Actions:
317 - Type: fixed-response
318 FixedResponseConfig:
319 ContentType: "text/plain"
320 MessageBody: "This is the page you're looking for"
321 StatusCode: "200"
322 - Conditions:
323 - Field: host-header
324 Values:
325 - "hostname.domain.com"
326 - "alternate.domain.com"
327 Priority: '4'
328 Actions:
329 - TargetGroupName: test-target-group
330 Type: forward
331 state: present
332
333 # Create an ALB with a listener having multiple listener certificates
334 - amazon.aws.elb_application_lb:
335 name: myalb
336 security_groups:
337 - sg-12345678
338 - my-sec-group
339 subnets:
340 - subnet-012345678
341 - subnet-abcdef000
342 listeners:
343 - Protocol: HTTP # Required. The protocol for connections from clients to the load balancer (HTTP or HTTPS) (case-sensitive).
344 Port: 80 # Required. The port on which the load balancer is listening.
345 # The security policy that defines which ciphers and protocols are supported. The default is the current predefined security policy.
346 SslPolicy: ELBSecurityPolicy-2015-05
347 Certificates: # The ARN of the certificate (first certificate in the list will be set as default certificate)
348 - CertificateArn: arn:aws:iam::123456789012:server-certificate/test.domain.com
349 - CertificateArn: arn:aws:iam::123456789012:server-certificate/secondtest.domain.com
350 - CertificateArn: arn:aws:iam::123456789012:server-certificate/thirdtest.domain.com
351 DefaultActions:
352 - Type: forward # Required.
353 TargetGroupName: # Required. The name of the target group
354 state: present
355
356 # Remove an ALB
357 - amazon.aws.elb_application_lb:
358 name: myalb
359 state: absent
360 """
361
362 RETURN = r"""
363 access_logs_s3_bucket:
364 description: The name of the S3 bucket for the access logs.
365 returned: when O(state=present)
366 type: str
367 sample: "mys3bucket"
368 access_logs_s3_enabled:
369 description: Indicates whether access logs stored in Amazon S3 are enabled.
370 returned: when O(state=present)
371 type: str
372 sample: "true"
373 access_logs_s3_prefix:
374 description: The prefix for the location in the S3 bucket.
375 returned: when O(state=present)
376 type: str
377 sample: "my/logs"
378 availability_zones:
379 description: The Availability Zones for the load balancer.
380 returned: when O(state=present)
381 type: list
382 elements: dict
383 contains:
384 load_balancer_addresses:
385 description: Information about static IP addresses for a load balancer.
386 returned: when O(state=present)
387 type: list
388 elements: dict
389 contains:
390 ip_address:
391 description: The static IP address.
392 returned: when O(state=present)
393 type: str
394 allocation_id:
395 description: The allocation ID of the Elastic IP address for an internal-facing load balancer.
396 returned: when O(state=present)
397 type: str
398 private_ipv4_address:
399 returned: when O(state=present)
400 description: The private IPv4 address for an internal load balancer.
401 type: str
402 ipv6_address:
403 returned: when O(state=present)
404 description: The IPv6 address.
405 type: str
406 subnet_id:
407 description: The ID of the subnet.
408 returned: when O(state=present)
409 type: str
410 zone_name:
411 description: The name of the Availability Zone.
412 returned: when O(state=present)
413 type: str
414 sample: [{ "load_balancer_addresses": [], "subnet_id": "subnet-aabbccddff", "zone_name": "ap-southeast-2a" }]
415 canonical_hosted_zone_id:
416 description: The ID of the Amazon Route 53 hosted zone associated with the load balancer.
417 returned: when O(state=present)
418 type: str
419 sample: "ABCDEF12345678"
420 changed:
421 description: Whether an ALB was created/updated/deleted.
422 returned: always
423 type: bool
424 sample: true
425 created_time:
426 description: The date and time the load balancer was created.
427 returned: when O(state=present)
428 type: str
429 sample: "2015-02-12T02:14:02+00:00"
430 client_keep_alive_seconds:
431 description: The client keep alive value, in seconds.
432 returned: when O(state=present)
433 type: str
434 sample: "3600"
435 connection_logs_s3_bucket:
436 description: The name of the S3 bucket for the connection logs.
437 returned: when O(state=present)
438 type: str
439 sample: ""
440 connection_logs_s3_enabled:
441 description: Indicates whether connection logs are enabled.
442 returned: when O(state=present)
443 type: str
444 sample: "false"
445 connection_logs_s3_prefix:
446 description: The prefix for the location in the S3 bucket for the connection logs.
447 returned: when O(state=present)
448 type: str
449 sample: ""
450 deletion_protection_enabled:
451 description: Indicates whether deletion protection is enabled.
452 returned: when O(state=present)
453 type: str
454 sample: "true"
455 dns_name:
456 description: The public DNS name of the load balancer.
457 returned: when O(state=present)
458 type: str
459 sample: "internal-my-elb-123456789.ap-southeast-2.elb.amazonaws.com"
460 idle_timeout_timeout_seconds:
461 description: The idle timeout value, in seconds.
462 returned: when O(state=present)
463 type: str
464 sample: "60"
465 ip_address_type:
466 description: The type of IP addresses used by the subnets for the load balancer.
467 returned: when O(state=present)
468 type: str
469 sample: "ipv4"
470 ipv6_deny_all_igw_traffic:
471 description: Locks internet gateway (IGW) access to the load balancer.
472 returned: when O(state=present)
473 type: str
474 sample: "false"
475 listeners:
476 description: Information about the listeners.
477 returned: when O(state=present)
478 type: list
479 elements: dict
480 contains:
481 listener_arn:
482 description: The Amazon Resource Name (ARN) of the listener.
483 returned: when O(state=present)
484 type: str
485 sample: "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/alb-test-169eb5ba/1659336d4100d496/8367c4262cc1d0cc"
486 load_balancer_arn:
487 description: The Amazon Resource Name (ARN) of the load balancer.
488 returned: when O(state=present)
489 type: str
490 sample: "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/alb-test-169eb5ba/1659336d4100d496"
491 port:
492 description: The port on which the load balancer is listening.
493 returned: when O(state=present)
494 type: int
495 sample: 80
496 protocol:
497 description: The protocol for connections from clients to the load balancer.
498 returned: when O(state=present)
499 type: str
500 sample: "HTTPS"
501 rules:
502 description: List of listener rules.
503 returned: when O(state=present)
504 type: list
505 elements: dict
506 contains:
507 rule_arn:
508 description: The Amazon Resource Name (ARN) of the rule.
509 returned: when O(state=present)
510 type: str
511 sample: ""
512 priority:
513 description: The priority.
514 returned: when O(state=present)
515 type: str
516 sample: "default"
517 is_default:
518 description: Indicates whether this is the default rule.
519 returned: when O(state=present)
520 type: bool
521 sample: false
522 conditions:
523 description: The conditions.
524 returned: when O(state=present)
525 type: list
526 sample: []
527 actions:
528 description: The actions.
529 returned: when O(state=present)
530 type: list
531 elements: dict
532 contains:
533 type:
534 description: The type of action.
535 returned: when O(state=present)
536 type: str
537 target_group_arn:
538 description: The Amazon Resource Name (ARN) of the target group.
539 returned: when O(state=present)
540 type: str
541 forward_config:
542 description: Information for creating an action that distributes requests among one or more target groups.
543 returned: when O(state=present)
544 type: dict
545 contains:
546 target_groups:
547 description: The target groups.
548 returned: when O(state=present)
549 type: dict
550 contains:
551 target_group_arn:
552 description: The Amazon Resource Name (ARN) of the target group.
553 returned: when O(state=present)
554 type: str
555 weight:
556 description: The weight.
557 returned: when O(state=present)
558 type: int
559 target_group_stickiness_config:
560 description: The target group stickiness for the rule.
561 returned: when O(state=present)
562 type: dict
563 contains:
564 enabled:
565 description: Indicates whether target group stickiness is enabled.
566 returned: when O(state=present)
567 type: bool
568 sample: [
569 {
570 "forward_config": {
571 "target_group_stickiness_config": {
572 "enabled": false
573 },
574 "target_groups": [
575 {
576 "target_group_arn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/alb-test-169eb/09ba111f8079fb83",
577 "weight": 1
578 }
579 ]
580 },
581 "target_group_arn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/alb-test-169eb/09ba111f8079fb83",
582 "type": "forward"
583 }
584 ]
585 certificates:
586 description: The SSL server certificate.
587 returned: when O(state=present)
588 type: list
589 elements: dict
590 contains:
591 certificate_arn:
592 description: The Amazon Resource Name (ARN) of the certificate.
593 returned: when O(state=present)
594 type: str
595 sample: "arn:aws:acm:us-east-1:123456789012:certificate/28d2f3d9-cb2f-4033-a9aa-e75e704125a2"
596 ssl_policy:
597 description: The security policy that defines which ciphers and protocols are supported.
598 returned: when O(state=present)
599 type: str
600 sample: "ELBSecurityPolicy-2016-08"
601 default_actions:
602 description: The default actions for the listener.
603 returned: when O(state=present)
604 type: str
605 contains:
606 type:
607 description: The type of action.
608 returned: when O(state=present)
609 type: str
610 sample: "forward"
611 target_group_arn:
612 description: The Amazon Resource Name (ARN) of the target group.
613 returned: when O(state=present)
614 type: str
615 sample: "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/alb-test-169eb5ba/09ba111f8079fb83"
616 forward_config:
617 description: Information for creating an action that distributes requests among one or more target groups.
618 returned: when O(state=present)
619 type: dict
620 contains:
621 target_groups:
622 description: The target groups.
623 returned: when O(state=present)
624 type: dict
625 contains:
626 target_group_arn:
627 description: The Amazon Resource Name (ARN) of the target group.
628 returned: when O(state=present)
629 type: str
630 weight:
631 description: The weight.
632 returned: when O(state=present)
633 type: int
634 target_group_stickiness_config:
635 description: The target group stickiness for the rule.
636 returned: when O(state=present)
637 type: dict
638 contains:
639 enabled:
640 description: Indicates whether target group stickiness is enabled.
641 returned: when O(state=present)
642 type: bool
643 sample: [
644 {
645 "forward_config": {
646 "target_group_stickiness_config": {
647 "enabled": false
648 },
649 "target_groups": [
650 {
651 "target_group_arn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/alb-test-2-98b7f374/bf43c68602c51c02",
652 "weight": 1
653 }
654 ]
655 },
656 "target_group_arn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/alb-test-2-98b7f374/bf43c68602c51c02",
657 "type": "forward"
658 }
659 ]
660 load_balancer_arn:
661 description: The Amazon Resource Name (ARN) of the load balancer.
662 returned: when O(state=present)
663 type: str
664 sample: "arn:aws:elasticloadbalancing:ap-southeast-2:123456789012:loadbalancer/app/my-alb/001122334455"
665 load_balancer_name:
666 description: The name of the load balancer.
667 returned: when O(state=present)
668 type: str
669 sample: "my-alb"
670 load_balancing_cross_zone_enabled:
671 description: Indicates whether cross-zone load balancing is enabled.
672 returned: when O(state=present)
673 type: str
674 sample: "true"
675 routing_http2_enabled:
676 description: Indicates whether HTTP/2 is enabled.
677 returned: when O(state=present)
678 type: str
679 sample: "true"
680 routing_http_desync_mitigation_mode:
681 description: Determines how the load balancer handles requests that might pose a security risk to an application.
682 returned: when O(state=present)
683 type: str
684 sample: "defensive"
685 routing_http_drop_invalid_header_fields_enabled:
686 description: Indicates whether HTTP headers with invalid header fields are removed by the load balancer (true) or routed to targets (false).
687 returned: when O(state=present)
688 type: str
689 sample: "false"
690 routing_http_preserve_host_header_enabled:
691 description:
692 - Indicates whether the Application Load Balancer should preserve the Host header in the HTTP request and send it to the target without any change.
693 returned: when O(state=present)
694 type: str
695 sample: "false"
696 routing_http_x_amzn_tls_version_and_cipher_suite_enabled:
697 description: Indicates whether the two headers are added to the client request before sending it to the target.
698 returned: when O(state=present)
699 type: str
700 sample: "false"
701 routing_http_xff_client_port_enabled:
702 description: Indicates whether the X-Forwarded-For header should preserve the source port that the client used to connect to the load balancer.
703 returned: when O(state=present)
704 type: str
705 sample: "false"
706 routing_http_xff_header_processing_mode:
707 description:
708 - Enables you to modify, preserve, or remove the X-Forwarded-For header in the HTTP request before the Application Load Balancer sends the
709 request to the target.
710 returned: when O(state=present)
711 type: str
712 sample: "append"
713 scheme:
714 description: Internet-facing or internal load balancer.
715 returned: when O(state=present)
716 type: str
717 sample: "internal"
718 security_groups:
719 description: The IDs of the security groups for the load balancer.
720 returned: when O(state=present)
721 type: list
722 elements: str
723 sample: ["sg-0011223344"]
724 state:
725 description: The state of the load balancer.
726 returned: when O(state=present)
727 type: dict
728 contains:
729 code:
730 description: The state code.
731 type: str
732 reason:
733 description: A description of the state.
734 returned: when available
735 type: str
736 sample: {"code": "active"}
737 tags:
738 description: The tags attached to the load balancer.
739 returned: when O(state=present)
740 type: dict
741 sample: {
742 "Tag": "Example"
743 }
744 type:
745 description: The type of load balancer.
746 returned: when O(state=present)
747 type: str
748 sample: "application"
749 vpc_id:
750 description: The ID of the VPC for the load balancer.
751 returned: when O(state=present)
752 type: str
753 sample: "vpc-0011223344"
754 waf_fail_open_enabled:
755 description: Indicates whether to allow a AWS WAF-enabled load balancer to route requests to targets if it is unable to forward the request to AWS WAF.
756 returned: when O(state=present)
757 type: str
758 sample: "false"
759 """
760
761 try:
762 import botocore
763 except ImportError:
764 pass # caught by AnsibleAWSModule
765
766 from ansible_collections.amazon.aws.plugins.module_utils.elb_utils import AnsibleELBv2Error
767 from ansible_collections.amazon.aws.plugins.module_utils.elb_utils import get_elb_listener_rules
768 from ansible_collections.amazon.aws.plugins.module_utils.elbv2 import ApplicationLoadBalancer
769 from ansible_collections.amazon.aws.plugins.module_utils.elbv2 import ELBListener
770 from ansible_collections.amazon.aws.plugins.module_utils.elbv2 import ELBListenerRule
771 from ansible_collections.amazon.aws.plugins.module_utils.elbv2 import ELBListenerRules
772 from ansible_collections.amazon.aws.plugins.module_utils.elbv2 import ELBListeners
773 from ansible_collections.amazon.aws.plugins.module_utils.elbv2 import normalize_application_load_balancer
774 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
775 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
776 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
777 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
778 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
779
780
781 @AWSRetry.jittered_backoff()
782 def describe_sgs_with_backoff(connection, **params):
783 paginator = connection.get_paginator("describe_security_groups")
784 return paginator.paginate(**params).build_full_result()["SecurityGroups"]
785
786
787 def find_default_sg(connection, module, vpc_id):
788 """
789 Finds the default security group for the given VPC ID.
790 """
791 filters = ansible_dict_to_boto3_filter_list({"vpc-id": vpc_id, "group-name": "default"})
792 try:
793 sg = describe_sgs_with_backoff(connection, Filters=filters)
794 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
795 module.fail_json_aws(e, msg=f"No default security group found for VPC {vpc_id}")
796 if len(sg) == 1:
797 return sg[0]["GroupId"]
798 elif len(sg) == 0:
799 module.fail_json(msg=f"No default security group found for VPC {vpc_id}")
800 else:
801 module.fail_json(msg=f'Multiple security groups named "default" found for VPC {vpc_id}')
802
803
804 def create_or_update_alb(alb_obj: ApplicationLoadBalancer) -> None:
805 """Create ALB or modify main attributes. json_exit here"""
806 if alb_obj.elb:
807 # ALB exists so check subnets, security groups and tags match what has been passed
808 # Subnets
809 if not alb_obj.compare_subnets():
810 if alb_obj.check_mode:
811 alb_obj.exit_json(changed=True, msg="Would have updated ALB if not in check mode.")
812 alb_obj.modify_subnets()
813
814 # Security Groups
815 if not alb_obj.compare_security_groups():
816 if alb_obj.check_mode:
817 alb_obj.exit_json(changed=True, msg="Would have updated ALB if not in check mode.")
818 alb_obj.modify_security_groups()
819
820 # ALB attributes
821 if not alb_obj.compare_elb_attributes():
822 if alb_obj.check_mode:
823 alb_obj.exit_json(changed=True, msg="Would have updated ALB if not in check mode.")
824 alb_obj.update_elb_attributes()
825 alb_obj.modify_elb_attributes()
826
827 # Tags - only need to play with tags if tags parameter has been set to something
828 if alb_obj.tags is not None:
829 tags_need_modify, tags_to_delete = compare_aws_tags(
830 boto3_tag_list_to_ansible_dict(alb_obj.elb["tags"]),
831 boto3_tag_list_to_ansible_dict(alb_obj.tags),
832 alb_obj.purge_tags,
833 )
834
835 # Exit on check_mode
836 if alb_obj.check_mode and (tags_need_modify or tags_to_delete):
837 alb_obj.exit_json(changed=True, msg="Would have updated ALB if not in check mode.")
838
839 # Delete necessary tags
840 if tags_to_delete:
841 alb_obj.delete_tags(tags_to_delete)
842
843 # Add/update tags
844 if tags_need_modify:
845 alb_obj.modify_tags()
846
847 else:
848 # Create load balancer
849 if alb_obj.check_mode:
850 alb_obj.exit_json(changed=True, msg="Would have created ALB if not in check mode.")
851 alb_obj.create_elb()
852
853 # Add ALB attributes
854 alb_obj.update_elb_attributes()
855 alb_obj.modify_elb_attributes()
856
857 # Listeners
858 listeners_obj = ELBListeners(alb_obj.connection, alb_obj.module, alb_obj.elb["LoadBalancerArn"])
859 listeners_to_add, listeners_to_modify, listeners_to_delete = listeners_obj.compare_listeners()
860
861 # Exit on check_mode
862 if alb_obj.check_mode and (listeners_to_add or listeners_to_modify or listeners_to_delete):
863 alb_obj.exit_json(changed=True, msg="Would have updated ALB if not in check mode.")
864
865 # Delete listeners
866 for listener_to_delete in listeners_to_delete:
867 listener_obj = ELBListener(
868 alb_obj.connection, alb_obj.module, listener_to_delete, alb_obj.elb["LoadBalancerArn"]
869 )
870 listener_obj.delete()
871 listeners_obj.changed = True
872
873 # Add listeners
874 for listener_to_add in listeners_to_add:
875 listener_obj = ELBListener(alb_obj.connection, alb_obj.module, listener_to_add, alb_obj.elb["LoadBalancerArn"])
876 listener_obj.add()
877 listeners_obj.changed = True
878
879 # Modify listeners
880 for listener_to_modify in listeners_to_modify:
881 listener_obj = ELBListener(
882 alb_obj.connection, alb_obj.module, listener_to_modify, alb_obj.elb["LoadBalancerArn"]
883 )
884 listener_obj.modify()
885 listeners_obj.changed = True
886
887 # If listeners changed, mark ALB as changed and refresh current_listeners
888 if listeners_obj.changed:
889 alb_obj.changed = True
890 listeners_obj.update()
891
892 # Rules of each listener
893 for listener in listeners_obj.listeners:
894 if "Rules" in listener:
895 rules_obj = ELBListenerRules(
896 connection=alb_obj.connection,
897 module=alb_obj.module,
898 listener_arn=listeners_obj.get_listener_arn_from_listener_port(listener["Port"]),
899 listener_rules=listener["Rules"],
900 )
901 rules_to_add, rules_to_set_priority, rules_to_modify, rules_to_delete = rules_obj.compare_rules()
902
903 # Exit on check_mode
904 if alb_obj.check_mode and (
905 rules_to_add
906 or rules_to_modify
907 or rules_to_set_priority
908 or (alb_obj.params["purge_rules"] and rules_to_delete)
909 ):
910 alb_obj.exit_json(changed=True, msg="Would have updated ALB if not in check mode.")
911
912 # Create/Update/Delete Listener Rules
913 rule_obj = ELBListenerRule(alb_obj.connection, alb_obj.module)
914 alb_obj.changed |= rule_obj.process_rules(
915 rules_to_add, rules_to_set_priority, rules_to_modify, rules_to_delete
916 )
917
918 # Update ALB ip address type only if option has been provided
919 if alb_obj.params.get("ip_address_type") and alb_obj.elb_ip_addr_type != alb_obj.params.get("ip_address_type"):
920 # Exit on check_mode
921 if alb_obj.check_mode:
922 alb_obj.exit_json(changed=True, msg="Would have updated ALB if not in check mode.")
923
924 alb_obj.modify_ip_address_type(alb_obj.params.get("ip_address_type"))
925
926 # Exit on check_mode - no changes
927 if alb_obj.check_mode:
928 alb_obj.exit_json(changed=False, msg="IN CHECK MODE - no changes to make to ALB specified.")
929
930 # Get the ALB again
931 alb_obj.update()
932
933 # Get the ALB listeners again
934 listeners_obj.update()
935
936 # Update the ALB attributes
937 alb_obj.update_elb_attributes()
938
939 # Build the complete ALB object in CamelCase format
940 alb = alb_obj.elb.copy()
941 alb.update(alb_obj.elb_attributes)
942
943 # Attach listeners with their rules
944 alb["Listeners"] = []
945 for listener in listeners_obj.current_listeners:
946 # For each listener, get listener rules (in CamelCase)
947 listener["Rules"] = get_elb_listener_rules(alb_obj.connection, alb_obj.module, listener["ListenerArn"])
948 alb["Listeners"].append(listener)
949
950 # Add ip address type
951 alb["IpAddressType"] = alb_obj.get_elb_ip_address_type()
952
953 # Add tags (not included in describe_load_balancers response)
954 alb["Tags"] = alb_obj.get_elb_tags()
955
956 # Normalize the entire ALB object (convert to snake_case, sort rules, convert tags)
957 snaked_alb = normalize_application_load_balancer(alb)
958
959 alb_obj.exit_json(changed=alb_obj.changed, **snaked_alb)
960
961
962 def delete_alb(alb_obj: ApplicationLoadBalancer) -> None:
963 if alb_obj.elb:
964 # Exit on check_mode
965 if alb_obj.check_mode:
966 alb_obj.exit_json(changed=True, msg="Would have deleted ALB if not in check mode.")
967
968 listeners_obj = ELBListeners(alb_obj.connection, alb_obj.module, alb_obj.elb["LoadBalancerArn"])
969 for listener_to_delete in [i["ListenerArn"] for i in listeners_obj.current_listeners]:
970 listener_obj = ELBListener(
971 alb_obj.connection, alb_obj.module, listener_to_delete, alb_obj.elb["LoadBalancerArn"]
972 )
973 listener_obj.delete()
974
975 alb_obj.delete()
976
977 else:
978 # Exit on check_mode - no changes
979 if alb_obj.check_mode:
980 alb_obj.exit_json(changed=False, msg="IN CHECK MODE - ALB already absent.")
981
982 alb_obj.exit_json(changed=alb_obj.changed)
983
984
985 def main():
986 argument_spec = dict(
987 access_logs_enabled=dict(type="bool"),
988 access_logs_s3_bucket=dict(type="str"),
989 access_logs_s3_prefix=dict(type="str"),
990 deletion_protection=dict(type="bool"),
991 http2=dict(type="bool"),
992 http_desync_mitigation_mode=dict(type="str", choices=["monitor", "defensive", "strictest"]),
993 http_drop_invalid_header_fields=dict(type="bool"),
994 http_x_amzn_tls_version_and_cipher_suite=dict(type="bool"),
995 http_xff_client_port=dict(type="bool"),
996 idle_timeout=dict(type="int"),
997 listeners=dict(
998 type="list",
999 elements="dict",
1000 options=dict(
1001 Protocol=dict(type="str", required=True),
1002 Port=dict(type="int", required=True),
1003 SslPolicy=dict(type="str"),
1004 Certificates=dict(type="list", elements="dict"),
1005 DefaultActions=dict(type="list", required=True, elements="dict"),
1006 Rules=dict(type="list", elements="dict"),
1007 ),
1008 ),
1009 name=dict(required=True, type="str"),
1010 purge_listeners=dict(default=True, type="bool"),
1011 purge_tags=dict(default=True, type="bool"),
1012 subnets=dict(type="list", elements="str"),
1013 security_groups=dict(type="list", elements="str"),
1014 scheme=dict(default="internet-facing", choices=["internet-facing", "internal"]),
1015 state=dict(choices=["present", "absent"], default="present"),
1016 tags=dict(type="dict", aliases=["resource_tags"]),
1017 waf_fail_open=dict(type="bool"),
1018 wait_timeout=dict(type="int"),
1019 wait=dict(default=False, type="bool"),
1020 purge_rules=dict(default=True, type="bool"),
1021 ip_address_type=dict(type="str", choices=["ipv4", "dualstack"]),
1022 )
1023
1024 module = AnsibleAWSModule(
1025 argument_spec=argument_spec,
1026 required_if=[("state", "present", ["subnets", "security_groups"])],
1027 required_together=[["access_logs_enabled", "access_logs_s3_bucket"]],
1028 supports_check_mode=True,
1029 )
1030
1031 # Quick check of listeners parameters
1032 listeners = module.params.get("listeners")
1033 if listeners is not None:
1034 for listener in listeners:
1035 for key in listener.keys():
1036 if key == "Protocol" and listener[key] == "HTTPS":
1037 if listener.get("SslPolicy") is None:
1038 module.fail_json(msg="'SslPolicy' is a required listener dict key when Protocol = HTTPS")
1039
1040 if listener.get("Certificates") is None:
1041 module.fail_json(msg="'Certificates' is a required listener dict key when Protocol = HTTPS")
1042
1043 connection = module.client("elbv2")
1044 connection_ec2 = module.client("ec2")
1045
1046 state = module.params.get("state")
1047
1048 try:
1049 alb = ApplicationLoadBalancer(connection, connection_ec2, module)
1050
1051 # Update security group if default is specified
1052 if alb.elb and module.params.get("security_groups") == []:
1053 module.params["security_groups"] = [find_default_sg(connection_ec2, module, alb.elb["VpcId"])]
1054 alb = ApplicationLoadBalancer(connection, connection_ec2, module)
1055
1056 if state == "present":
1057 create_or_update_alb(alb)
1058 elif state == "absent":
1059 delete_alb(alb)
1060 except AnsibleELBv2Error as e:
1061 module.fail_json_aws_error(e)
1062
1063
1064 if __name__ == "__main__":
1065 main()