Debian Codegraph @

ansible_collections/community/aws/plugins/modules/cloudfront_distribution.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2017 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
10 version_added: 1.0.0
11 module: cloudfront_distribution
12
13 short_description: Create, update and delete AWS CloudFront distributions
14
15 description:
16 - Allows for easy creation, updating and deletion of CloudFront distributions.
17
18 author:
19 - Willem van Ketwich (@wilvk)
20 - Will Thames (@willthames)
21
22 options:
23
24 state:
25 description:
26 - The desired state of the distribution.
27 - I(state=present) creates a new distribution or updates an existing distribution.
28 - I(state=absent) deletes an existing distribution.
29 choices: ['present', 'absent']
30 default: 'present'
31 type: str
32
33 distribution_id:
34 description:
35 - The ID of the CloudFront distribution.
36 - This parameter can be exchanged with I(alias) or I(caller_reference) and is used in conjunction with I(e_tag).
37 type: str
38
39 e_tag:
40 description:
41 - A unique identifier of a modified or existing distribution. Used in conjunction with I(distribution_id).
42 - Is determined automatically if not specified.
43 type: str
44
45 caller_reference:
46 description:
47 - A unique identifier for creating and updating CloudFront distributions.
48 - Each caller reference must be unique across all distributions. e.g. a caller reference used in a web
49 distribution cannot be reused in a streaming distribution. This parameter can be used instead of I(distribution_id)
50 to reference an existing distribution. If not specified, this defaults to a datetime stamp of the format
51 C(YYYY-MM-DDTHH:MM:SS.ffffff).
52 type: str
53
54 alias:
55 description:
56 - The name of an alias (CNAME) that is used in a distribution. This is used to effectively reference a distribution by its alias as an alias can only
57 be used by one distribution per AWS account. This variable avoids having to provide the I(distribution_id) as well as
58 the I(e_tag), or I(caller_reference) of an existing distribution.
59 type: str
60
61 aliases:
62 description:
63 - A list of domain name aliases (CNAMEs) as strings to be used for the distribution.
64 - Each alias must be unique across all distribution for the AWS account.
65 type: list
66 elements: str
67 default: []
68
69 purge_aliases:
70 description:
71 - Specifies whether existing aliases will be removed before adding new aliases.
72 - When I(purge_aliases=true), existing aliases are removed and I(aliases) are added.
73 default: false
74 type: bool
75
76 default_root_object:
77 description:
78 - A config element that specifies the path to request when the user requests the origin.
79 - e.g. if specified as 'index.html', this maps to www.example.com/index.html when www.example.com is called by the user.
80 - This prevents the entire distribution origin from being exposed at the root.
81 type: str
82
83 default_origin_domain_name:
84 description:
85 - The domain name to use for an origin if no I(origins) have been specified.
86 - Should only be used on a first run of generating a distribution and not on
87 subsequent runs.
88 - Should not be used in conjunction with I(distribution_id), I(caller_reference) or I(alias).
89 type: str
90
91 default_origin_path:
92 description:
93 - The default origin path to specify for an origin if no I(origins) have been specified. Defaults to empty if not specified.
94 type: str
95
96 origins:
97 type: list
98 elements: dict
99 description:
100 - A config element that is a list of complex origin objects to be specified for the distribution. Used for creating and updating distributions.
101 suboptions:
102 id:
103 description: A unique identifier for the origin or origin group. I(id) must be unique within the distribution.
104 type: str
105 domain_name:
106 description:
107 - The domain name which CloudFront will query as the origin.
108 - For more information see the CloudFront documentation
109 at U(https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName)
110 type: str
111 origin_path:
112 description: Tells CloudFront to request your content from a directory in your Amazon S3 bucket or your custom origin.
113 type: str
114 origin_shield:
115 description: Specify origin shield options for the origin.
116 type: dict
117 suboptions:
118 enabled:
119 description: Indicate whether you want the origin to have Origin Shield enabled or not.
120 type: bool
121 origin_shield_region:
122 description: Specify which AWS region will be used for Origin Shield. Required if Origin Shield is enabled.
123 type: str
124 version_added: 6.0.0
125 custom_headers:
126 description:
127 - Custom headers you wish to add to the request before passing it to the origin.
128 - For more information see the CloudFront documentation
129 at U(https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/forward-custom-headers.html).
130 type: list
131 elements: dict
132 suboptions:
133 header_name:
134 description: The name of a header that you want CloudFront to forward to your origin.
135 type: str
136 header_value:
137 description: The value for the header that you specified in the I(header_name) field.
138 type: str
139 s3_origin_access_identity_enabled:
140 description:
141 - Use an origin access identity to configure the origin so that viewers can only access objects in an Amazon S3 bucket through CloudFront.
142 - Will automatically create an Identity for you if no I(s3_origin_config) is specified.
143 - See also U(https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html).
144 type: bool
145 s3_origin_config:
146 description: Specify origin access identity for S3 origins.
147 type: dict
148 suboptions:
149 origin_access_identity:
150 description: Existing origin access identity in the format C(origin-access-identity/cloudfront/OID_ID).
151 type: str
152 custom_origin_config:
153 description: Connection information about the origin.
154 type: dict
155 suboptions:
156 http_port:
157 description: The HTTP port the custom origin listens on.
158 type: int
159 https_port:
160 description: The HTTPS port the custom origin listens on.
161 type: int
162 origin_protocol_policy:
163 description: The origin protocol policy to apply to your origin.
164 type: str
165 origin_ssl_protocols:
166 description: A list of SSL/TLS protocols that you want CloudFront to use when communicating to the origin over HTTPS.
167 type: list
168 elements: str
169 origin_read_timeout:
170 description: A timeout (in seconds) when reading from your origin.
171 type: int
172 origin_keepalive_timeout:
173 description: A keep-alive timeout (in seconds).
174 type: int
175 connection_attempts:
176 description: The number of times that CloudFront attempts to connect to the origin.
177 The minimum number is C(1), the maximum is C(3).
178 type: int
179 default: 3
180 version_added: 6.0.0
181 connection_timeout:
182 description: The number of seconds that CloudFront waits when trying to establish a connection to the origin.
183 The minimum timeout is C(1) second, the maximum is C(10) seconds.
184 type: int
185 default: 10
186 version_added: 6.0.0
187 purge_origins:
188 description: Whether to remove any origins that aren't listed in I(origins).
189 default: false
190 type: bool
191
192 default_cache_behavior:
193 type: dict
194 description:
195 - A dict specifying the default cache behavior of the distribution.
196 - If not specified, the I(target_origin_id) is defined as the I(target_origin_id) of the first valid
197 cache_behavior in I(cache_behaviors) with defaults.
198 suboptions:
199 target_origin_id:
200 description:
201 - The ID of the origin that you want CloudFront to route requests to
202 by default.
203 type: str
204 response_headers_policy_id:
205 description:
206 - The ID of the header policy that CloudFront adds to responses that it sends to viewers.
207 type: str
208 cache_policy_id:
209 version_added: 7.1.0
210 description:
211 - The ID of the cache policy for CloudFront to use for the default cache behavior.
212 - A behavior should use either a C(cache_policy_id) or a C(forwarded_values) option.
213 - For more information see the CloudFront documentation
214 at U(https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html)
215 type: str
216 origin_request_policy_id:
217 version_added: 7.1.0
218 description:
219 - The ID of the origin request policy for CloudFront to use for the default cache behavior.
220 - For more information see the CloudFront documentation
221 at U(https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html)
222 type: str
223 forwarded_values:
224 description:
225 - A dict that specifies how CloudFront handles query strings and cookies.
226 - A behavior should use either a C(cache_policy_id) or a C(forwarded_values) option.
227 type: dict
228 suboptions:
229 query_string:
230 description:
231 - Indicates whether you want CloudFront to forward query strings
232 to the origin that is associated with this cache behavior.
233 type: bool
234 cookies:
235 description: A dict that specifies whether you want CloudFront to forward cookies to the origin and, if so, which ones.
236 type: dict
237 suboptions:
238 forward:
239 description:
240 - Specifies which cookies to forward to the origin for this cache behavior.
241 - Valid values are C(all), C(none), or C(whitelist).
242 type: str
243 whitelisted_names:
244 type: list
245 elements: str
246 description: A list of cookies to forward to the origin for this cache behavior.
247 headers:
248 description:
249 - A list of headers to forward to the origin for this cache behavior.
250 - To forward all headers use a list containing a single element '*' (C(['*']))
251 type: list
252 elements: str
253 query_string_cache_keys:
254 description:
255 - A list that contains the query string parameters you want CloudFront to use as a basis for caching for a cache behavior.
256 type: list
257 elements: str
258 trusted_signers:
259 description:
260 - A dict that specifies the AWS accounts that you want to allow to create signed URLs for private content.
261 type: dict
262 suboptions:
263 enabled:
264 description: Whether you want to require viewers to use signed URLs to access the files specified by I(target_origin_id)
265 type: bool
266 items:
267 description: A list of trusted signers for this cache behavior.
268 elements: str
269 type: list
270 viewer_protocol_policy:
271 description:
272 - The protocol that viewers can use to access the files in the origin specified by I(target_origin_id).
273 - Valid values are C(allow-all), C(redirect-to-https) and C(https-only).
274 type: str
275 default_ttl:
276 description: The default amount of time that you want objects to stay in CloudFront caches.
277 type: int
278 max_ttl:
279 description: The maximum amount of time that you want objects to stay in CloudFront caches.
280 type: int
281 min_ttl:
282 description: The minimum amount of time that you want objects to stay in CloudFront caches.
283 type: int
284 allowed_methods:
285 description: A dict that controls which HTTP methods CloudFront processes and forwards.
286 type: dict
287 suboptions:
288 items:
289 description: A list of HTTP methods that you want CloudFront to process and forward.
290 type: list
291 elements: str
292 cached_methods:
293 description:
294 - A list of HTTP methods that you want CloudFront to apply caching to.
295 - This can either be C([GET,HEAD]), or C([GET,HEAD,OPTIONS]).
296 type: list
297 elements: str
298 smooth_streaming:
299 description:
300 - Whether you want to distribute media files in the Microsoft Smooth Streaming format.
301 type: bool
302 compress:
303 description:
304 - Whether you want CloudFront to automatically compress files.
305 type: bool
306 lambda_function_associations:
307 description:
308 - A list of Lambda function associations to use for this cache behavior.
309 type: list
310 elements: dict
311 suboptions:
312 lambda_function_arn:
313 description: The ARN of the Lambda function.
314 type: str
315 event_type:
316 description:
317 - Specifies the event type that triggers a Lambda function invocation.
318 - This can be C(viewer-request), C(origin-request), C(origin-response) or C(viewer-response).
319 type: str
320 field_level_encryption_id:
321 description:
322 - The field-level encryption configuration that you want CloudFront to use for encrypting specific fields of data.
323 type: str
324
325 cache_behaviors:
326 type: list
327 elements: dict
328 description:
329 - A list of dictionaries describing the cache behaviors for the distribution.
330 - The order of the list is preserved across runs unless I(purge_cache_behaviors) is enabled.
331 suboptions:
332 path_pattern:
333 description:
334 - The pattern that specifies which requests to apply the behavior to.
335 type: str
336 target_origin_id:
337 description:
338 - The ID of the origin that you want CloudFront to route requests to
339 by default.
340 type: str
341 response_headers_policy_id:
342 description:
343 - The ID of the header policy that CloudFront adds to responses that it sends to viewers.
344 type: str
345 cache_policy_id:
346 version_added: 7.1.0
347 description:
348 - The ID of the cache policy for CloudFront to use for the cache behavior.
349 - A behavior should use either a C(cache_policy_id) or a C(forwarded_values) option.
350 - For more information see the CloudFront documentation
351 at U(https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html)
352 type: str
353 origin_request_policy_id:
354 version_added: 7.1.0
355 description:
356 - The ID of the origin request policy for CloudFront to use for the cache behavior.
357 - For more information see the CloudFront documentation
358 at U(https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html)
359 type: str
360 forwarded_values:
361 description:
362 - A dict that specifies how CloudFront handles query strings and cookies.
363 - A behavior should use either a C(cache_policy_id) or a C(forwarded_values) option.
364 type: dict
365 suboptions:
366 query_string:
367 description:
368 - Indicates whether you want CloudFront to forward query strings
369 to the origin that is associated with this cache behavior.
370 type: bool
371 cookies:
372 description: A dict that specifies whether you want CloudFront to forward cookies to the origin and, if so, which ones.
373 type: dict
374 suboptions:
375 forward:
376 description:
377 - Specifies which cookies to forward to the origin for this cache behavior.
378 - Valid values are C(all), C(none), or C(whitelist).
379 type: str
380 whitelisted_names:
381 type: list
382 elements: str
383 description: A list of cookies to forward to the origin for this cache behavior.
384 headers:
385 description:
386 - A list of headers to forward to the origin for this cache behavior.
387 - To forward all headers use a list containing a single element '*' (C(['*']))
388 type: list
389 elements: str
390 query_string_cache_keys:
391 description:
392 - A list that contains the query string parameters you want CloudFront to use as a basis for caching for a cache behavior.
393 type: list
394 elements: str
395 trusted_signers:
396 description:
397 - A dict that specifies the AWS accounts that you want to allow to create signed URLs for private content.
398 type: dict
399 suboptions:
400 enabled:
401 description: Whether you want to require viewers to use signed URLs to access the files specified by I(path_pattern) and I(target_origin_id)
402 type: bool
403 items:
404 description: A list of trusted signers for this cache behavior.
405 elements: str
406 type: list
407 viewer_protocol_policy:
408 description:
409 - The protocol that viewers can use to access the files in the origin specified by I(target_origin_id) when a request matches I(path_pattern).
410 - Valid values are C(allow-all), C(redirect-to-https) and C(https-only).
411 type: str
412 default_ttl:
413 description: The default amount of time that you want objects to stay in CloudFront caches.
414 type: int
415 max_ttl:
416 description: The maximum amount of time that you want objects to stay in CloudFront caches.
417 type: int
418 min_ttl:
419 description: The minimum amount of time that you want objects to stay in CloudFront caches.
420 type: int
421 allowed_methods:
422 description: A dict that controls which HTTP methods CloudFront processes and forwards.
423 type: dict
424 suboptions:
425 items:
426 description: A list of HTTP methods that you want CloudFront to process and forward.
427 type: list
428 elements: str
429 cached_methods:
430 description:
431 - A list of HTTP methods that you want CloudFront to apply caching to.
432 - This can either be C([GET,HEAD]), or C([GET,HEAD,OPTIONS]).
433 type: list
434 elements: str
435 smooth_streaming:
436 description:
437 - Whether you want to distribute media files in the Microsoft Smooth Streaming format.
438 type: bool
439 compress:
440 description:
441 - Whether you want CloudFront to automatically compress files.
442 type: bool
443 lambda_function_associations:
444 description:
445 - A list of Lambda function associations to use for this cache behavior.
446 type: list
447 elements: dict
448 suboptions:
449 lambda_function_arn:
450 description: The ARN of the Lambda function.
451 type: str
452 event_type:
453 description:
454 - Specifies the event type that triggers a Lambda function invocation.
455 - This can be C(viewer-request), C(origin-request), C(origin-response) or C(viewer-response).
456 type: str
457 field_level_encryption_id:
458 description:
459 - The field-level encryption configuration that you want CloudFront to use for encrypting specific fields of data.
460 type: str
461
462
463 purge_cache_behaviors:
464 description:
465 - Whether to remove any cache behaviors that aren't listed in I(cache_behaviors).
466 - This switch also allows the reordering of I(cache_behaviors).
467 default: false
468 type: bool
469
470 custom_error_responses:
471 type: list
472 elements: dict
473 description:
474 - A config element that is a I(list[]) of complex custom error responses to be specified for the distribution.
475 - This attribute configures custom http error messages returned to the user.
476 suboptions:
477 error_code:
478 type: int
479 description: The error code the custom error page is for.
480 error_caching_min_ttl:
481 type: int
482 description: The length of time (in seconds) that CloudFront will cache status codes for.
483 response_code:
484 type: int
485 description:
486 - The HTTP status code that CloudFront should return to a user when the origin returns the HTTP status code specified by I(error_code).
487 response_page_path:
488 type: str
489 description:
490 - The path to the custom error page that you want CloudFront to return to a viewer when your origin returns
491 the HTTP status code specified by I(error_code).
492
493 purge_custom_error_responses:
494 description: Whether to remove any custom error responses that aren't listed in I(custom_error_responses).
495 default: false
496 type: bool
497
498 comment:
499 description:
500 - A comment that describes the CloudFront distribution.
501 - If not specified, it defaults to a generic message that it has been created with Ansible, and a datetime stamp.
502 type: str
503
504 logging:
505 description:
506 - A config element that is a complex object that defines logging for the distribution.
507 suboptions:
508 enabled:
509 description: When I(enabled=true) CloudFront will log access to an S3 bucket.
510 type: bool
511 include_cookies:
512 description: When I(include_cookies=true) CloudFront will include cookies in the logs.
513 type: bool
514 bucket:
515 description: The S3 bucket to store the log in.
516 type: str
517 prefix:
518 description: A prefix to include in the S3 object names.
519 type: str
520 type: dict
521
522 price_class:
523 description:
524 - A string that specifies the pricing class of the distribution. As per
525 U(https://aws.amazon.com/cloudfront/pricing/)
526 - I(price_class=PriceClass_100) consists of the areas United States, Canada and Europe.
527 - I(price_class=PriceClass_200) consists of the areas United States, Canada, Europe, Japan, India,
528 Hong Kong, Philippines, S. Korea, Singapore & Taiwan.
529 - I(price_class=PriceClass_All) consists of the areas United States, Canada, Europe, Japan, India,
530 South America, Australia, Hong Kong, Philippines, S. Korea, Singapore & Taiwan.
531 - AWS defaults this to C(PriceClass_All).
532 - Valid values are C(PriceClass_100), C(PriceClass_200) and C(PriceClass_All)
533 type: str
534
535 enabled:
536 description:
537 - A boolean value that specifies whether the distribution is enabled or disabled.
538 - Defaults to C(false).
539 type: bool
540
541 viewer_certificate:
542 type: dict
543 description:
544 - A dict that specifies the encryption details of the distribution.
545 suboptions:
546 cloudfront_default_certificate:
547 type: bool
548 description:
549 - If you're using the CloudFront domain name for your distribution, such as C(123456789abcde.cloudfront.net)
550 you should set I(cloudfront_default_certificate=true).
551 - If I(cloudfront_default_certificate=true) do not set I(ssl_support_method).
552 iam_certificate_id:
553 type: str
554 description:
555 - The ID of a certificate stored in IAM to use for HTTPS connections.
556 - If I(iam_certificate_id) is set then you must also specify I(ssl_support_method).
557 acm_certificate_arn:
558 type: str
559 description:
560 - The ID of a certificate stored in ACM to use for HTTPS connections.
561 - If I(acm_certificate_id) is set then you must also specify I(ssl_support_method).
562 ssl_support_method:
563 type: str
564 description:
565 - How CloudFront should serve SSL certificates.
566 - Valid values are C(sni-only) for SNI, and C(vip) if CloudFront is configured to use a dedicated IP for your content.
567 minimum_protocol_version:
568 type: str
569 description:
570 - The security policy that you want CloudFront to use for HTTPS connections.
571 - See U(https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/secure-connections-supported-viewer-protocols-ciphers.html)
572 for supported security policies.
573
574 restrictions:
575 type: dict
576 description:
577 - A config element that is a complex object that describes how a distribution should restrict it's content.
578 suboptions:
579 geo_restriction:
580 description: Apply a restriction based on the location of the requester.
581 type: dict
582 suboptions:
583 restriction_type:
584 type: str
585 description:
586 - The method that you want to use to restrict distribution of your content by country.
587 - Valid values are C(none), C(whitelist), C(blacklist).
588 items:
589 description:
590 - A list of ISO 3166-1 two letter (Alpha 2) country codes that the
591 restriction should apply to.
592 - 'See the ISO website for a full list of codes U(https://www.iso.org/obp/ui/#search/code/).'
593 type: list
594 elements: str
595
596 web_acl_id:
597 description:
598 - The ID of a Web Application Firewall (WAF) Access Control List (ACL).
599 type: str
600
601 http_version:
602 description:
603 - The version of the http protocol to use for the distribution.
604 - AWS defaults this to C(http2).
605 - Valid values are C(http1.1), C(http2), C(http3) and C(http2and3).
606 type: str
607
608 ipv6_enabled:
609 description:
610 - Determines whether IPv6 support is enabled or not.
611 - Defaults to C(false).
612 type: bool
613
614 wait:
615 description:
616 - Specifies whether the module waits until the distribution has completed processing the creation or update.
617 type: bool
618 default: false
619
620 wait_timeout:
621 description:
622 - Specifies the duration in seconds to wait for a timeout of a cloudfront create or update.
623 default: 1800
624 type: int
625
626 extends_documentation_fragment:
627 - amazon.aws.common.modules
628 - amazon.aws.region.modules
629 - amazon.aws.tags
630 - amazon.aws.boto3
631 """
632
633 EXAMPLES = r"""
634 - name: create a basic distribution with defaults and tags
635 community.aws.cloudfront_distribution:
636 state: present
637 default_origin_domain_name: www.my-cloudfront-origin.com
638 tags:
639 Name: example distribution
640 Project: example project
641 Priority: '1'
642
643 - name: update a distribution comment by distribution_id
644 community.aws.cloudfront_distribution:
645 state: present
646 distribution_id: E1RP5A2MJ8073O
647 comment: modified by ansible cloudfront.py
648
649 - name: update a distribution comment by caller_reference
650 community.aws.cloudfront_distribution:
651 state: present
652 caller_reference: my cloudfront distribution 001
653 comment: modified by ansible cloudfront.py
654
655 - name: update a distribution's aliases and comment using the distribution_id as a reference
656 community.aws.cloudfront_distribution:
657 state: present
658 distribution_id: E1RP5A2MJ8073O
659 comment: modified by cloudfront.py again
660 aliases:
661 - 'www.my-distribution-source.com'
662 - 'zzz.aaa.io'
663
664 - name: update a distribution's aliases and comment using an alias as a reference
665 community.aws.cloudfront_distribution:
666 state: present
667 caller_reference: my test distribution
668 comment: modified by cloudfront.py again
669 aliases:
670 - www.my-distribution-source.com
671 - zzz.aaa.io
672
673 - name: update a distribution's comment and aliases and tags and remove existing tags
674 community.aws.cloudfront_distribution:
675 state: present
676 distribution_id: E15BU8SDCGSG57
677 comment: modified by cloudfront.py again
678 aliases:
679 - tested.com
680 tags:
681 Project: distribution 1.2
682 purge_tags: true
683
684 - name: create a distribution with an origin, logging and default cache behavior
685 community.aws.cloudfront_distribution:
686 state: present
687 caller_reference: unique test distribution ID
688 origins:
689 - id: 'my test origin-000111'
690 domain_name: www.example.com
691 origin_path: /production
692 custom_headers:
693 - header_name: MyCustomHeaderName
694 header_value: MyCustomHeaderValue
695 default_cache_behavior:
696 target_origin_id: 'my test origin-000111'
697 forwarded_values:
698 query_string: true
699 cookies:
700 forward: all
701 headers:
702 - '*'
703 viewer_protocol_policy: allow-all
704 smooth_streaming: true
705 compress: true
706 allowed_methods:
707 items:
708 - GET
709 - HEAD
710 cached_methods:
711 - GET
712 - HEAD
713 logging:
714 enabled: true
715 include_cookies: false
716 bucket: mylogbucket.s3.amazonaws.com
717 prefix: myprefix/
718 enabled: false
719 comment: this is a CloudFront distribution with logging
720
721 - name: delete a distribution
722 community.aws.cloudfront_distribution:
723 state: absent
724 caller_reference: replaceable distribution
725 """
726
727 RETURN = r"""
728 active_trusted_signers:
729 description: Key pair IDs that CloudFront is aware of for each trusted signer.
730 returned: always
731 type: complex
732 contains:
733 enabled:
734 description: Whether trusted signers are in use.
735 returned: always
736 type: bool
737 sample: false
738 quantity:
739 description: Number of trusted signers.
740 returned: always
741 type: int
742 sample: 1
743 items:
744 description:
745 - A list of trusted signers.
746 - This return value has been deprecated and will be removed in a release after 2026-12-16.
747 Use RV(active_trusted_signers.elements) instead.
748 returned: when there are trusted signers
749 type: list
750 sample:
751 - key_pair_id
752 elements:
753 description: A list of trusted signers.
754 returned: when there are trusted signers
755 type: list
756 version_added: 10.1.0
757 sample:
758 - key_pair_id
759 active_trusted_key_groups:
760 description:
761 - This field contains a list of key groups and the public keys in each key group that CloudFront
762 can use to verify the signatures of signed URLs or signed cookies.
763 returned: always
764 type: complex
765 contains:
766 enabled:
767 description:
768 - This field is true if any of the key groups have public keys that CloudFront can use to verify
769 the signatures of signed URLs and signed cookies. If not, this field is false.
770 returned: always
771 type: bool
772 sample: false
773 quantity:
774 description: Number of key groups.
775 returned: always
776 type: int
777 sample: 1
778 items:
779 description:
780 - A list of key groups.
781 - This return value has been deprecated and will be removed in a release after 2026-12-16.
782 Use RV(active_trusted_key_groups.elements) instead.
783 returned: when there are trusted signers
784 type: list
785 elements:
786 description: A list of key groups.
787 returned: when there are trusted signers
788 type: list
789 version_added: 10.1.0
790 aliases:
791 description: Aliases that refer to the distribution.
792 returned: always
793 type: complex
794 contains:
795 items:
796 description:
797 - List of aliases.
798 - This return value has been deprecated and will be removed in a release after 2026-12-16.
799 Use RV(aliases.elements) instead.
800 returned: always
801 type: list
802 sample:
803 - test.example.com
804 elements:
805 description: List of aliases.
806 returned: always
807 type: list
808 version_added: 10.1.0
809 sample:
810 - test.example.com
811 quantity:
812 description: Number of aliases.
813 returned: always
814 type: int
815 sample: 1
816 arn:
817 description: Amazon Resource Name of the distribution.
818 returned: always
819 type: str
820 sample: arn:aws:cloudfront::123456789012:distribution/E1234ABCDEFGHI
821 cache_behaviors:
822 description: CloudFront cache behaviors.
823 returned: always
824 type: complex
825 contains:
826 items:
827 description:
828 - List of cache behaviors.
829 - This return value has been deprecated and will be removed in a release after 2026-12-16.
830 Use RV(cache_behaviors.elements) instead.
831 returned: always
832 type: complex
833 contains:
834 allowed_methods:
835 description: Methods allowed by the cache behavior.
836 returned: always
837 type: complex
838 contains:
839 cached_methods:
840 description: Methods cached by the cache behavior.
841 returned: always
842 type: complex
843 contains:
844 items:
845 description: List of cached methods.
846 returned: always
847 type: list
848 sample:
849 - HEAD
850 - GET
851 quantity:
852 description: Count of cached methods.
853 returned: always
854 type: int
855 sample: 2
856 items:
857 description:
858 - List of methods allowed by the cache behavior.
859 - This return value has been deprecated and will be removed in a release after 2026-12-16.
860 Use RV(cache_behaviors.elements.allowed_methods.elements) instead.
861 returned: always
862 type: list
863 sample:
864 - HEAD
865 - GET
866 quantity:
867 description: Count of methods allowed by the cache behavior.
868 returned: always
869 type: int
870 sample: 2
871 compress:
872 description: Whether compression is turned on for the cache behavior.
873 returned: always
874 type: bool
875 sample: false
876 default_ttl:
877 description: Default Time to Live of the cache behavior.
878 returned: always
879 type: int
880 sample: 86400
881 forwarded_values:
882 description: Values forwarded to the origin for this cache behavior.
883 returned: always
884 type: complex
885 contains:
886 cookies:
887 description: Cookies to forward to the origin.
888 returned: always
889 type: complex
890 contains:
891 forward:
892 description: Which cookies to forward to the origin for this cache behavior.
893 returned: always
894 type: str
895 sample: none
896 whitelisted_names:
897 description: The names of the cookies to forward to the origin for this cache behavior.
898 returned: when I(forward=whitelist)
899 type: complex
900 contains:
901 quantity:
902 description: Count of cookies to forward.
903 returned: always
904 type: int
905 sample: 1
906 items:
907 description:
908 - List of cookies to forward.
909 - This return value has been deprecated and will be removed in a release after 2026-12-16.
910 Use RV(cache_behaviors.elements.forwarded_values.cookies.whitelisted_names.elements) instead.
911 returned: when list is not empty
912 type: list
913 sample: my_cookie
914 headers:
915 description: Which headers are used to vary on cache retrievals.
916 returned: always
917 type: complex
918 contains:
919 quantity:
920 description: Count of headers to vary on.
921 returned: always
922 type: int
923 sample: 1
924 items:
925 description:
926 - List of headers to vary on.
927 - This return value has been deprecated and will be removed in a release after 2026-12-16.
928 Use RV(cache_behaviors.elements.forwarded_values.headers.elements) instead.
929 returned: when list is not empty
930 type: list
931 sample:
932 - Host
933 query_string:
934 description: Whether the query string is used in cache lookups.
935 returned: always
936 type: bool
937 sample: false
938 query_string_cache_keys:
939 description: Which query string keys to use in cache lookups.
940 returned: always
941 type: complex
942 contains:
943 quantity:
944 description: Count of query string cache keys to use in cache lookups.
945 returned: always
946 type: int
947 sample: 1
948 items:
949 description:
950 - List of query string cache keys to use in cache lookups.
951 - This return value has been deprecated and will be removed in a release after 2026-12-16.
952 Use RV(cache_behaviors.elements.forwarded_values.query_string_cache_keys.elements) instead.
953 returned: when list is not empty
954 type: list
955 sample:
956 lambda_function_associations:
957 description: Lambda function associations for a cache behavior.
958 returned: always
959 type: complex
960 contains:
961 quantity:
962 description: Count of lambda function associations.
963 returned: always
964 type: int
965 sample: 1
966 items:
967 description:
968 - List of lambda function associations.
969 - This return value has been deprecated and will be removed in a release after 2026-12-16.
970 Use RV(cache_behaviors.elements.lambda_function_associations.elements) instead.
971 returned: when list is not empty
972 type: list
973 sample:
974 - lambda_function_arn: arn:aws:lambda:123456789012:us-east-1/lambda/lambda-function
975 event_type: viewer-response
976 max_ttl:
977 description: Maximum Time to Live.
978 returned: always
979 type: int
980 sample: 31536000
981 min_ttl:
982 description: Minimum Time to Live.
983 returned: always
984 type: int
985 sample: 0
986 path_pattern:
987 description: Path pattern that determines this cache behavior.
988 returned: always
989 type: str
990 sample: /path/to/files/*
991 smooth_streaming:
992 description: Whether smooth streaming is enabled.
993 returned: always
994 type: bool
995 sample: false
996 target_origin_id:
997 description: ID of origin reference by this cache behavior.
998 returned: always
999 type: str
1000 sample: origin_abcd
1001 trusted_signers:
1002 description: Trusted signers.
1003 returned: always
1004 type: complex
1005 contains:
1006 enabled:
1007 description: Whether trusted signers are enabled for this cache behavior.
1008 returned: always
1009 type: bool
1010 sample: false
1011 quantity:
1012 description: Count of trusted signers.
1013 returned: always
1014 type: int
1015 sample: 1
1016 viewer_protocol_policy:
1017 description: Policy of how to handle http/https.
1018 returned: always
1019 type: str
1020 sample: redirect-to-https
1021 elements:
1022 description: List of cache behaviors.
1023 returned: always
1024 type: complex
1025 version_added: 10.1.0
1026 contains:
1027 allowed_methods:
1028 description: Methods allowed by the cache behavior.
1029 returned: always
1030 type: complex
1031 contains:
1032 cached_methods:
1033 description: Methods cached by the cache behavior.
1034 returned: always
1035 type: complex
1036 contains:
1037 elements:
1038 description: List of cached methods.
1039 returned: always
1040 type: list
1041 sample:
1042 - HEAD
1043 - GET
1044 quantity:
1045 description: Count of cached methods.
1046 returned: always
1047 type: int
1048 sample: 2
1049 elements:
1050 description: List of methods allowed by the cache behavior.
1051 returned: always
1052 type: list
1053 sample:
1054 - HEAD
1055 - GET
1056 quantity:
1057 description: Count of methods allowed by the cache behavior.
1058 returned: always
1059 type: int
1060 sample: 2
1061 compress:
1062 description: Whether compression is turned on for the cache behavior.
1063 returned: always
1064 type: bool
1065 sample: false
1066 default_ttl:
1067 description: Default Time to Live of the cache behavior.
1068 returned: always
1069 type: int
1070 sample: 86400
1071 forwarded_values:
1072 description: Values forwarded to the origin for this cache behavior.
1073 returned: always
1074 type: complex
1075 contains:
1076 cookies:
1077 description: Cookies to forward to the origin.
1078 returned: always
1079 type: complex
1080 contains:
1081 forward:
1082 description: Which cookies to forward to the origin for this cache behavior.
1083 returned: always
1084 type: str
1085 sample: none
1086 whitelisted_names:
1087 description: The names of the cookies to forward to the origin for this cache behavior.
1088 returned: when I(forward=whitelist)
1089 type: complex
1090 contains:
1091 quantity:
1092 description: Count of cookies to forward.
1093 returned: always
1094 type: int
1095 sample: 1
1096 elements:
1097 description: List of cookies to forward.
1098 returned: when list is not empty
1099 type: list
1100 sample: my_cookie
1101 headers:
1102 description: Which headers are used to vary on cache retrievals.
1103 returned: always
1104 type: complex
1105 contains:
1106 quantity:
1107 description: Count of headers to vary on.
1108 returned: always
1109 type: int
1110 sample: 1
1111 elements:
1112 description: List of headers to vary on.
1113 returned: when list is not empty
1114 type: list
1115 sample:
1116 - Host
1117 query_string:
1118 description: Whether the query string is used in cache lookups.
1119 returned: always
1120 type: bool
1121 sample: false
1122 query_string_cache_keys:
1123 description: Which query string keys to use in cache lookups.
1124 returned: always
1125 type: complex
1126 contains:
1127 quantity:
1128 description: Count of query string cache keys to use in cache lookups.
1129 returned: always
1130 type: int
1131 sample: 1
1132 elements:
1133 description: List of query string cache keys to use in cache lookups.
1134 returned: when list is not empty
1135 type: list
1136 sample:
1137 lambda_function_associations:
1138 description: Lambda function associations for a cache behavior.
1139 returned: always
1140 type: complex
1141 contains:
1142 quantity:
1143 description: Count of lambda function associations.
1144 returned: always
1145 type: int
1146 sample: 1
1147 elements:
1148 description: List of lambda function associations.
1149 returned: when list is not empty
1150 type: list
1151 sample:
1152 - lambda_function_arn: arn:aws:lambda:123456789012:us-east-1/lambda/lambda-function
1153 event_type: viewer-response
1154 max_ttl:
1155 description: Maximum Time to Live.
1156 returned: always
1157 type: int
1158 sample: 31536000
1159 min_ttl:
1160 description: Minimum Time to Live.
1161 returned: always
1162 type: int
1163 sample: 0
1164 path_pattern:
1165 description: Path pattern that determines this cache behavior.
1166 returned: always
1167 type: str
1168 sample: /path/to/files/*
1169 smooth_streaming:
1170 description: Whether smooth streaming is enabled.
1171 returned: always
1172 type: bool
1173 sample: false
1174 target_origin_id:
1175 description: ID of origin reference by this cache behavior.
1176 returned: always
1177 type: str
1178 sample: origin_abcd
1179 trusted_signers:
1180 description: Trusted signers.
1181 returned: always
1182 type: complex
1183 contains:
1184 enabled:
1185 description: Whether trusted signers are enabled for this cache behavior.
1186 returned: always
1187 type: bool
1188 sample: false
1189 quantity:
1190 description: Count of trusted signers.
1191 returned: always
1192 type: int
1193 sample: 1
1194 viewer_protocol_policy:
1195 description: Policy of how to handle http/https.
1196 returned: always
1197 type: str
1198 sample: redirect-to-https
1199 quantity:
1200 description: Count of cache behaviors.
1201 returned: always
1202 type: int
1203 sample: 1
1204
1205 caller_reference:
1206 description: Idempotency reference given when creating CloudFront distribution.
1207 returned: always
1208 type: str
1209 sample: '1484796016700'
1210 comment:
1211 description: Any comments you want to include about the distribution.
1212 returned: always
1213 type: str
1214 sample: 'my first CloudFront distribution'
1215 custom_error_responses:
1216 description: Custom error responses to use for error handling.
1217 returned: always
1218 type: complex
1219 contains:
1220 items:
1221 description:
1222 - List of custom error responses.
1223 - This return value has been deprecated and will be removed in a release after 2026-12-16.
1224 Use RV(custom_error_responses.elements) instead.
1225 returned: always
1226 type: complex
1227 contains:
1228 error_caching_min_ttl:
1229 description: Minimum time to cache this error response.
1230 returned: always
1231 type: int
1232 sample: 300
1233 error_code:
1234 description: Origin response code that triggers this error response.
1235 returned: always
1236 type: int
1237 sample: 500
1238 response_code:
1239 description: Response code to return to the requester.
1240 returned: always
1241 type: str
1242 sample: '500'
1243 response_page_path:
1244 description: Path that contains the error page to display.
1245 returned: always
1246 type: str
1247 sample: /errors/5xx.html
1248 elements:
1249 description: List of custom error responses.
1250 returned: always
1251 type: complex
1252 version_added: 10.1.0
1253 contains:
1254 error_caching_min_ttl:
1255 description: Minimum time to cache this error response.
1256 returned: always
1257 type: int
1258 sample: 300
1259 error_code:
1260 description: Origin response code that triggers this error response.
1261 returned: always
1262 type: int
1263 sample: 500
1264 response_code:
1265 description: Response code to return to the requester.
1266 returned: always
1267 type: str
1268 sample: '500'
1269 response_page_path:
1270 description: Path that contains the error page to display.
1271 returned: always
1272 type: str
1273 sample: /errors/5xx.html
1274 quantity:
1275 description: Count of custom error response items
1276 returned: always
1277 type: int
1278 sample: 1
1279 default_cache_behavior:
1280 description: Default cache behavior.
1281 returned: always
1282 type: complex
1283 contains:
1284 allowed_methods:
1285 description: Methods allowed by the cache behavior.
1286 returned: always
1287 type: complex
1288 contains:
1289 cached_methods:
1290 description: Methods cached by the cache behavior.
1291 returned: always
1292 type: complex
1293 contains:
1294 items:
1295 description:
1296 - List of cached methods.
1297 - This return value has been deprecated and will be removed in a release after 2026-12-16.
1298 Use RV(default_cache_behavior.allowed_methods.cached_methods.elements) instead.
1299 returned: always
1300 type: list
1301 sample:
1302 - HEAD
1303 - GET
1304 elements:
1305 description: List of cached methods.
1306 returned: always
1307 type: list
1308 version_added: 10.1.0
1309 sample:
1310 - HEAD
1311 - GET
1312 quantity:
1313 description: Count of cached methods.
1314 returned: always
1315 type: int
1316 sample: 2
1317 items:
1318 description:
1319 - List of methods allowed by the cache behavior.
1320 - This return value has been deprecated and will be removed in a release after 2026-12-16.
1321 Use RV(default_cache_behavior.allowed_methods.elements) instead.
1322 returned: always
1323 type: list
1324 sample:
1325 - HEAD
1326 - GET
1327 elements:
1328 description: List of methods allowed by the cache behavior.
1329 returned: always
1330 type: list
1331 version_added: 10.1.0
1332 sample:
1333 - HEAD
1334 - GET
1335 quantity:
1336 description: Count of methods allowed by the cache behavior.
1337 returned: always
1338 type: int
1339 sample: 2
1340 compress:
1341 description: Whether compression is turned on for the cache behavior.
1342 returned: always
1343 type: bool
1344 sample: false
1345 default_ttl:
1346 description: Default Time to Live of the cache behavior.
1347 returned: always
1348 type: int
1349 sample: 86400
1350 forwarded_values:
1351 description: Values forwarded to the origin for this cache behavior.
1352 returned: always
1353 type: complex
1354 contains:
1355 cookies:
1356 description: Cookies to forward to the origin.
1357 returned: always
1358 type: complex
1359 contains:
1360 forward:
1361 description: Which cookies to forward to the origin for this cache behavior.
1362 returned: always
1363 type: str
1364 sample: none
1365 whitelisted_names:
1366 description: The names of the cookies to forward to the origin for this cache behavior.
1367 returned: when I(forward=whitelist)
1368 type: complex
1369 contains:
1370 quantity:
1371 description: Count of cookies to forward.
1372 returned: always
1373 type: int
1374 sample: 1
1375 items:
1376 description: List of cookies to forward.
1377 returned: when list is not empty
1378 type: list
1379 sample: my_cookie
1380 elements:
1381 description:
1382 - List of cookies to forward.
1383 - This return value has been deprecated and will be removed in a release after 2026-12-16.
1384 Use RV(default_cache_behavior.forwarded_values.cookies.whitelisted_names.elements) instead.
1385 returned: when list is not empty
1386 version_added: 10.1.0
1387 type: list
1388 sample: my_cookie
1389 headers:
1390 description: Which headers are used to vary on cache retrievals.
1391 returned: always
1392 type: complex
1393 contains:
1394 quantity:
1395 description: Count of headers to vary on.
1396 returned: always
1397 type: int
1398 sample: 1
1399 items:
1400 description:
1401 - List of headers to vary on.
1402 - This return value has been deprecated and will be removed in a release after 2026-12-16.
1403 Use RV(default_cache_behavior.forwarded_values.headers.elements) instead.
1404 returned: when list is not empty
1405 type: list
1406 sample:
1407 - Host
1408 elements:
1409 description: List of headers to vary on.
1410 returned: when list is not empty
1411 type: list
1412 version_added: 10.1.0
1413 sample:
1414 - Host
1415 query_string:
1416 description: Whether the query string is used in cache lookups.
1417 returned: always
1418 type: bool
1419 sample: false
1420 query_string_cache_keys:
1421 description: Which query string keys to use in cache lookups.
1422 returned: always
1423 type: complex
1424 contains:
1425 quantity:
1426 description: Count of query string cache keys to use in cache lookups.
1427 returned: always
1428 type: int
1429 sample: 1
1430 items:
1431 description:
1432 - List of query string cache keys to use in cache lookups.
1433 - This return value has been deprecated and will be removed in a release after 2026-12-16.
1434 Use RV(default_cache_behavior.forwarded_values.query_string_cache_keys.elements) instead.
1435 returned: when list is not empty
1436 type: list
1437 elements:
1438 description: List of query string cache keys to use in cache lookups.
1439 returned: when list is not empty
1440 type: list
1441 version_added: 10.1.0
1442 lambda_function_associations:
1443 description: Lambda function associations for a cache behavior.
1444 returned: always
1445 type: complex
1446 contains:
1447 quantity:
1448 description: Count of lambda function associations.
1449 returned: always
1450 type: int
1451 sample: 1
1452 items:
1453 description:
1454 - List of lambda function associations.
1455 - This return value has been deprecated and will be removed in a release after 2026-12-16.
1456 Use RV(default_cache_behavior.lambda_function_associations.elements) instead.
1457 returned: when list is not empty
1458 type: list
1459 sample:
1460 - lambda_function_arn: arn:aws:lambda:123456789012:us-east-1/lambda/lambda-function
1461 event_type: viewer-response
1462 elements:
1463 description: List of lambda function associations.
1464 returned: when list is not empty
1465 type: list
1466 version_added: 10.1.0
1467 sample:
1468 - lambda_function_arn: arn:aws:lambda:123456789012:us-east-1/lambda/lambda-function
1469 event_type: viewer-response
1470 max_ttl:
1471 description: Maximum Time to Live.
1472 returned: always
1473 type: int
1474 sample: 31536000
1475 min_ttl:
1476 description: Minimum Time to Live.
1477 returned: always
1478 type: int
1479 sample: 0
1480 path_pattern:
1481 description: Path pattern that determines this cache behavior.
1482 returned: always
1483 type: str
1484 sample: /path/to/files/*
1485 smooth_streaming:
1486 description: Whether smooth streaming is enabled.
1487 returned: always
1488 type: bool
1489 sample: false
1490 target_origin_id:
1491 description: ID of origin reference by this cache behavior.
1492 returned: always
1493 type: str
1494 sample: origin_abcd
1495 trusted_signers:
1496 description: Trusted signers.
1497 returned: always
1498 type: complex
1499 contains:
1500 enabled:
1501 description: Whether trusted signers are enabled for this cache behavior.
1502 returned: always
1503 type: bool
1504 sample: false
1505 quantity:
1506 description: Count of trusted signers.
1507 returned: always
1508 type: int
1509 sample: 1
1510 viewer_protocol_policy:
1511 description: Policy of how to handle http/https.
1512 returned: always
1513 type: str
1514 sample: redirect-to-https
1515 default_root_object:
1516 description: The object that you want CloudFront to request from your origin (for example, index.html)
1517 when a viewer requests the root URL for your distribution.
1518 returned: always
1519 type: str
1520 sample: ''
1521 diff:
1522 description: Difference between previous configuration and new configuration.
1523 returned: always
1524 type: dict
1525 sample: {}
1526 domain_name:
1527 description: Domain name of CloudFront distribution.
1528 returned: always
1529 type: str
1530 sample: d1vz8pzgurxosf.cloudfront.net
1531 enabled:
1532 description: Whether the CloudFront distribution is enabled or not.
1533 returned: always
1534 type: bool
1535 sample: true
1536 http_version:
1537 description: Version of HTTP supported by the distribution.
1538 returned: always
1539 type: str
1540 sample: http2
1541 id:
1542 description: CloudFront distribution ID.
1543 returned: always
1544 type: str
1545 sample: E123456ABCDEFG
1546 in_progress_invalidation_batches:
1547 description: The number of invalidation batches currently in progress.
1548 returned: always
1549 type: int
1550 sample: 0
1551 is_ipv6_enabled:
1552 description: Whether IPv6 is enabled.
1553 returned: always
1554 type: bool
1555 sample: true
1556 last_modified_time:
1557 description: Date and time distribution was last modified.
1558 returned: always
1559 type: str
1560 sample: '2017-10-13T01:51:12.656000+00:00'
1561 logging:
1562 description: Logging information.
1563 returned: always
1564 type: complex
1565 contains:
1566 bucket:
1567 description: S3 bucket logging destination.
1568 returned: always
1569 type: str
1570 sample: logs-example-com.s3.amazonaws.com
1571 enabled:
1572 description: Whether logging is enabled.
1573 returned: always
1574 type: bool
1575 sample: true
1576 include_cookies:
1577 description: Whether to log cookies.
1578 returned: always
1579 type: bool
1580 sample: false
1581 prefix:
1582 description: Prefix added to logging object names.
1583 returned: always
1584 type: str
1585 sample: cloudfront/test
1586 origins:
1587 description: Origins in the CloudFront distribution.
1588 returned: always
1589 type: complex
1590 contains:
1591 items:
1592 description:
1593 - List of origins.
1594 - This return value has been deprecated and will be removed in a release after 2026-12-16.
1595 Use RV(origins.elements) instead.
1596 returned: always
1597 type: complex
1598 contains:
1599 custom_headers:
1600 description: Custom headers passed to the origin.
1601 returned: always
1602 type: complex
1603 contains:
1604 quantity:
1605 description: Count of headers.
1606 returned: always
1607 type: int
1608 sample: 1
1609 custom_origin_config:
1610 description: Configuration of the origin.
1611 returned: always
1612 type: complex
1613 contains:
1614 http_port:
1615 description: Port on which HTTP is listening.
1616 returned: always
1617 type: int
1618 sample: 80
1619 https_port:
1620 description: Port on which HTTPS is listening.
1621 returned: always
1622 type: int
1623 sample: 443
1624 origin_keepalive_timeout:
1625 description: Keep-alive timeout.
1626 returned: always
1627 type: int
1628 sample: 5
1629 origin_protocol_policy:
1630 description: Policy of which protocols are supported.
1631 returned: always
1632 type: str
1633 sample: https-only
1634 origin_read_timeout:
1635 description: Timeout for reads to the origin.
1636 returned: always
1637 type: int
1638 sample: 30
1639 origin_ssl_protocols:
1640 description: SSL protocols allowed by the origin.
1641 returned: always
1642 type: complex
1643 contains:
1644 items:
1645 description:
1646 - List of SSL protocols.
1647 - This return value has been deprecated and will be removed in a release after 2026-12-16.
1648 Use RV(origins.elements.custom_origin_config.origin_ssl_protocols.elements) instead.
1649 returned: always
1650 type: list
1651 sample:
1652 - TLSv1
1653 - TLSv1.1
1654 - TLSv1.2
1655 quantity:
1656 description: Count of SSL protocols.
1657 returned: always
1658 type: int
1659 sample: 3
1660 domain_name:
1661 description: Domain name of the origin.
1662 returned: always
1663 type: str
1664 sample: test-origin.example.com
1665 id:
1666 description: ID of the origin.
1667 returned: always
1668 type: str
1669 sample: test-origin.example.com
1670 origin_path:
1671 description: Subdirectory to prefix the request from the S3 or HTTP origin.
1672 returned: always
1673 type: str
1674 sample: ''
1675 connection_attempts:
1676 description: The number of times that CloudFront attempts to connect to the origin.
1677 returned: always
1678 type: int
1679 sample: 3
1680 connection_timeout:
1681 description: The number of seconds that CloudFront waits when trying to establish a connection to the origin.
1682 returned: always
1683 type: int
1684 sample: 10
1685 origin_shield:
1686 description: Configuration of the origin Origin Shield.
1687 returned: always
1688 type: complex
1689 contains:
1690 enabled:
1691 description: Whether Origin Shield is enabled or not.
1692 returned: always
1693 type: bool
1694 sample: false
1695 origin_shield_region:
1696 description: Which region is used by Origin Shield.
1697 returned: when enabled is true
1698 type: str
1699 sample: us-east-1
1700 version_added: 6.0.0
1701 s3_origin_config:
1702 description: Origin access identity configuration for S3 Origin.
1703 returned: when s3_origin_access_identity_enabled is true
1704 type: dict
1705 contains:
1706 origin_access_identity:
1707 type: str
1708 description: The origin access id as a path.
1709 sample: origin-access-identity/cloudfront/EXAMPLEID
1710 elements:
1711 description: List of origins.
1712 returned: always
1713 version_added: 10.1.0
1714 type: complex
1715 contains:
1716 custom_headers:
1717 description: Custom headers passed to the origin.
1718 returned: always
1719 type: complex
1720 contains:
1721 quantity:
1722 description: Count of headers.
1723 returned: always
1724 type: int
1725 sample: 1
1726 custom_origin_config:
1727 description: Configuration of the origin.
1728 returned: always
1729 type: complex
1730 contains:
1731 http_port:
1732 description: Port on which HTTP is listening.
1733 returned: always
1734 type: int
1735 sample: 80
1736 https_port:
1737 description: Port on which HTTPS is listening.
1738 returned: always
1739 type: int
1740 sample: 443
1741 origin_keepalive_timeout:
1742 description: Keep-alive timeout.
1743 returned: always
1744 type: int
1745 sample: 5
1746 origin_protocol_policy:
1747 description: Policy of which protocols are supported.
1748 returned: always
1749 type: str
1750 sample: https-only
1751 origin_read_timeout:
1752 description: Timeout for reads to the origin.
1753 returned: always
1754 type: int
1755 sample: 30
1756 origin_ssl_protocols:
1757 description: SSL protocols allowed by the origin.
1758 returned: always
1759 type: complex
1760 contains:
1761 elements:
1762 description: List of SSL protocols.
1763 returned: always
1764 type: list
1765 sample:
1766 - TLSv1
1767 - TLSv1.1
1768 - TLSv1.2
1769 quantity:
1770 description: Count of SSL protocols.
1771 returned: always
1772 type: int
1773 sample: 3
1774 domain_name:
1775 description: Domain name of the origin.
1776 returned: always
1777 type: str
1778 sample: test-origin.example.com
1779 id:
1780 description: ID of the origin.
1781 returned: always
1782 type: str
1783 sample: test-origin.example.com
1784 origin_path:
1785 description: Subdirectory to prefix the request from the S3 or HTTP origin.
1786 returned: always
1787 type: str
1788 sample: ''
1789 connection_attempts:
1790 description: The number of times that CloudFront attempts to connect to the origin.
1791 returned: always
1792 type: int
1793 sample: 3
1794 connection_timeout:
1795 description: The number of seconds that CloudFront waits when trying to establish a connection to the origin.
1796 returned: always
1797 type: int
1798 sample: 10
1799 origin_shield:
1800 description: Configuration of the origin Origin Shield.
1801 returned: always
1802 type: complex
1803 contains:
1804 enabled:
1805 description: Whether Origin Shield is enabled or not.
1806 returned: always
1807 type: bool
1808 sample: false
1809 origin_shield_region:
1810 description: Which region is used by Origin Shield.
1811 returned: when enabled is true
1812 type: str
1813 sample: us-east-1
1814 version_added: 6.0.0
1815 s3_origin_config:
1816 description: Origin access identity configuration for S3 Origin.
1817 returned: when s3_origin_access_identity_enabled is true
1818 type: dict
1819 contains:
1820 origin_access_identity:
1821 type: str
1822 description: The origin access id as a path.
1823 sample: origin-access-identity/cloudfront/EXAMPLEID
1824 quantity:
1825 description: Count of origins.
1826 returned: always
1827 type: int
1828 sample: 1
1829 price_class:
1830 description: Price class of CloudFront distribution.
1831 returned: always
1832 type: str
1833 sample: PriceClass_All
1834 restrictions:
1835 description: Restrictions in use by CloudFront.
1836 returned: always
1837 type: complex
1838 contains:
1839 geo_restriction:
1840 description: Controls the countries in which your content is distributed.
1841 returned: always
1842 type: complex
1843 contains:
1844 quantity:
1845 description: Count of restrictions.
1846 returned: always
1847 type: int
1848 sample: 1
1849 items:
1850 description:
1851 - List of country codes allowed or disallowed.
1852 - This return value has been deprecated and will be removed in a release after 2026-12-16.
1853 Use RV(restrictions.geo_restriction.elements) instead.
1854 returned: always
1855 type: list
1856 sample: xy
1857 elements:
1858 description: List of country codes allowed or disallowed.
1859 returned: always
1860 type: list
1861 version_added: 10.1.0
1862 sample: xy
1863 restriction_type:
1864 description: Type of restriction.
1865 returned: always
1866 type: str
1867 sample: blacklist
1868 status:
1869 description: Status of the CloudFront distribution.
1870 returned: always
1871 type: str
1872 sample: InProgress
1873 tags:
1874 description: Distribution tags.
1875 returned: always
1876 type: dict
1877 sample:
1878 Hello: World
1879 viewer_certificate:
1880 description: Certificate used by CloudFront distribution.
1881 returned: always
1882 type: complex
1883 contains:
1884 acm_certificate_arn:
1885 description: ARN of ACM certificate.
1886 returned: when certificate comes from ACM
1887 type: str
1888 sample: arn:aws:acm:us-east-1:123456789012:certificate/abcd1234-1234-1234-abcd-123456abcdef
1889 certificate:
1890 description: Reference to certificate.
1891 returned: always
1892 type: str
1893 sample: arn:aws:acm:us-east-1:123456789012:certificate/abcd1234-1234-1234-abcd-123456abcdef
1894 certificate_source:
1895 description: Where certificate comes from.
1896 returned: always
1897 type: str
1898 sample: acm
1899 minimum_protocol_version:
1900 description: Minimum SSL/TLS protocol supported by this distribution.
1901 returned: always
1902 type: str
1903 sample: TLSv1
1904 ssl_support_method:
1905 description: Support for pre-SNI browsers or not.
1906 returned: always
1907 type: str
1908 sample: sni-only
1909 web_acl_id:
1910 description: ID of Web Access Control List (from WAF service).
1911 returned: always
1912 type: str
1913 sample: abcd1234-1234-abcd-abcd-abcd12345678
1914 """
1915
1916 import datetime
1917 import re
1918 from collections import OrderedDict
1919
1920 try:
1921 import botocore
1922 except ImportError:
1923 pass # caught by AnsibleAWSModule
1924
1925 from ansible.module_utils._text import to_native
1926 from ansible.module_utils._text import to_text
1927 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
1928 from ansible.module_utils.common.dict_transformations import recursive_diff
1929 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
1930
1931 from ansible_collections.amazon.aws.plugins.module_utils.cloudfront_facts import CloudFrontFactsServiceManager
1932 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
1933 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
1934 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
1935 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
1936
1937 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
1938
1939
1940 def change_dict_key_name(dictionary, old_key, new_key):
1941 if old_key in dictionary:
1942 dictionary[new_key] = dictionary.get(old_key)
1943 dictionary.pop(old_key, None)
1944 return dictionary
1945
1946
1947 def merge_validation_into_config(config, validated_node, node_name):
1948 if validated_node is not None:
1949 if isinstance(validated_node, dict):
1950 config_node = config.get(node_name)
1951 if config_node is not None:
1952 config_node_items = list(config_node.items())
1953 else:
1954 config_node_items = []
1955 config[node_name] = dict(config_node_items + list(validated_node.items()))
1956 if isinstance(validated_node, list):
1957 config[node_name] = list(set(config.get(node_name) + validated_node))
1958 return config
1959
1960
1961 def ansible_list_to_cloudfront_list(list_items=None, include_quantity=True):
1962 if list_items is None:
1963 list_items = []
1964 if not isinstance(list_items, list):
1965 raise ValueError(f"Expected a list, got a {type(list_items).__name__} with value {str(list_items)}")
1966 result = {}
1967 if include_quantity:
1968 result["quantity"] = len(list_items)
1969 if len(list_items) > 0:
1970 result["items"] = list_items
1971 return result
1972
1973
1974 def create_distribution(client, module, config, tags):
1975 try:
1976 if not tags:
1977 return client.create_distribution(aws_retry=True, DistributionConfig=config)["Distribution"]
1978 else:
1979 distribution_config_with_tags = {"DistributionConfig": config, "Tags": {"Items": tags}}
1980 return client.create_distribution_with_tags(
1981 aws_retry=True, DistributionConfigWithTags=distribution_config_with_tags
1982 )["Distribution"]
1983 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
1984 module.fail_json_aws(e, msg="Error creating distribution")
1985
1986
1987 def delete_distribution(client, module, distribution):
1988 try:
1989 return client.delete_distribution(
1990 aws_retry=True, Id=distribution["Distribution"]["Id"], IfMatch=distribution["ETag"]
1991 )
1992 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
1993 module.fail_json_aws(e, msg=f"Error deleting distribution {to_native(distribution['Distribution'])}")
1994
1995
1996 def update_distribution(client, module, config, distribution_id, e_tag):
1997 try:
1998 return client.update_distribution(aws_retry=True, DistributionConfig=config, Id=distribution_id, IfMatch=e_tag)[
1999 "Distribution"
2000 ]
2001 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
2002 module.fail_json_aws(e, msg=f"Error updating distribution to {to_native(config)}")
2003
2004
2005 def tag_resource(client, module, arn, tags):
2006 try:
2007 return client.tag_resource(aws_retry=True, Resource=arn, Tags=dict(Items=tags))
2008 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
2009 module.fail_json_aws(e, msg="Error tagging resource")
2010
2011
2012 def untag_resource(client, module, arn, tag_keys):
2013 try:
2014 return client.untag_resource(aws_retry=True, Resource=arn, TagKeys=dict(Items=tag_keys))
2015 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
2016 module.fail_json_aws(e, msg="Error untagging resource")
2017
2018
2019 def list_tags_for_resource(client, module, arn):
2020 try:
2021 response = client.list_tags_for_resource(aws_retry=True, Resource=arn)
2022 return boto3_tag_list_to_ansible_dict(response.get("Tags").get("Items"))
2023 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
2024 module.fail_json_aws(e, msg="Error listing tags for resource")
2025
2026
2027 def update_tags(client, module, existing_tags, valid_tags, purge_tags, arn):
2028 if valid_tags is None:
2029 return False
2030 changed = False
2031 to_add, to_remove = compare_aws_tags(existing_tags, valid_tags, purge_tags)
2032 if to_remove:
2033 untag_resource(client, module, arn, to_remove)
2034 changed = True
2035 if to_add:
2036 tag_resource(client, module, arn, ansible_dict_to_boto3_tag_list(to_add))
2037 changed = True
2038 return changed
2039
2040
2041 class CloudFrontValidationManager(object):
2042 """
2043 Manages CloudFront validations
2044 """
2045
2046 def __init__(self, module):
2047 self.__cloudfront_facts_mgr = CloudFrontFactsServiceManager(module)
2048 self.module = module
2049 self.__default_distribution_enabled = True
2050 self.__default_http_port = 80
2051 self.__default_https_port = 443
2052 self.__default_ipv6_enabled = False
2053 self.__default_origin_ssl_protocols = [
2054 "TLSv1",
2055 "TLSv1.1",
2056 "TLSv1.2",
2057 ]
2058 self.__default_custom_origin_protocol_policy = "match-viewer"
2059 self.__default_custom_origin_read_timeout = 30
2060 self.__default_custom_origin_keepalive_timeout = 5
2061 self.__default_datetime_string = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")
2062 self.__default_cache_behavior_min_ttl = 0
2063 self.__default_cache_behavior_max_ttl = 31536000
2064 self.__default_cache_behavior_default_ttl = 86400
2065 self.__default_cache_behavior_compress = False
2066 self.__default_cache_behavior_viewer_protocol_policy = "allow-all"
2067 self.__default_cache_behavior_smooth_streaming = False
2068 self.__default_cache_behavior_forwarded_values_forward_cookies = "none"
2069 self.__default_cache_behavior_forwarded_values_query_string = True
2070 self.__default_trusted_signers_enabled = False
2071 self.__valid_price_classes = set(
2072 [
2073 "PriceClass_100",
2074 "PriceClass_200",
2075 "PriceClass_All",
2076 ]
2077 )
2078 self.__valid_origin_protocol_policies = set(
2079 [
2080 "http-only",
2081 "match-viewer",
2082 "https-only",
2083 ]
2084 )
2085 self.__valid_origin_ssl_protocols = set(
2086 [
2087 "SSLv3",
2088 "TLSv1",
2089 "TLSv1.1",
2090 "TLSv1.2",
2091 ]
2092 )
2093 self.__valid_cookie_forwarding = set(
2094 [
2095 "none",
2096 "whitelist",
2097 "all",
2098 ]
2099 )
2100 self.__valid_viewer_protocol_policies = set(
2101 [
2102 "allow-all",
2103 "https-only",
2104 "redirect-to-https",
2105 ]
2106 )
2107 self.__valid_methods = set(
2108 [
2109 "GET",
2110 "HEAD",
2111 "POST",
2112 "PUT",
2113 "PATCH",
2114 "OPTIONS",
2115 "DELETE",
2116 ]
2117 )
2118 self.__valid_methods_cached_methods = [
2119 set(
2120 [
2121 "GET",
2122 "HEAD",
2123 ]
2124 ),
2125 set(
2126 [
2127 "GET",
2128 "HEAD",
2129 "OPTIONS",
2130 ]
2131 ),
2132 ]
2133 self.__valid_methods_allowed_methods = [
2134 self.__valid_methods_cached_methods[0],
2135 self.__valid_methods_cached_methods[1],
2136 self.__valid_methods,
2137 ]
2138 self.__valid_lambda_function_association_event_types = set(
2139 [
2140 "viewer-request",
2141 "viewer-response",
2142 "origin-request",
2143 "origin-response",
2144 ]
2145 )
2146 self.__valid_viewer_certificate_ssl_support_methods = set(
2147 [
2148 "sni-only",
2149 "vip",
2150 ]
2151 )
2152 self.__valid_viewer_certificate_minimum_protocol_versions = set(
2153 [
2154 "SSLv3",
2155 "TLSv1",
2156 "TLSv1_2016",
2157 "TLSv1.1_2016",
2158 "TLSv1.2_2018",
2159 "TLSv1.2_2019",
2160 "TLSv1.2_2021",
2161 ]
2162 )
2163 self.__valid_viewer_certificate_certificate_sources = set(
2164 [
2165 "cloudfront",
2166 "iam",
2167 "acm",
2168 ]
2169 )
2170 self.__valid_http_versions = set(
2171 [
2172 "http1.1",
2173 "http2",
2174 "http3",
2175 "http2and3",
2176 ]
2177 )
2178 self.__s3_bucket_domain_regex = re.compile(r"\.s3(?:\.[^.]+)?\.amazonaws\.com$")
2179
2180 def add_missing_key(self, dict_object, key_to_set, value_to_set):
2181 if key_to_set not in dict_object and value_to_set is not None:
2182 dict_object[key_to_set] = value_to_set
2183 return dict_object
2184
2185 def add_key_else_change_dict_key(self, dict_object, old_key, new_key, value_to_set):
2186 if old_key not in dict_object and value_to_set is not None:
2187 dict_object[new_key] = value_to_set
2188 else:
2189 dict_object = change_dict_key_name(dict_object, old_key, new_key)
2190 return dict_object
2191
2192 def add_key_else_validate(
2193 self, dict_object, key_name, attribute_name, value_to_set, valid_values, to_aws_list=False
2194 ):
2195 if key_name in dict_object:
2196 self.validate_attribute_with_allowed_values(value_to_set, attribute_name, valid_values)
2197 else:
2198 if to_aws_list:
2199 dict_object[key_name] = ansible_list_to_cloudfront_list(value_to_set)
2200 elif value_to_set is not None:
2201 dict_object[key_name] = value_to_set
2202 return dict_object
2203
2204 def validate_logging(self, logging):
2205 try:
2206 if logging is None:
2207 return None
2208 valid_logging = {}
2209 if logging and not set(["enabled", "include_cookies", "bucket", "prefix"]).issubset(logging):
2210 self.module.fail_json(
2211 msg="The logging parameters enabled, include_cookies, bucket and prefix must be specified."
2212 )
2213 valid_logging["include_cookies"] = logging.get("include_cookies")
2214 valid_logging["enabled"] = logging.get("enabled")
2215 valid_logging["bucket"] = logging.get("bucket")
2216 valid_logging["prefix"] = logging.get("prefix")
2217 return valid_logging
2218 except Exception as e:
2219 self.module.fail_json_aws(e, msg="Error validating distribution logging")
2220
2221 def validate_is_list(self, list_to_validate, list_name):
2222 if not isinstance(list_to_validate, list):
2223 self.module.fail_json(msg=f"{list_name} is of type {type(list_to_validate).__name__}. Must be a list.")
2224
2225 def validate_required_key(self, key_name, full_key_name, dict_object):
2226 if key_name not in dict_object:
2227 self.module.fail_json(msg=f"{full_key_name} must be specified.")
2228
2229 def validate_origins(
2230 self,
2231 client,
2232 config,
2233 origins,
2234 default_origin_domain_name,
2235 default_origin_path,
2236 create,
2237 purge_origins=False,
2238 ):
2239 try:
2240 if origins is None:
2241 if default_origin_domain_name is None and not create:
2242 if purge_origins:
2243 return None
2244 else:
2245 return ansible_list_to_cloudfront_list(config)
2246 if default_origin_domain_name is not None:
2247 origins = [{"domain_name": default_origin_domain_name, "origin_path": default_origin_path or ""}]
2248 else:
2249 origins = []
2250 self.validate_is_list(origins, "origins")
2251 if not origins and default_origin_domain_name is None and create:
2252 self.module.fail_json(
2253 msg="Both origins[] and default_origin_domain_name have not been specified. Please specify at least one."
2254 )
2255 all_origins = OrderedDict()
2256 new_domains = list()
2257 for origin in config:
2258 all_origins[origin.get("domain_name")] = origin
2259 for origin in origins:
2260 origin = self.validate_origin(
2261 client, all_origins.get(origin.get("domain_name"), {}), origin, default_origin_path
2262 )
2263 all_origins[origin["domain_name"]] = origin
2264 new_domains.append(origin["domain_name"])
2265 if purge_origins:
2266 for domain in list(all_origins.keys()):
2267 if domain not in new_domains:
2268 del all_origins[domain]
2269 return ansible_list_to_cloudfront_list(list(all_origins.values()))
2270 except Exception as e:
2271 self.module.fail_json_aws(e, msg="Error validating distribution origins")
2272
2273 def validate_s3_origin_configuration(self, client, existing_config, origin):
2274 if origin.get("s3_origin_config", {}).get("origin_access_identity"):
2275 return origin["s3_origin_config"]["origin_access_identity"]
2276
2277 if existing_config.get("s3_origin_config", {}).get("origin_access_identity"):
2278 return existing_config["s3_origin_config"]["origin_access_identity"]
2279
2280 try:
2281 comment = f"access-identity-by-ansible-{origin.get('domain_name')}-{self.__default_datetime_string}"
2282 caller_reference = f"{origin.get('domain_name')}-{self.__default_datetime_string}"
2283 cfoai_config = dict(
2284 CloudFrontOriginAccessIdentityConfig=dict(CallerReference=caller_reference, Comment=comment)
2285 )
2286 oai = client.create_cloud_front_origin_access_identity(**cfoai_config)["CloudFrontOriginAccessIdentity"][
2287 "Id"
2288 ]
2289 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
2290 self.module.fail_json_aws(e, msg=f"Couldn't create Origin Access Identity for id {origin['id']}")
2291 return f"origin-access-identity/cloudfront/{oai}"
2292
2293 def validate_origin(self, client, existing_config, origin, default_origin_path):
2294 try:
2295 origin = self.add_missing_key(
2296 origin, "origin_path", existing_config.get("origin_path", default_origin_path or "")
2297 )
2298 self.validate_required_key("origin_path", "origins[].origin_path", origin)
2299 origin = self.add_missing_key(origin, "id", existing_config.get("id", self.__default_datetime_string))
2300 if "custom_headers" in origin and len(origin.get("custom_headers")) > 0:
2301 for custom_header in origin.get("custom_headers"):
2302 if "header_name" not in custom_header or "header_value" not in custom_header:
2303 self.module.fail_json(
2304 msg="Both origins[].custom_headers.header_name and origins[].custom_headers.header_value must be specified."
2305 )
2306 origin["custom_headers"] = ansible_list_to_cloudfront_list(origin.get("custom_headers"))
2307 else:
2308 origin["custom_headers"] = ansible_list_to_cloudfront_list()
2309 if "origin_shield" in origin:
2310 origin_shield = origin.get("origin_shield")
2311 if origin_shield.get("enabled"):
2312 origin_shield_region = origin_shield.get("origin_shield_region")
2313 if origin_shield_region is None:
2314 self.module.fail_json(
2315 msg="origins[].origin_shield.origin_shield_region must be specified"
2316 " when origins[].origin_shield.enabled is true."
2317 )
2318 else:
2319 origin_shield_region = origin_shield_region.lower()
2320 if self.__s3_bucket_domain_regex.search(origin.get("domain_name").lower()):
2321 if origin.get("s3_origin_access_identity_enabled") is not None:
2322 if origin["s3_origin_access_identity_enabled"]:
2323 s3_origin_config = self.validate_s3_origin_configuration(client, existing_config, origin)
2324 else:
2325 s3_origin_config = None
2326
2327 del origin["s3_origin_access_identity_enabled"]
2328
2329 if s3_origin_config:
2330 oai = s3_origin_config
2331 else:
2332 oai = ""
2333
2334 origin["s3_origin_config"] = dict(origin_access_identity=oai)
2335
2336 if "custom_origin_config" in origin:
2337 self.module.fail_json(
2338 msg="s3 origin domains and custom_origin_config are mutually exclusive",
2339 )
2340 else:
2341 origin = self.add_missing_key(
2342 origin, "custom_origin_config", existing_config.get("custom_origin_config", {})
2343 )
2344 custom_origin_config = origin.get("custom_origin_config")
2345 custom_origin_config = self.add_key_else_validate(
2346 custom_origin_config,
2347 "origin_protocol_policy",
2348 "origins[].custom_origin_config.origin_protocol_policy",
2349 self.__default_custom_origin_protocol_policy,
2350 self.__valid_origin_protocol_policies,
2351 )
2352 custom_origin_config = self.add_missing_key(
2353 custom_origin_config, "origin_read_timeout", self.__default_custom_origin_read_timeout
2354 )
2355 custom_origin_config = self.add_missing_key(
2356 custom_origin_config, "origin_keepalive_timeout", self.__default_custom_origin_keepalive_timeout
2357 )
2358 custom_origin_config = self.add_key_else_change_dict_key(
2359 custom_origin_config, "http_port", "h_t_t_p_port", self.__default_http_port
2360 )
2361 custom_origin_config = self.add_key_else_change_dict_key(
2362 custom_origin_config, "https_port", "h_t_t_p_s_port", self.__default_https_port
2363 )
2364 if custom_origin_config.get("origin_ssl_protocols", {}).get("items"):
2365 custom_origin_config["origin_ssl_protocols"] = custom_origin_config["origin_ssl_protocols"]["items"]
2366 if custom_origin_config.get("origin_ssl_protocols"):
2367 self.validate_attribute_list_with_allowed_list(
2368 custom_origin_config["origin_ssl_protocols"],
2369 "origins[].origin_ssl_protocols",
2370 self.__valid_origin_ssl_protocols,
2371 )
2372 else:
2373 custom_origin_config["origin_ssl_protocols"] = self.__default_origin_ssl_protocols
2374 custom_origin_config["origin_ssl_protocols"] = ansible_list_to_cloudfront_list(
2375 custom_origin_config["origin_ssl_protocols"]
2376 )
2377 return origin
2378 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
2379 self.module.fail_json_aws(e, msg="Error validating distribution origin")
2380
2381 def validate_cache_behaviors(self, config, cache_behaviors, valid_origins, purge_cache_behaviors=False):
2382 try:
2383 if cache_behaviors is None and valid_origins is not None and purge_cache_behaviors is False:
2384 return ansible_list_to_cloudfront_list(config)
2385 all_cache_behaviors = OrderedDict()
2386 # cache behaviors are order dependent so we don't preserve the existing ordering when purge_cache_behaviors
2387 # is true (if purge_cache_behaviors is not true, we can't really know the full new order)
2388 if not purge_cache_behaviors:
2389 for behavior in config:
2390 all_cache_behaviors[behavior["path_pattern"]] = behavior
2391 for cache_behavior in cache_behaviors:
2392 valid_cache_behavior = self.validate_cache_behavior(
2393 all_cache_behaviors.get(cache_behavior.get("path_pattern"), {}), cache_behavior, valid_origins
2394 )
2395 all_cache_behaviors[cache_behavior["path_pattern"]] = valid_cache_behavior
2396 if purge_cache_behaviors:
2397 for target_origin_id in set(all_cache_behaviors.keys()) - set(
2398 [cb["path_pattern"] for cb in cache_behaviors]
2399 ):
2400 del all_cache_behaviors[target_origin_id]
2401 return ansible_list_to_cloudfront_list(list(all_cache_behaviors.values()))
2402 except Exception as e:
2403 self.module.fail_json_aws(e, msg="Error validating distribution cache behaviors")
2404
2405 def validate_cache_behavior(self, config, cache_behavior, valid_origins, is_default_cache=False):
2406 if is_default_cache and cache_behavior is None:
2407 cache_behavior = {}
2408 if cache_behavior is None and valid_origins is not None:
2409 return config
2410 cache_behavior = self.validate_cache_behavior_first_level_keys(
2411 config, cache_behavior, valid_origins, is_default_cache
2412 )
2413 if cache_behavior.get("cache_policy_id") is None:
2414 cache_behavior = self.validate_forwarded_values(
2415 config, cache_behavior.get("forwarded_values"), cache_behavior
2416 )
2417 cache_behavior = self.validate_allowed_methods(config, cache_behavior.get("allowed_methods"), cache_behavior)
2418 cache_behavior = self.validate_lambda_function_associations(
2419 config, cache_behavior.get("lambda_function_associations"), cache_behavior
2420 )
2421 cache_behavior = self.validate_trusted_signers(config, cache_behavior.get("trusted_signers"), cache_behavior)
2422 cache_behavior = self.validate_field_level_encryption_id(
2423 config, cache_behavior.get("field_level_encryption_id"), cache_behavior
2424 )
2425 return cache_behavior
2426
2427 def validate_cache_behavior_first_level_keys(self, config, cache_behavior, valid_origins, is_default_cache):
2428 if cache_behavior.get("cache_policy_id") is not None and cache_behavior.get("forwarded_values") is not None:
2429 if is_default_cache:
2430 cache_behavior_name = "Default cache behavior"
2431 else:
2432 cache_behavior_name = f"Cache behavior for path {cache_behavior['path_pattern']}"
2433 self.module.fail_json(
2434 msg=f"{cache_behavior_name} cannot have both a cache_policy_id and a forwarded_values option."
2435 )
2436 try:
2437 if cache_behavior.get("cache_policy_id") is None:
2438 cache_behavior = self.add_key_else_change_dict_key(
2439 cache_behavior,
2440 "min_ttl",
2441 "min_t_t_l",
2442 config.get("min_t_t_l", self.__default_cache_behavior_min_ttl),
2443 )
2444 cache_behavior = self.add_key_else_change_dict_key(
2445 cache_behavior,
2446 "max_ttl",
2447 "max_t_t_l",
2448 config.get("max_t_t_l", self.__default_cache_behavior_max_ttl),
2449 )
2450 cache_behavior = self.add_key_else_change_dict_key(
2451 cache_behavior,
2452 "default_ttl",
2453 "default_t_t_l",
2454 config.get("default_t_t_l", self.__default_cache_behavior_default_ttl),
2455 )
2456 cache_behavior = self.add_missing_key(
2457 cache_behavior, "compress", config.get("compress", self.__default_cache_behavior_compress)
2458 )
2459 target_origin_id = cache_behavior.get("target_origin_id", config.get("target_origin_id"))
2460 if not target_origin_id:
2461 target_origin_id = self.get_first_origin_id_for_default_cache_behavior(valid_origins)
2462 if target_origin_id not in [origin["id"] for origin in valid_origins.get("items", [])]:
2463 if is_default_cache:
2464 cache_behavior_name = "Default cache behavior"
2465 else:
2466 cache_behavior_name = f"Cache behavior for path {cache_behavior['path_pattern']}"
2467 self.module.fail_json(
2468 msg=f"{cache_behavior_name} has target_origin_id pointing to an origin that does not exist."
2469 )
2470 cache_behavior["target_origin_id"] = target_origin_id
2471 cache_behavior = self.add_key_else_validate(
2472 cache_behavior,
2473 "viewer_protocol_policy",
2474 "cache_behavior.viewer_protocol_policy",
2475 config.get("viewer_protocol_policy", self.__default_cache_behavior_viewer_protocol_policy),
2476 self.__valid_viewer_protocol_policies,
2477 )
2478 cache_behavior = self.add_missing_key(
2479 cache_behavior,
2480 "smooth_streaming",
2481 config.get("smooth_streaming", self.__default_cache_behavior_smooth_streaming),
2482 )
2483 return cache_behavior
2484 except Exception as e:
2485 self.module.fail_json_aws(e, msg="Error validating distribution cache behavior first level keys")
2486
2487 def validate_forwarded_values(self, config, forwarded_values, cache_behavior):
2488 try:
2489 if not forwarded_values:
2490 forwarded_values = dict()
2491 existing_config = config.get("forwarded_values", {})
2492 headers = forwarded_values.get("headers", existing_config.get("headers", {}).get("items"))
2493 if headers:
2494 headers.sort()
2495 forwarded_values["headers"] = ansible_list_to_cloudfront_list(headers)
2496 if "cookies" not in forwarded_values:
2497 forward = existing_config.get("cookies", {}).get(
2498 "forward", self.__default_cache_behavior_forwarded_values_forward_cookies
2499 )
2500 forwarded_values["cookies"] = {"forward": forward}
2501 else:
2502 existing_whitelist = existing_config.get("cookies", {}).get("whitelisted_names", {}).get("items")
2503 whitelist = forwarded_values.get("cookies").get("whitelisted_names", existing_whitelist)
2504 if whitelist:
2505 self.validate_is_list(whitelist, "forwarded_values.whitelisted_names")
2506 forwarded_values["cookies"]["whitelisted_names"] = ansible_list_to_cloudfront_list(whitelist)
2507 cookie_forwarding = forwarded_values.get("cookies").get(
2508 "forward", existing_config.get("cookies", {}).get("forward")
2509 )
2510 self.validate_attribute_with_allowed_values(
2511 cookie_forwarding, "cache_behavior.forwarded_values.cookies.forward", self.__valid_cookie_forwarding
2512 )
2513 forwarded_values["cookies"]["forward"] = cookie_forwarding
2514 query_string_cache_keys = forwarded_values.get(
2515 "query_string_cache_keys", existing_config.get("query_string_cache_keys", {}).get("items", [])
2516 )
2517 self.validate_is_list(query_string_cache_keys, "forwarded_values.query_string_cache_keys")
2518 forwarded_values["query_string_cache_keys"] = ansible_list_to_cloudfront_list(query_string_cache_keys)
2519 forwarded_values = self.add_missing_key(
2520 forwarded_values,
2521 "query_string",
2522 existing_config.get("query_string", self.__default_cache_behavior_forwarded_values_query_string),
2523 )
2524 cache_behavior["forwarded_values"] = forwarded_values
2525 return cache_behavior
2526 except Exception as e:
2527 self.module.fail_json_aws(e, msg="Error validating forwarded values")
2528
2529 def validate_lambda_function_associations(self, config, lambda_function_associations, cache_behavior):
2530 try:
2531 if lambda_function_associations is not None:
2532 self.validate_is_list(lambda_function_associations, "lambda_function_associations")
2533 for association in lambda_function_associations:
2534 association = change_dict_key_name(association, "lambda_function_arn", "lambda_function_a_r_n")
2535 self.validate_attribute_with_allowed_values(
2536 association.get("event_type"),
2537 "cache_behaviors[].lambda_function_associations.event_type",
2538 self.__valid_lambda_function_association_event_types,
2539 )
2540 cache_behavior["lambda_function_associations"] = ansible_list_to_cloudfront_list(
2541 lambda_function_associations
2542 )
2543 else:
2544 if "lambda_function_associations" in config:
2545 cache_behavior["lambda_function_associations"] = config.get("lambda_function_associations")
2546 else:
2547 cache_behavior["lambda_function_associations"] = ansible_list_to_cloudfront_list([])
2548 return cache_behavior
2549 except Exception as e:
2550 self.module.fail_json_aws(e, msg="Error validating lambda function associations")
2551
2552 def validate_field_level_encryption_id(self, config, field_level_encryption_id, cache_behavior):
2553 if field_level_encryption_id is not None:
2554 cache_behavior["field_level_encryption_id"] = field_level_encryption_id
2555 elif "field_level_encryption_id" in config:
2556 cache_behavior["field_level_encryption_id"] = config.get("field_level_encryption_id")
2557 else:
2558 cache_behavior["field_level_encryption_id"] = ""
2559 return cache_behavior
2560
2561 def validate_allowed_methods(self, config, allowed_methods, cache_behavior):
2562 try:
2563 if allowed_methods is not None:
2564 self.validate_required_key("items", "cache_behavior.allowed_methods.items[]", allowed_methods)
2565 temp_allowed_items = allowed_methods.get("items")
2566 self.validate_is_list(temp_allowed_items, "cache_behavior.allowed_methods.items")
2567 self.validate_attribute_list_with_allowed_list(
2568 temp_allowed_items, "cache_behavior.allowed_methods.items[]", self.__valid_methods_allowed_methods
2569 )
2570 cached_items = allowed_methods.get("cached_methods")
2571 if "cached_methods" in allowed_methods:
2572 self.validate_is_list(cached_items, "cache_behavior.allowed_methods.cached_methods")
2573 self.validate_attribute_list_with_allowed_list(
2574 cached_items,
2575 "cache_behavior.allowed_items.cached_methods[]",
2576 self.__valid_methods_cached_methods,
2577 )
2578 # we don't care if the order of how cloudfront stores the methods differs - preserving existing
2579 # order reduces likelihood of making unnecessary changes
2580 if "allowed_methods" in config and set(config["allowed_methods"]["items"]) == set(temp_allowed_items):
2581 cache_behavior["allowed_methods"] = config["allowed_methods"]
2582 else:
2583 cache_behavior["allowed_methods"] = ansible_list_to_cloudfront_list(temp_allowed_items)
2584
2585 if cached_items and set(cached_items) == set(
2586 config.get("allowed_methods", {}).get("cached_methods", {}).get("items", [])
2587 ):
2588 cache_behavior["allowed_methods"]["cached_methods"] = config["allowed_methods"]["cached_methods"]
2589 else:
2590 cache_behavior["allowed_methods"]["cached_methods"] = ansible_list_to_cloudfront_list(cached_items)
2591 else:
2592 if "allowed_methods" in config:
2593 cache_behavior["allowed_methods"] = config.get("allowed_methods")
2594 return cache_behavior
2595 except Exception as e:
2596 self.module.fail_json_aws(e, msg="Error validating allowed methods")
2597
2598 def validate_trusted_signers(self, config, trusted_signers, cache_behavior):
2599 try:
2600 if trusted_signers is None:
2601 trusted_signers = {}
2602 if "items" in trusted_signers:
2603 valid_trusted_signers = ansible_list_to_cloudfront_list(trusted_signers.get("items"))
2604 else:
2605 valid_trusted_signers = dict(quantity=config.get("quantity", 0))
2606 if "items" in config:
2607 valid_trusted_signers = dict(items=config["items"])
2608 valid_trusted_signers["enabled"] = trusted_signers.get(
2609 "enabled", config.get("enabled", self.__default_trusted_signers_enabled)
2610 )
2611 cache_behavior["trusted_signers"] = valid_trusted_signers
2612 return cache_behavior
2613 except Exception as e:
2614 self.module.fail_json_aws(e, msg="Error validating trusted signers")
2615
2616 def validate_viewer_certificate(self, viewer_certificate):
2617 try:
2618 if viewer_certificate is None:
2619 return None
2620 if (
2621 viewer_certificate.get("cloudfront_default_certificate")
2622 and viewer_certificate.get("ssl_support_method") is not None
2623 ):
2624 self.module.fail_json(
2625 msg="viewer_certificate.ssl_support_method should not be specified with viewer_certificate_cloudfront_default"
2626 + "_certificate set to true."
2627 )
2628 self.validate_attribute_with_allowed_values(
2629 viewer_certificate.get("ssl_support_method"),
2630 "viewer_certificate.ssl_support_method",
2631 self.__valid_viewer_certificate_ssl_support_methods,
2632 )
2633 self.validate_attribute_with_allowed_values(
2634 viewer_certificate.get("minimum_protocol_version"),
2635 "viewer_certificate.minimum_protocol_version",
2636 self.__valid_viewer_certificate_minimum_protocol_versions,
2637 )
2638 self.validate_attribute_with_allowed_values(
2639 viewer_certificate.get("certificate_source"),
2640 "viewer_certificate.certificate_source",
2641 self.__valid_viewer_certificate_certificate_sources,
2642 )
2643 viewer_certificate = change_dict_key_name(
2644 viewer_certificate, "cloudfront_default_certificate", "cloud_front_default_certificate"
2645 )
2646 viewer_certificate = change_dict_key_name(viewer_certificate, "ssl_support_method", "s_s_l_support_method")
2647 viewer_certificate = change_dict_key_name(viewer_certificate, "iam_certificate_id", "i_a_m_certificate_id")
2648 viewer_certificate = change_dict_key_name(
2649 viewer_certificate, "acm_certificate_arn", "a_c_m_certificate_arn"
2650 )
2651 return viewer_certificate
2652 except Exception as e:
2653 self.module.fail_json_aws(e, msg="Error validating viewer certificate")
2654
2655 def validate_custom_error_responses(self, config, custom_error_responses, purge_custom_error_responses):
2656 try:
2657 if custom_error_responses is None and not purge_custom_error_responses:
2658 return ansible_list_to_cloudfront_list(config)
2659 self.validate_is_list(custom_error_responses, "custom_error_responses")
2660 result = list()
2661 existing_responses = dict((response["error_code"], response) for response in custom_error_responses)
2662 for custom_error_response in custom_error_responses:
2663 self.validate_required_key("error_code", "custom_error_responses[].error_code", custom_error_response)
2664 custom_error_response = change_dict_key_name(
2665 custom_error_response, "error_caching_min_ttl", "error_caching_min_t_t_l"
2666 )
2667 if "response_code" in custom_error_response:
2668 custom_error_response["response_code"] = str(custom_error_response["response_code"])
2669 if custom_error_response["error_code"] in existing_responses:
2670 del existing_responses[custom_error_response["error_code"]]
2671 result.append(custom_error_response)
2672 if not purge_custom_error_responses:
2673 result.extend(existing_responses.values())
2674
2675 return ansible_list_to_cloudfront_list(result)
2676 except Exception as e:
2677 self.module.fail_json_aws(e, msg="Error validating custom error responses")
2678
2679 def validate_restrictions(self, config, restrictions, purge_restrictions=False):
2680 try:
2681 if restrictions is None:
2682 if purge_restrictions:
2683 return None
2684 else:
2685 return config
2686 self.validate_required_key("geo_restriction", "restrictions.geo_restriction", restrictions)
2687 geo_restriction = restrictions.get("geo_restriction")
2688 self.validate_required_key(
2689 "restriction_type", "restrictions.geo_restriction.restriction_type", geo_restriction
2690 )
2691 existing_restrictions = (
2692 config.get("geo_restriction", {}).get(geo_restriction["restriction_type"], {}).get("items", [])
2693 )
2694 geo_restriction_items = geo_restriction.get("items")
2695 if not purge_restrictions:
2696 geo_restriction_items.extend(
2697 [rest for rest in existing_restrictions if rest not in geo_restriction_items]
2698 )
2699 valid_restrictions = ansible_list_to_cloudfront_list(geo_restriction_items)
2700 valid_restrictions["restriction_type"] = geo_restriction.get("restriction_type")
2701 return {"geo_restriction": valid_restrictions}
2702 except Exception as e:
2703 self.module.fail_json_aws(e, msg="Error validating restrictions")
2704
2705 def validate_distribution_config_parameters(
2706 self, config, default_root_object, ipv6_enabled, http_version, web_acl_id
2707 ):
2708 try:
2709 config["default_root_object"] = default_root_object or config.get("default_root_object", "")
2710 config["is_i_p_v6_enabled"] = (
2711 ipv6_enabled
2712 if ipv6_enabled is not None
2713 else config.get("is_i_p_v6_enabled", self.__default_ipv6_enabled)
2714 )
2715 if http_version is not None or config.get("http_version"):
2716 self.validate_attribute_with_allowed_values(http_version, "http_version", self.__valid_http_versions)
2717 config["http_version"] = http_version or config.get("http_version")
2718 if web_acl_id or config.get("web_a_c_l_id"):
2719 config["web_a_c_l_id"] = web_acl_id or config.get("web_a_c_l_id")
2720 return config
2721 except Exception as e:
2722 self.module.fail_json_aws(e, msg="Error validating distribution config parameters")
2723
2724 def validate_common_distribution_parameters(
2725 self, config, enabled, aliases, logging, price_class, purge_aliases=False
2726 ):
2727 try:
2728 if config is None:
2729 config = {}
2730 if aliases is not None:
2731 if not purge_aliases:
2732 aliases.extend(
2733 [alias for alias in config.get("aliases", {}).get("items", []) if alias not in aliases]
2734 )
2735 config["aliases"] = ansible_list_to_cloudfront_list(aliases)
2736 if logging is not None:
2737 config["logging"] = self.validate_logging(logging)
2738 config["enabled"] = (
2739 enabled if enabled is not None else config.get("enabled", self.__default_distribution_enabled)
2740 )
2741 if price_class is not None:
2742 self.validate_attribute_with_allowed_values(price_class, "price_class", self.__valid_price_classes)
2743 config["price_class"] = price_class
2744 return config
2745 except Exception as e:
2746 self.module.fail_json_aws(e, msg="Error validating common distribution parameters")
2747
2748 def validate_comment(self, config, comment):
2749 config["comment"] = comment or config.get(
2750 "comment", "Distribution created by Ansible with datetime stamp " + self.__default_datetime_string
2751 )
2752 return config
2753
2754 def validate_caller_reference(self, caller_reference):
2755 return caller_reference or self.__default_datetime_string
2756
2757 def get_first_origin_id_for_default_cache_behavior(self, valid_origins):
2758 try:
2759 if valid_origins is not None:
2760 valid_origins_list = valid_origins.get("items")
2761 if (
2762 valid_origins_list is not None
2763 and isinstance(valid_origins_list, list)
2764 and len(valid_origins_list) > 0
2765 ):
2766 return str(valid_origins_list[0].get("id"))
2767 self.module.fail_json(
2768 msg="There are no valid origins from which to specify a target_origin_id for the default_cache_behavior configuration."
2769 )
2770 except Exception as e:
2771 self.module.fail_json_aws(e, msg="Error getting first origin_id for default cache behavior")
2772
2773 def validate_attribute_list_with_allowed_list(self, attribute_list, attribute_list_name, allowed_list):
2774 try:
2775 self.validate_is_list(attribute_list, attribute_list_name)
2776 if (
2777 isinstance(allowed_list, list)
2778 and set(attribute_list) not in allowed_list
2779 or isinstance(allowed_list, set)
2780 and not set(allowed_list).issuperset(attribute_list)
2781 ):
2782 attribute_list = " ".join(str(a) for a in allowed_list)
2783 self.module.fail_json(msg=f"The attribute list {attribute_list_name} must be one of [{attribute_list}]")
2784 except Exception as e:
2785 self.module.fail_json_aws(e, msg="Error validating attribute list with allowed value list")
2786
2787 def validate_attribute_with_allowed_values(self, attribute, attribute_name, allowed_list):
2788 if attribute is not None and attribute not in allowed_list:
2789 attribute_list = " ".join(str(a) for a in allowed_list)
2790 self.module.fail_json(msg=f"The attribute {attribute_name} must be one of [{attribute_list}]")
2791
2792 def validate_distribution_from_caller_reference(self, caller_reference):
2793 try:
2794 distributions = self.__cloudfront_facts_mgr.list_distributions(keyed=False)
2795 distribution_name = "Distribution"
2796 distribution_config_name = "DistributionConfig"
2797 distribution_ids = [dist.get("Id") for dist in distributions]
2798 for distribution_id in distribution_ids:
2799 distribution = self.__cloudfront_facts_mgr.get_distribution(id=distribution_id)
2800 if distribution is not None:
2801 distribution_config = distribution[distribution_name].get(distribution_config_name)
2802 if (
2803 distribution_config is not None
2804 and distribution_config.get("CallerReference") == caller_reference
2805 ):
2806 distribution[distribution_name][distribution_config_name] = distribution_config
2807 return distribution
2808
2809 except Exception as e:
2810 self.module.fail_json_aws(e, msg="Error validating distribution from caller reference")
2811
2812 def validate_distribution_from_aliases_caller_reference(self, distribution_id, aliases, caller_reference):
2813 try:
2814 if caller_reference is not None:
2815 return self.validate_distribution_from_caller_reference(caller_reference)
2816 else:
2817 if aliases and distribution_id is None:
2818 distribution_id = self.validate_distribution_id_from_alias(aliases)
2819 if distribution_id:
2820 return self.__cloudfront_facts_mgr.get_distribution(id=distribution_id)
2821 return None
2822 except Exception as e:
2823 self.module.fail_json_aws(
2824 e, msg="Error validating distribution_id from alias, aliases and caller reference"
2825 )
2826
2827 def validate_distribution_id_from_alias(self, aliases):
2828 distributions = self.__cloudfront_facts_mgr.list_distributions(keyed=False)
2829 if distributions:
2830 for distribution in distributions:
2831 distribution_aliases = distribution.get("Aliases", {}).get("Items", [])
2832 if set(aliases) & set(distribution_aliases):
2833 return distribution["Id"]
2834 return None
2835
2836 def wait_until_processed(self, client, wait_timeout, distribution_id, caller_reference):
2837 if distribution_id is None:
2838 distribution = self.validate_distribution_from_caller_reference(caller_reference=caller_reference)
2839 distribution_id = distribution["Distribution"]["Id"]
2840
2841 try:
2842 waiter = client.get_waiter("distribution_deployed")
2843 attempts = 1 + int(wait_timeout / 60)
2844 waiter.wait(Id=distribution_id, WaiterConfig={"MaxAttempts": attempts})
2845 except botocore.exceptions.WaiterError as e:
2846 self.module.fail_json_aws(
2847 e,
2848 msg=f"Timeout waiting for CloudFront action. Waited for {to_text(wait_timeout)} seconds before timeout.",
2849 )
2850
2851 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
2852 self.module.fail_json_aws(e, msg=f"Error getting distribution {distribution_id}")
2853
2854
2855 def duplicate_keys_for_deprecation(result):
2856 """
2857 Rename all dict 'items' keys to 'elements'
2858 """
2859 for t in (
2860 "active_trusted_signers.elements",
2861 "active_trusted_key_groups.elements",
2862 "distribution_config.aliases.elements",
2863 "distribution_config.cache_behaviors.elements",
2864 "distribution_config.custom_error_responses.elements",
2865 "distribution_config.default_cache_behavior.allowed_methods.cached_methods.elements",
2866 "distribution_config.default_cache_behavior.allowed_methods.elements",
2867 "distribution_config.default_cache_behavior.forwarded_values.cookies.whitelisted_names.elements",
2868 "distribution_config.default_cache_behavior.forwarded_values.headers.elements",
2869 "distribution_config.default_cache_behavior.forwarded_values.query_string_cache_keys.elements",
2870 "distribution_config.default_cache_behavior.lambda_function_associations.elements",
2871 "distribution_config.origins.elements",
2872 "distribution_config.restrictions.geo_restriction.elements",
2873 ):
2874 keys = t.split(".")
2875 copy_result = result
2876 while True:
2877 try:
2878 if len(keys) == 1:
2879 copy_result["elements"] = copy_result["items"]
2880 break
2881 copy_result = copy_result[keys.pop(0)]
2882 except KeyError:
2883 # The result does contain the key, skipping it
2884 break
2885
2886 # Origins
2887 for i in result.get("distribution_config", {}).get("origins", {}).get("elements", []):
2888 try:
2889 items = i["custom_origin_config"]["origin_ssl_protocols"]["items"]
2890 i["elements"] = items
2891 del i["custom_origin_config"]["origin_ssl_protocols"]["items"]
2892 except KeyError:
2893 pass
2894
2895 # Cache behaviors
2896 for i in result.get("distribution_config", {}).get("cache_behaviors", {}).get("elements", []):
2897 try:
2898 i["allowed_methods"]["elements"] = i["allowed_methods"]["items"]
2899 del i["allowed_methods"]["items"]
2900 except KeyError:
2901 pass
2902
2903 try:
2904 i["lambda_function_associations"]["elements"] = i["lambda_function_associations"]["items"]
2905 del i["lambda_function_associations"]["items"]
2906 except KeyError:
2907 pass
2908 try:
2909 i["forwarded_values"]["cookies"]["whitelisted_names"]["elements"] = i["forwarded_values"]["cookies"][
2910 "whitelisted_names"
2911 ]["items"]
2912 del i["forwarded_values"]["cookies"]["whitelisted_names"]["items"]
2913 except KeyError:
2914 pass
2915 try:
2916 i["forwarded_values"]["headers"]["elements"] = i["forwarded_values"]["headers"]["items"]
2917 del i["forwarded_values"]["headers"]["items"]
2918 except KeyError:
2919 pass
2920 try:
2921 i["forwarded_values"]["query_string_cache_keys"]["elements"] = i["forwarded_values"][
2922 "query_string_cache_keys"
2923 ]["items"]
2924 del i["forwarded_values"]["query_string_cache_keys"]["items"]
2925 except KeyError:
2926 pass
2927
2928
2929 def main():
2930 argument_spec = dict(
2931 state=dict(choices=["present", "absent"], default="present"),
2932 caller_reference=dict(),
2933 comment=dict(),
2934 distribution_id=dict(),
2935 e_tag=dict(),
2936 tags=dict(type="dict", aliases=["resource_tags"]),
2937 purge_tags=dict(type="bool", default=True),
2938 alias=dict(),
2939 aliases=dict(type="list", default=[], elements="str"),
2940 purge_aliases=dict(type="bool", default=False),
2941 default_root_object=dict(),
2942 origins=dict(type="list", elements="dict"),
2943 purge_origins=dict(type="bool", default=False),
2944 default_cache_behavior=dict(type="dict"),
2945 cache_behaviors=dict(type="list", elements="dict"),
2946 purge_cache_behaviors=dict(type="bool", default=False),
2947 custom_error_responses=dict(type="list", elements="dict"),
2948 purge_custom_error_responses=dict(type="bool", default=False),
2949 logging=dict(type="dict"),
2950 price_class=dict(),
2951 enabled=dict(type="bool"),
2952 viewer_certificate=dict(type="dict"),
2953 restrictions=dict(type="dict"),
2954 web_acl_id=dict(),
2955 http_version=dict(),
2956 ipv6_enabled=dict(type="bool"),
2957 default_origin_domain_name=dict(),
2958 default_origin_path=dict(),
2959 wait=dict(default=False, type="bool"),
2960 wait_timeout=dict(default=1800, type="int"),
2961 )
2962
2963 result = {}
2964 changed = True
2965
2966 module = AnsibleAWSModule(
2967 argument_spec=argument_spec,
2968 supports_check_mode=False,
2969 mutually_exclusive=[
2970 ["distribution_id", "alias"],
2971 ["default_origin_domain_name", "distribution_id"],
2972 ["default_origin_domain_name", "alias"],
2973 ],
2974 )
2975
2976 client = module.client("cloudfront", retry_decorator=AWSRetry.jittered_backoff())
2977
2978 validation_mgr = CloudFrontValidationManager(module)
2979
2980 state = module.params.get("state")
2981 caller_reference = module.params.get("caller_reference")
2982 comment = module.params.get("comment")
2983 e_tag = module.params.get("e_tag")
2984 tags = module.params.get("tags")
2985 purge_tags = module.params.get("purge_tags")
2986 distribution_id = module.params.get("distribution_id")
2987 alias = module.params.get("alias")
2988 aliases = module.params.get("aliases")
2989 purge_aliases = module.params.get("purge_aliases")
2990 default_root_object = module.params.get("default_root_object")
2991 origins = module.params.get("origins")
2992 purge_origins = module.params.get("purge_origins")
2993 default_cache_behavior = module.params.get("default_cache_behavior")
2994 cache_behaviors = module.params.get("cache_behaviors")
2995 purge_cache_behaviors = module.params.get("purge_cache_behaviors")
2996 custom_error_responses = module.params.get("custom_error_responses")
2997 purge_custom_error_responses = module.params.get("purge_custom_error_responses")
2998 logging = module.params.get("logging")
2999 price_class = module.params.get("price_class")
3000 enabled = module.params.get("enabled")
3001 viewer_certificate = module.params.get("viewer_certificate")
3002 restrictions = module.params.get("restrictions")
3003 purge_restrictions = module.params.get("purge_restrictions")
3004 web_acl_id = module.params.get("web_acl_id")
3005 http_version = module.params.get("http_version")
3006 ipv6_enabled = module.params.get("ipv6_enabled")
3007 default_origin_domain_name = module.params.get("default_origin_domain_name")
3008 default_origin_path = module.params.get("default_origin_path")
3009 wait = module.params.get("wait")
3010 wait_timeout = module.params.get("wait_timeout")
3011
3012 if alias and alias not in aliases:
3013 aliases.append(alias)
3014
3015 distribution = validation_mgr.validate_distribution_from_aliases_caller_reference(
3016 distribution_id, aliases, caller_reference
3017 )
3018
3019 update = state == "present" and distribution
3020 create = state == "present" and not distribution
3021 delete = state == "absent" and distribution
3022
3023 if not (update or create or delete):
3024 module.exit_json(changed=False)
3025
3026 config = {}
3027 if update or delete:
3028 config = distribution["Distribution"]["DistributionConfig"]
3029 e_tag = distribution["ETag"]
3030 distribution_id = distribution["Distribution"]["Id"]
3031
3032 if update:
3033 config = camel_dict_to_snake_dict(config, reversible=True)
3034
3035 if create or update:
3036 config = validation_mgr.validate_common_distribution_parameters(
3037 config, enabled, aliases, logging, price_class, purge_aliases
3038 )
3039 config = validation_mgr.validate_distribution_config_parameters(
3040 config, default_root_object, ipv6_enabled, http_version, web_acl_id
3041 )
3042 config["origins"] = validation_mgr.validate_origins(
3043 client,
3044 config.get("origins", {}).get("items", []),
3045 origins,
3046 default_origin_domain_name,
3047 default_origin_path,
3048 create,
3049 purge_origins,
3050 )
3051 config["cache_behaviors"] = validation_mgr.validate_cache_behaviors(
3052 config.get("cache_behaviors", {}).get("items", []),
3053 cache_behaviors,
3054 config["origins"],
3055 purge_cache_behaviors,
3056 )
3057 config["default_cache_behavior"] = validation_mgr.validate_cache_behavior(
3058 config.get("default_cache_behavior", {}), default_cache_behavior, config["origins"], True
3059 )
3060 config["custom_error_responses"] = validation_mgr.validate_custom_error_responses(
3061 config.get("custom_error_responses", {}).get("items", []),
3062 custom_error_responses,
3063 purge_custom_error_responses,
3064 )
3065 valid_restrictions = validation_mgr.validate_restrictions(
3066 config.get("restrictions", {}), restrictions, purge_restrictions
3067 )
3068 if valid_restrictions:
3069 config["restrictions"] = valid_restrictions
3070 valid_viewer_certificate = validation_mgr.validate_viewer_certificate(viewer_certificate)
3071 config = merge_validation_into_config(config, valid_viewer_certificate, "viewer_certificate")
3072 config = validation_mgr.validate_comment(config, comment)
3073 config = snake_dict_to_camel_dict(config, capitalize_first=True)
3074
3075 if create:
3076 config["CallerReference"] = validation_mgr.validate_caller_reference(caller_reference)
3077 result = create_distribution(client, module, config, ansible_dict_to_boto3_tag_list(tags or {}))
3078 result = camel_dict_to_snake_dict(result)
3079 duplicate_keys_for_deprecation(result)
3080 result["tags"] = list_tags_for_resource(client, module, result["arn"])
3081
3082 if delete:
3083 if config["Enabled"]:
3084 config["Enabled"] = False
3085 result = update_distribution(client, module, config, distribution_id, e_tag)
3086 validation_mgr.wait_until_processed(client, wait_timeout, distribution_id, config.get("CallerReference"))
3087 distribution = validation_mgr.validate_distribution_from_aliases_caller_reference(
3088 distribution_id, aliases, caller_reference
3089 )
3090 # e_tag = distribution['ETag']
3091 result = delete_distribution(client, module, distribution)
3092 result.pop("ResponseMetadata", None)
3093
3094 if update:
3095 changed = config != distribution["Distribution"]["DistributionConfig"]
3096 if changed:
3097 result = update_distribution(client, module, config, distribution_id, e_tag)
3098 else:
3099 result = distribution["Distribution"]
3100 existing_tags = list_tags_for_resource(client, module, result["ARN"])
3101 distribution["Distribution"]["DistributionConfig"]["tags"] = existing_tags
3102 changed |= update_tags(client, module, existing_tags, tags, purge_tags, result["ARN"])
3103 result = camel_dict_to_snake_dict(result)
3104 duplicate_keys_for_deprecation(result)
3105 result["distribution_config"]["tags"] = config["tags"] = list_tags_for_resource(client, module, result["arn"])
3106 result["diff"] = dict()
3107 diff = recursive_diff(distribution["Distribution"]["DistributionConfig"], config)
3108 if diff:
3109 result["diff"]["before"] = diff[0]
3110 result["diff"]["after"] = diff[1]
3111
3112 if wait and (create or update):
3113 validation_mgr.wait_until_processed(client, wait_timeout, distribution_id, config.get("CallerReference"))
3114
3115 if "distribution_config" in result:
3116 result.update(result["distribution_config"])
3117 del result["distribution_config"]
3118
3119 module.exit_json(changed=changed, **result)
3120
3121
3122 if __name__ == "__main__":
3123 main()