Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/s3_bucket.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the Ansible project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 ---
11 module: s3_bucket
12 version_added: 1.0.0
13 short_description: Manage S3 buckets in AWS, DigitalOcean, Ceph, Walrus, FakeS3 and StorageGRID
14 description:
15 - Manage S3 buckets.
16 - Compatible with AWS, DigitalOcean, Ceph, Walrus, FakeS3 and StorageGRID.
17 - When using non-AWS services, O(endpoint_url) should be specified.
18 author:
19 - Rob White (@wimnat)
20 - Aubin Bikouo (@abikouo)
21 options:
22 force:
23 description:
24 - When trying to delete a bucket, delete all keys (including versions and delete markers)
25 in the bucket first (an S3 bucket must be empty for a successful deletion).
26 type: bool
27 default: false
28 name:
29 description:
30 - Name of the S3 bucket.
31 required: true
32 type: str
33 policy:
34 description:
35 - The JSON policy as a string. Set to the string V("null") to force the absence of a policy.
36 type: json
37 ceph:
38 description:
39 - Enable API compatibility with Ceph RGW.
40 - It takes into account the S3 API subset working with Ceph in order to provide the same module
41 behaviour where possible.
42 - Requires O(endpoint_url) if O(ceph=true).
43 aliases: ['rgw']
44 type: bool
45 default: false
46 account_regional:
47 description:
48 - Whether to create the bucket in the account-regional namespace instead of the global namespace.
49 - When V(true), the bucket name must follow the format C(prefix-accountId-region-an).
50 - Can only be set during bucket creation. Cannot be changed for existing buckets.
51 - Not supported for directory buckets.
52 - Requires botocore >= 1.42.67
53 type: bool
54 version_added: 11.3.0
55 requester_pays:
56 description:
57 - With Requester Pays buckets, the requester instead of the bucket owner pays the cost
58 of the request and the data download from the bucket.
59 type: bool
60 state:
61 description:
62 - Create or remove the S3 bucket.
63 required: false
64 default: present
65 choices: [ 'present', 'absent' ]
66 type: str
67 versioning:
68 description:
69 - Whether versioning is enabled or disabled (note that once versioning is enabled, it can only be suspended).
70 type: bool
71 encryption:
72 description:
73 - Describes the default server-side encryption to apply to new objects in the bucket.
74 In order to remove the server-side encryption, the encryption needs to be set to 'none' explicitly.
75 - "Note: Since January 2023 Amazon S3 doesn't support disabling encryption on S3 buckets."
76 choices: [ 'none', 'AES256', 'aws:kms' ]
77 type: str
78 encryption_key_id:
79 description:
80 - KMS master key ID to use for the default encryption.
81 - If not specified then it will default to the AWS provided KMS key.
82 - This parameter is only supported if O(encryption) is V(aws:kms).
83 type: str
84 bucket_key_enabled:
85 description:
86 - Enable S3 Bucket Keys for SSE-KMS on new objects.
87 - See the AWS documentation for more information
88 U(https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-key.html).
89 - Bucket Key encryption is only supported if O(encryption=aws:kms).
90 required: false
91 type: bool
92 version_added: 4.1.0
93 public_access:
94 description:
95 - Configure public access block for S3 bucket.
96 - This option cannot be used together with O(delete_public_access).
97 - |
98 Note: At the end of April 2023 Amazon updated the default settings to block public access by
99 default. While the defaults for this module remain unchanged, it is necessary to explicitly
100 pass the O(public_access) parameter to enable public access ACLs.
101 suboptions:
102 block_public_acls:
103 description: Sets BlockPublicAcls value.
104 type: bool
105 default: false
106 block_public_policy:
107 description: Sets BlockPublicPolicy value.
108 type: bool
109 default: false
110 ignore_public_acls:
111 description: Sets IgnorePublicAcls value.
112 type: bool
113 default: false
114 restrict_public_buckets:
115 description: Sets RestrictPublicAcls value.
116 type: bool
117 default: false
118 type: dict
119 version_added: 1.3.0
120 delete_public_access:
121 description:
122 - Delete public access block configuration from bucket.
123 - This option cannot be used together with a O(public_access) definition.
124 default: false
125 type: bool
126 version_added: 1.3.0
127 object_ownership:
128 description:
129 - Allow bucket's ownership controls.
130 - V(BucketOwnerEnforced) - ACLs are disabled and no longer affect access permissions to your
131 bucket. Requests to set or update ACLs fail. However, requests to read ACLs are supported.
132 Bucket owner has full ownership and control. Object writer no longer has full ownership and
133 control.
134 - V(BucketOwnerPreferred) - Objects uploaded to the bucket change ownership to the bucket owner
135 if the objects are uploaded with the bucket-owner-full-control canned ACL.
136 - V(ObjectWriter) - The uploading account will own the object
137 if the object is uploaded with the bucket-owner-full-control canned ACL.
138 - This option cannot be used together with a O(delete_object_ownership) definition.
139 - V(BucketOwnerEnforced) has been added in version 3.2.0.
140 - "Note: At the end of April 2023 Amazon updated the default setting to V(BucketOwnerEnforced)."
141 choices: [ 'BucketOwnerEnforced', 'BucketOwnerPreferred', 'ObjectWriter' ]
142 type: str
143 version_added: 2.0.0
144 object_lock_enabled:
145 description:
146 - Whether S3 Object Lock to be enabled.
147 - Defaults to V(false) when creating a new bucket.
148 type: bool
149 version_added: 5.3.0
150 delete_object_ownership:
151 description:
152 - Delete bucket's ownership controls.
153 - This option cannot be used together with a O(object_ownership) definition.
154 default: false
155 type: bool
156 version_added: 2.0.0
157 acl:
158 description:
159 - The canned ACL to apply to the bucket.
160 - If your bucket uses the bucket owner enforced setting for S3 Object Ownership,
161 ACLs are disabled and no longer affect permissions.
162 - If O(public_access.ignore_public_acls=true) setting O(acl) to a value other than V(private)
163 may return success but not have an affect.
164 choices: [ 'private', 'public-read', 'public-read-write', 'authenticated-read' ]
165 type: str
166 version_added: 3.1.0
167 validate_bucket_name:
168 description:
169 - Whether the bucket name should be validated to conform to AWS S3 naming rules.
170 - On by default, this may be disabled for S3 backends that do not enforce these rules.
171 - See U(https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html).
172 type: bool
173 version_added: 3.1.0
174 default: true
175 dualstack:
176 description:
177 - Enables Amazon S3 Dual-Stack Endpoints, allowing S3 communications using both IPv4 and IPv6.
178 - Mutually exclusive with O(endpoint_url).
179 type: bool
180 default: false
181 version_added: 6.0.0
182 accelerate_enabled:
183 description:
184 - Enables Amazon S3 Transfer Acceleration, sent data will be routed to Amazon S3 over an optimized network path.
185 - Transfer Acceleration is not available in AWS GovCloud (US).
186 - See U(https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-s3.html#govcloud-S3-diffs).
187 type: bool
188 version_added: 8.1.0
189 object_lock_default_retention:
190 description:
191 - Default Object Lock configuration that will be applied by default to
192 every new object placed in the specified bucket.
193 - O(object_lock_enabled) must be included and set to V(True).
194 - Object lock retention policy can't be removed.
195 suboptions:
196 mode:
197 description: Type of retention modes.
198 choices: [ "GOVERNANCE", "COMPLIANCE"]
199 required: true
200 type: str
201 days:
202 description:
203 - The number of days that you want to specify for the default retention period.
204 - Mutually exclusive with O(object_lock_default_retention.years).
205 type: int
206 years:
207 description:
208 - The number of years that you want to specify for the default retention period.
209 - Mutually exclusive with O(object_lock_default_retention.days).
210 type: int
211 type: dict
212 version_added: 8.1.0
213 inventory:
214 description:
215 - Enable S3 Inventory, saving list of the objects and their corresponding
216 metadata on a daily or weekly basis for an S3 bucket.
217 type: list
218 elements: dict
219 suboptions:
220 destination:
221 description: Contains information about where to publish the inventory results.
222 type: dict
223 required: True
224 suboptions:
225 account_id:
226 description: The account ID that owns the destination S3 bucket. If no account ID is provided, the owner is not validated before exporting data.
227 type: str
228 bucket:
229 description: The Amazon Resource Name (ARN) of the bucket where inventory results will be published.
230 type: str
231 required: True
232 format:
233 description: Specifies the output format of the inventory results.
234 type: str
235 choices: [ 'CSV', 'ORC', 'Parquet' ]
236 required: True
237 prefix:
238 description: The prefix that is prepended to all inventory results.
239 type: str
240 filter:
241 description: The prefix that an object must have to be included in the inventory results.
242 type: str
243 id:
244 description: The ID used to identify the inventory configuration.
245 type: str
246 required: True
247 schedule:
248 description: Specifies the schedule for generating inventory results.
249 type: str
250 choices: [ 'Daily', 'Weekly' ]
251 required: True
252 included_object_versions:
253 description: |
254 Object versions to include in the inventory list. If set to All, the list includes all the object versions,
255 which adds the version-related fields VersionId, IsLatest, and DeleteMarker to the list. If set to Current,
256 the list does not contain these version-related fields.
257 type: str
258 required: True
259 choices: [ 'All', 'Current' ]
260 optional_fields:
261 description: Contains the optional fields that are included in the inventory results.
262 type: list
263 elements: str
264 choices: [ "Size", "LastModifiedDate", "StorageClass", "ETag",
265 "IsMultipartUploaded", "ReplicationStatus", "EncryptionStatus",
266 "ObjectLockRetainUntilDate", "ObjectLockMode",
267 "ObjectLockLegalHoldStatus", "IntelligentTieringAccessTier",
268 "BucketKeyStatus", "ChecksumAlgorithm", "ObjectAccessControlList",
269 "ObjectOwner" ]
270 logging:
271 description:
272 - Configure S3 bucket logging to track requests for access to the bucket.
273 - To disable logging, explicitly set O(logging.target_bucket) to an empty string.
274 - "Note: The target bucket must have appropriate permissions configured. This module does NOT automatically
275 configure ACLs on the target bucket. See AWS documentation for required permissions."
276 type: dict
277 suboptions:
278 target_bucket:
279 description: The name of the bucket where Amazon S3 should store server access log files.
280 type: str
281 required: true
282 target_prefix:
283 description: A prefix for all log object keys.
284 type: str
285 default: ""
286 version_added: 11.3.0
287 extends_documentation_fragment:
288 - amazon.aws.common.modules
289 - amazon.aws.region.modules
290 - amazon.aws.tags
291 - amazon.aws.boto3
292
293 notes:
294 - If C(requestPayment), C(policy), C(tagging) or C(versioning)
295 operations/API aren't implemented by the endpoint, module doesn't fail
296 if each parameter satisfies the following condition.
297 O(requester_pays) is V(false), O(policy), O(tags), and O(versioning) are V(None).
298 - For Walrus O(endpoint_url) should be set to the FQDN of the endpoint with neither scheme nor path.
299 """
300
301 EXAMPLES = r"""
302 # Note: These examples do not set authentication details, see the AWS Guide for details.
303
304 # Create a simple S3 bucket
305 - amazon.aws.s3_bucket:
306 name: mys3bucket
307 state: present
308
309 # Create a simple S3 bucket on Ceph Rados Gateway
310 - amazon.aws.s3_bucket:
311 name: mys3bucket
312 endpoint_url: http://your-ceph-rados-gateway-server.xxx
313 ceph: true
314
315 # Create a bucket with account-regional namespace
316 - amazon.aws.s3_bucket:
317 name: my-bucket-111122223333-us-east-1-an
318 state: present
319 account_regional: true
320 # Remove an S3 bucket and any keys it contains
321 - amazon.aws.s3_bucket:
322 name: mys3bucket
323 state: absent
324 force: true
325
326 # Create a bucket, add a policy from a file, enable requester pays, enable versioning and tag
327 - amazon.aws.s3_bucket:
328 name: mys3bucket
329 policy: "{{ lookup('file','policy.json') }}"
330 requester_pays: true
331 versioning: true
332 tags:
333 example: tag1
334 another: tag2
335
336 # Create a simple DigitalOcean Spaces bucket using their provided regional endpoint
337 - amazon.aws.s3_bucket:
338 name: mydobucket
339 endpoint_url: 'https://nyc3.digitaloceanspaces.com'
340
341 # Create a bucket with AES256 encryption
342 - amazon.aws.s3_bucket:
343 name: mys3bucket
344 state: present
345 encryption: "AES256"
346
347 # Create a bucket with aws:kms encryption, KMS key
348 - amazon.aws.s3_bucket:
349 name: mys3bucket
350 state: present
351 encryption: "aws:kms"
352 encryption_key_id: "arn:aws:kms:us-east-1:1234/5678example"
353
354 # Create a bucket with aws:kms encryption, Bucket key
355 - amazon.aws.s3_bucket:
356 name: mys3bucket
357 bucket_key_enabled: true
358 encryption: "aws:kms"
359
360 # Create a bucket with aws:kms encryption, default key
361 - amazon.aws.s3_bucket:
362 name: mys3bucket
363 state: present
364 encryption: "aws:kms"
365
366 # Create a bucket with public policy block configuration
367 - amazon.aws.s3_bucket:
368 name: mys3bucket
369 state: present
370 public_access:
371 block_public_acls: true
372 ignore_public_acls: true
373 ## keys == 'false' can be omitted, undefined keys defaults to 'false'
374 # block_public_policy: false
375 # restrict_public_buckets: false
376
377 # Delete public policy block from bucket
378 - amazon.aws.s3_bucket:
379 name: mys3bucket
380 state: present
381 delete_public_access: true
382
383 # Create a bucket with object ownership controls set to ObjectWriter
384 - amazon.aws.s3_bucket:
385 name: mys3bucket
386 state: present
387 object_ownership: ObjectWriter
388
389 # Delete onwership controls from bucket
390 - amazon.aws.s3_bucket:
391 name: mys3bucket
392 state: present
393 delete_object_ownership: true
394
395 # Delete a bucket policy from bucket
396 - amazon.aws.s3_bucket:
397 name: mys3bucket
398 state: present
399 policy: "null"
400
401 # This example grants public-read to everyone on bucket using ACL
402 - amazon.aws.s3_bucket:
403 name: mys3bucket
404 state: present
405 acl: public-read
406
407 # Enable transfer acceleration
408 - amazon.aws.s3_bucket:
409 name: mys3bucket
410 state: present
411 accelerate_enabled: true
412
413 # Default Object Lock retention
414 - amazon.aws.s3_bucket:
415 name: mys3bucket
416 state: present
417 object_lock_enabled: true
418 object_lock_default_retention:
419 mode: governance
420 days: 1
421 # Bucket with inventory configuration:
422 - amazon.aws.s3_bucket:
423 name: mys3bucket
424 state: present
425 inventory:
426 - id: mys3bucket-inventory-id
427 destination:
428 bucket: "arn:aws:s3:::mys3inventorybucket"
429 optional_fields:
430 - "Size"
431 included_object_versions: "All"
432 schedule: "Weekly"
433
434 # Enable bucket logging
435 - amazon.aws.s3_bucket:
436 name: mys3bucket
437 state: present
438 logging:
439 target_bucket: my-logging-bucket
440 target_prefix: logs/mys3bucket/
441
442 # Disable bucket logging
443 - amazon.aws.s3_bucket:
444 name: mys3bucket
445 state: present
446 logging:
447 target_bucket: ""
448 """
449
450 RETURN = r"""
451 encryption:
452 description: Server-side encryption of the objects in the S3 bucket.
453 type: dict
454 returned: when O(state=present)
455 sample: {
456 "SSEAlgorithm": "AES256"
457 }
458 name:
459 description: Bucket name.
460 returned: when O(state=present)
461 type: str
462 sample: "a-testing-bucket-name"
463 logging:
464 description: S3 bucket's logging configuration.
465 type: dict
466 returned: when O(state=present)
467 sample: {
468 "target_bucket": "my-logging-bucket",
469 "target_prefix": "logs/"
470 }
471 object_ownership:
472 description: S3 bucket's ownership controls.
473 type: str
474 returned: when O(state=present)
475 sample: "BucketOwnerPreferred"
476 object_lock_default_retention:
477 description: S3 bucket's object lock retention policy.
478 type: dict
479 returned: when O(state=present)
480 sample: {
481 "Days": 1,
482 "Mode": "GOVERNANCE",
483 "Years": 0,
484 }
485 policy:
486 description: S3 bucket's policy.
487 type: dict
488 returned: when O(state=present)
489 sample: {
490 "Statement": [
491 {
492 "Action": "s3:GetObject",
493 "Effect": "Allow",
494 "Principal": "*",
495 "Resource": "arn:aws:s3:::2d3ce10a8210d36d6b4d23b822892074complex/*",
496 "Sid": "AddPerm"
497 }
498 ],
499 "Version": "2012-10-17"
500 }
501 requester_pays:
502 description: Indicates that the requester was successfully charged for the request.
503 type: bool
504 returned: when O(state=present)
505 sample: true
506 tags:
507 description: S3 bucket's tags.
508 type: dict
509 returned: when O(state=present)
510 sample: {
511 "Tag1": "tag1",
512 "Tag2": "tag2"
513 }
514 versioning:
515 description: S3 bucket's versioning configuration.
516 type: dict
517 returned: when O(state=present)
518 sample: {
519 "MfaDelete": "Disabled",
520 "Versioning": "Enabled"
521 }
522 contains:
523 MfaDelete:
524 description: Specifies whether MFA delete is enabled in the bucket versioning configuration.
525 returned: when O(state=presnet) and MfaDelete configured on bucket.
526 type: str
527 Versioning:
528 description: The versioning state of the bucket.
529 type: str
530 returned: always
531 acl:
532 description: S3 bucket's canned ACL.
533 type: dict
534 returned: when O(state=present).
535 sample: "public-read"
536 object_lock_enabled:
537 description: Whether S3 Object Lock is enabled.
538 type: bool
539 returned: when O(state=present)
540 sample: false
541 public_access_block:
542 description: Bucket public access block configuration.
543 returned: when O(state=present)
544 type: dict
545 sample: {
546 "PublicAccessBlockConfiguration": {
547 "BlockPublicAcls": true,
548 "BlockPublicPolicy": true,
549 "IgnorePublicAcls": true,
550 "RestrictPublicBuckets": true
551 }
552 }
553 contains:
554 PublicAccessBlockConfiguration:
555 description: The PublicAccessBlock configuration currently in effect for this Amazon S3 bucket.
556 type: dict
557 contains:
558 BlockPublicAcls:
559 description: Specifies whether Amazon S3 should block public access control lists (ACLs) for this bucket and objects in this bucket.
560 type: bool
561 BlockPublicPolicy:
562 description: Specifies whether Amazon S3 should block public bucket policies for this bucket.
563 type: bool
564 IgnorePublicAcls:
565 description: Specifies whether Amazon S3 should ignore public ACLs for this bucket and objects in this bucket.
566 type: bool
567 RestrictPublicBuckets:
568 description: Specifies whether Amazon S3 should restrict public bucket policies for this bucket.
569 type: bool
570 accelerate_enabled:
571 description: S3 bucket acceleration status.
572 type: bool
573 returned: O(state=present)
574 sample: true
575 bucket_inventory:
576 description: S3 bucket inventory configuration.
577 type: list
578 returned: when O(state=present)
579 sample: [
580 {
581 "IsEnabled": true,
582 "Id": "9c2a337ba5fd64de777f499441f83093-inventory-target",
583 "Destination": {
584 "S3BucketDestination": {
585 "Bucket": "arn:aws:s3:::9c2a337ba5fd64de777f499441f83093-inventory-target",
586 "Format": "CSV"
587 }
588 },
589 "IncludedObjectVersions": "All",
590 "Schedule": {
591 "Frequency": "Daily"
592 },
593 "OptionalFields": []
594 }
595 ]
596 """
597
598 import json
599 import time
600 import typing
601 from typing import Iterator
602 from typing import List
603 from typing import NoReturn
604 from typing import Optional
605 from typing import Tuple
606 from typing import cast
607
608 if typing.TYPE_CHECKING:
609 from ansible_collections.amazon.aws.plugins.module_utils.botocore import ClientType
610
611 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
612
613 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
614 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
615 from ansible_collections.amazon.aws.plugins.module_utils.policy import compare_policies
616 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
617 from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3Error
618 from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3PermissionsError
619 from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3SupportError
620 from ansible_collections.amazon.aws.plugins.module_utils.s3 import S3ErrorHandler
621 from ansible_collections.amazon.aws.plugins.module_utils.s3 import delete_s3_bucket
622 from ansible_collections.amazon.aws.plugins.module_utils.s3 import delete_s3_bucket_accelerate_configuration
623 from ansible_collections.amazon.aws.plugins.module_utils.s3 import delete_s3_bucket_encryption
624 from ansible_collections.amazon.aws.plugins.module_utils.s3 import delete_s3_bucket_inventory
625 from ansible_collections.amazon.aws.plugins.module_utils.s3 import delete_s3_bucket_ownership
626 from ansible_collections.amazon.aws.plugins.module_utils.s3 import delete_s3_bucket_policy
627 from ansible_collections.amazon.aws.plugins.module_utils.s3 import delete_s3_bucket_public_access
628 from ansible_collections.amazon.aws.plugins.module_utils.s3 import delete_s3_bucket_tagging
629 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_accelerate_configuration
630 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_acl
631 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_encryption
632 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_location
633 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_logging
634 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_ownership_controls
635 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_policy
636 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_public_access_block
637 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_request_payment
638 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_tagging
639 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_versioning
640 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_object_lock_configuration
641 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_waiter
642 from ansible_collections.amazon.aws.plugins.module_utils.s3 import list_bucket_inventory_configurations
643 from ansible_collections.amazon.aws.plugins.module_utils.s3 import merge_tags
644 from ansible_collections.amazon.aws.plugins.module_utils.s3 import normalize_s3_bucket_acls
645 from ansible_collections.amazon.aws.plugins.module_utils.s3 import normalize_s3_bucket_logging
646 from ansible_collections.amazon.aws.plugins.module_utils.s3 import normalize_s3_bucket_public_access
647 from ansible_collections.amazon.aws.plugins.module_utils.s3 import normalize_s3_bucket_versioning
648 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_accelerate_configuration
649 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_acl
650 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_encryption
651 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_inventory
652 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_logging
653 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_ownership
654 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_policy
655 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_public_access
656 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_request_payment
657 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_tagging
658 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_bucket_versioning
659 from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_object_lock_configuration
660 from ansible_collections.amazon.aws.plugins.module_utils.s3 import s3_acl_to_name
661 from ansible_collections.amazon.aws.plugins.module_utils.s3 import s3_bucket_exists
662 from ansible_collections.amazon.aws.plugins.module_utils.s3 import s3_extra_params
663 from ansible_collections.amazon.aws.plugins.module_utils.s3 import validate_account_regional_bucket_name
664 from ansible_collections.amazon.aws.plugins.module_utils.s3 import validate_bucket_name
665 from ansible_collections.amazon.aws.plugins.module_utils.transformation import scrub_none_parameters
666
667
668 def handle_bucket_versioning(s3_client: ClientType, module: AnsibleAWSModule, name: str) -> Tuple[bool, Optional[dict]]:
669 """
670 Manage versioning for an S3 bucket.
671 Parameters:
672 s3_client (boto3.client): The Boto3 S3 client object.
673 module (AnsibleAWSModule): The Ansible module object.
674 name (str): The name of the bucket to handle versioning for.
675 Returns:
676 A tuple containing a boolean indicating whether versioning
677 was changed and a dictionary containing the updated versioning status.
678 """
679
680 versioning = module.params.get("versioning")
681 required_versioning = ""
682
683 try:
684 versioning_status = get_s3_bucket_versioning(s3_client, name)
685 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
686 if versioning is not None:
687 raise
688 module.warn(e.message)
689 return False, None
690
691 if versioning is None:
692 return False, normalize_s3_bucket_versioning(versioning_status)
693
694 if versioning and versioning_status.get("Status") != "Enabled":
695 required_versioning = "Enabled"
696 if not versioning and versioning_status.get("Status") == "Enabled":
697 required_versioning = "Suspended"
698
699 if not required_versioning:
700 return False, normalize_s3_bucket_versioning(versioning_status)
701
702 put_s3_bucket_versioning(s3_client, name, required_versioning)
703
704 wait_versioning_is_applied(s3_client, name, required_versioning)
705 versioning_status = get_s3_bucket_versioning(s3_client, name)
706 return True, normalize_s3_bucket_versioning(versioning_status)
707
708
709 def handle_bucket_requester_pays(
710 s3_client: ClientType, module: AnsibleAWSModule, name: str
711 ) -> Tuple[bool, Optional[dict]]:
712 """
713 Manage requester pays setting for an S3 bucket.
714 Parameters:
715 s3_client (boto3.client): The Boto3 S3 client object.
716 module (AnsibleAWSModule): The Ansible module object.
717 name (str): The name of the bucket to handle requester pays setting for.
718 Returns:
719 A tuple containing a boolean indicating whether requester pays setting
720 was changed and a boolean containing the updated requester pays status.
721 """
722
723 requester_pays = module.params.get("requester_pays")
724
725 try:
726 requester_pays_status = get_s3_bucket_request_payment(s3_client, name)
727 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
728 if requester_pays is not None:
729 raise
730 module.warn(e.message)
731 return False, None
732
733 requester_pays_status = bool(requester_pays_status == "Requester")
734
735 if requester_pays is None:
736 return False, requester_pays_status
737 if requester_pays == requester_pays_status:
738 return False, requester_pays_status
739
740 payer = "Requester" if requester_pays else "BucketOwner"
741 put_s3_bucket_request_payment(s3_client, name, payer)
742 requester_pays_status = wait_payer_is_applied(s3_client, name, payer, should_fail=False)
743 if requester_pays_status is None:
744 put_s3_bucket_request_payment(s3_client, name, payer)
745 requester_pays_status = wait_payer_is_applied(s3_client, name, payer, should_fail=True)
746
747 return True, requester_pays
748
749
750 def handle_bucket_public_access_config(
751 s3_client: ClientType, module: AnsibleAWSModule, name: str
752 ) -> Tuple[bool, Optional[dict]]:
753 """
754 Manage public access configuration for an S3 bucket.
755 Parameters:
756 s3_client (boto3.client): The Boto3 S3 client object.
757 module (AnsibleAWSModule): The Ansible module object.
758 name (str): The name of the bucket to handle public access configuration for.
759 Returns:
760 A tuple containing a boolean indicating whether public access configuration
761 was changed and a dictionary containing the updated public access configuration.
762 """
763
764 public_access = module.params.get("public_access")
765 delete_public_access = module.params.get("delete_public_access")
766
767 try:
768 current_public_access = get_s3_bucket_public_access_block(s3_client, name)
769 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
770 if public_access is not None:
771 raise
772 module.warn(e.message)
773 return False, None
774
775 # -- Delete public access block if necessary
776 if delete_public_access:
777 if not current_public_access:
778 return False, None
779 delete_s3_bucket_public_access(s3_client, name)
780 return True, None
781
782 # -- Create / Update public access block
783 # Short circuit comparisons if no change was requested
784 if public_access is None:
785 return False, normalize_s3_bucket_public_access(current_public_access)
786
787 camel_public_block = snake_dict_to_camel_dict(public_access, capitalize_first=True)
788 # No change needed
789 if current_public_access == camel_public_block:
790 return False, normalize_s3_bucket_public_access(current_public_access)
791
792 # Make a change
793 put_s3_bucket_public_access(s3_client, name, public_access_config=camel_public_block)
794 return True, normalize_s3_bucket_public_access(camel_public_block)
795
796
797 def handle_bucket_policy(s3_client: ClientType, module: AnsibleAWSModule, name: str) -> Tuple[bool, Optional[dict]]:
798 """
799 Manage bucket policy for an S3 bucket.
800 Parameters:
801 s3_client (boto3.client): The Boto3 S3 client object.
802 module (AnsibleAWSModule): The Ansible module object.
803 name (str): The name of the bucket to handle the policy for.
804 Returns:
805 A tuple containing a boolean indicating whether the bucket policy
806 was changed and a dictionary containing the updated bucket policy.
807 """
808
809 policy = module.params.get("policy")
810 try:
811 current_policy = get_s3_bucket_policy(s3_client, name)
812 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
813 if policy is not None:
814 raise
815 module.warn(e.message)
816 return False, None
817
818 if policy is None:
819 return False, current_policy
820
821 if isinstance(policy, str):
822 try:
823 policy = json.loads(policy)
824 except ValueError as e:
825 raise AnsibleS3Error(exception=e, message="Unable to parse bucket policy") from e
826
827 if not policy:
828 if not current_policy:
829 return False, current_policy
830
831 delete_s3_bucket_policy(s3_client, name)
832 return True, wait_policy_is_applied(s3_client, name, policy)
833
834 if not compare_policies(current_policy, policy):
835 return False, current_policy
836
837 put_s3_bucket_policy(s3_client, name, policy)
838 current_policy = wait_policy_is_applied(s3_client, name, policy, should_fail=False)
839 if current_policy is None:
840 # As for request payement, it happens quite a lot of times that the put request was not taken into
841 # account, so we retry one more time
842 put_s3_bucket_policy(s3_client, name, policy)
843 current_policy = wait_policy_is_applied(s3_client, name, policy, should_fail=True)
844
845 return True, current_policy
846
847
848 def handle_bucket_tags(s3_client: ClientType, module: AnsibleAWSModule, name: str) -> Tuple[bool, Optional[dict]]:
849 """
850 Manage tags for an S3 bucket.
851 Parameters:
852 s3_client (boto3.client): The Boto3 S3 client object.
853 module (AnsibleAWSModule): The Ansible module object.
854 name (str): The name of the bucket to handle tags for.
855 Returns:
856 A tuple containing a boolean indicating whether tags were changed
857 and a dictionary containing the updated tags.
858 """
859
860 tags = module.params.get("tags")
861 purge_tags = cast(bool, module.params.get("purge_tags"))
862
863 try:
864 current_tags_dict = get_s3_bucket_tagging(s3_client, name)
865 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
866 if tags is not None:
867 raise
868 module.warn(e.message)
869 return False, None
870
871 if tags is None:
872 return False, current_tags_dict
873
874 updated_tags = merge_tags(current_tags_dict, tags, purge_tags)
875
876 if current_tags_dict == updated_tags:
877 return False, current_tags_dict
878
879 if not updated_tags:
880 delete_s3_bucket_tagging(s3_client, name)
881 else:
882 put_s3_bucket_tagging(s3_client, name, updated_tags)
883 current_tags_dict = wait_tags_are_applied(s3_client, name, updated_tags)
884
885 return True, updated_tags
886
887
888 def _handle_remove_bucket_encryption(
889 s3_client: ClientType, name: str, current_encryption: Optional[dict]
890 ) -> Tuple[bool, Optional[dict]]:
891 current_encryption_algorithm = current_encryption.get("SSEAlgorithm") if current_encryption else None
892
893 if current_encryption_algorithm is None:
894 return False, current_encryption
895
896 delete_s3_bucket_encryption(s3_client, name)
897 current_encryption = wait_encryption_is_applied(s3_client, name, None)
898
899 return True, current_encryption
900
901
902 def _handle_bucket_encryption(
903 s3_client: ClientType,
904 name: str,
905 current_encryption: Optional[dict],
906 encryption: Optional[str],
907 encryption_key_id: Optional[str],
908 ) -> Tuple[bool, Optional[dict]]:
909 if encryption is None:
910 return False, current_encryption
911
912 current_encryption_algorithm = cast(dict, current_encryption).get("SSEAlgorithm") if current_encryption else None
913 current_encryption_key = cast(dict, current_encryption).get("KMSMasterKeyID") if current_encryption else None
914
915 if encryption == current_encryption_algorithm:
916 # Non KMS is simple
917 if encryption != "aws:kms":
918 return False, current_encryption
919 # When working with KMS, we also need to check the Key
920 if current_encryption_key == encryption_key_id:
921 return False, current_encryption
922
923 expected_encryption = {"SSEAlgorithm": encryption}
924 if encryption_key_id is not None:
925 expected_encryption["KMSMasterKeyID"] = encryption_key_id
926
927 current_encryption = put_bucket_encryption_with_retry(s3_client, name, expected_encryption)
928 return True, current_encryption
929
930
931 def _handle_bucket_key_encryption(
932 s3_client: ClientType, name, current_encryption, bucket_key_enabled
933 ) -> Tuple[bool, Optional[dict]]:
934 if bucket_key_enabled is None:
935 return False, current_encryption
936
937 current_encryption_algorithm = current_encryption.get("SSEAlgorithm") if current_encryption else None
938
939 if current_encryption_algorithm != "aws:kms":
940 if bucket_key_enabled:
941 raise AnsibleS3Error(
942 f'Unable to set bucket key: current encryption algorithm ("{current_encryption_algorithm}") is not "aws:kms"'
943 )
944 return False, current_encryption
945
946 if get_bucket_key_enabled(s3_client, name) == bucket_key_enabled:
947 return False, current_encryption
948
949 expected_encryption = bool(bucket_key_enabled)
950 put_bucket_key_with_retry(s3_client, name, expected_encryption)
951 return True, get_bucket_encryption(s3_client, name)
952
953
954 def handle_bucket_encryption(s3_client: ClientType, module: AnsibleAWSModule, name: str) -> Tuple[bool, Optional[dict]]:
955 """
956 Manage encryption settings for an S3 bucket.
957 Parameters:
958 s3_client (boto3.client): The Boto3 S3 client object.
959 module (AnsibleAWSModule): The Ansible module object.
960 name (str): The name of the bucket to handle encryption for.
961 Returns:
962 A tuple containing a boolean indicating whether encryption settings
963 were changed and a dictionary containing the updated encryption settings.
964 """
965 encryption = module.params.get("encryption")
966 encryption_key_id = module.params.get("encryption_key_id")
967 bucket_key_enabled = module.params.get("bucket_key_enabled")
968
969 try:
970 current_encryption = get_bucket_encryption(s3_client, name)
971 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
972 if encryption is not None:
973 raise
974 module.warn(e.message)
975 return False, None
976
977 if encryption == "none":
978 return _handle_remove_bucket_encryption(s3_client, name, current_encryption)
979
980 changed, current_encryption = _handle_bucket_encryption(
981 s3_client, name, current_encryption, encryption, encryption_key_id
982 )
983 bk_changed, current_encryption = _handle_bucket_key_encryption(
984 s3_client, name, current_encryption, bucket_key_enabled
985 )
986 changed |= bk_changed
987 return changed, current_encryption
988
989
990 def handle_bucket_ownership(s3_client: ClientType, module: AnsibleAWSModule, name: str) -> Tuple[bool, Optional[str]]:
991 """
992 Manage ownership settings for an S3 bucket.
993 Parameters:
994 s3_client (boto3.client): The Boto3 S3 client object.
995 module (AnsibleAWSModule): The Ansible module object.
996 name (str): The name of the bucket to handle ownership for.
997 Returns:
998 A tuple containing a boolean indicating whether ownership settings were changed
999 and a dictionary containing the updated ownership settings.
1000 """
1001
1002 delete_object_ownership = module.params.get("delete_object_ownership")
1003 object_ownership = module.params.get("object_ownership")
1004
1005 try:
1006 bucket_ownership = get_bucket_ownership_cntrl(s3_client, name)
1007 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
1008 if delete_object_ownership or object_ownership is not None:
1009 raise
1010 module.warn(e.message)
1011 return False, None
1012
1013 if delete_object_ownership:
1014 if bucket_ownership is None:
1015 return False, None
1016 delete_s3_bucket_ownership(s3_client, name)
1017 return True, None
1018
1019 if object_ownership is None:
1020 return False, bucket_ownership
1021 if bucket_ownership == object_ownership:
1022 return False, bucket_ownership
1023
1024 put_s3_bucket_ownership(s3_client, name, object_ownership=object_ownership)
1025 return True, object_ownership
1026
1027
1028 def handle_bucket_acl(
1029 s3_client: ClientType, module: AnsibleAWSModule, name: str
1030 ) -> Tuple[bool, Optional[str], Optional[dict]]:
1031 """
1032 Manage Access Control List (ACL) for an S3 bucket.
1033 Parameters:
1034 s3_client (boto3.client): The Boto3 S3 client object.
1035 module (AnsibleAWSModule): The Ansible module object.
1036 name (str): The name of the bucket to handle ACL for.
1037 Returns:
1038 A tuple containing a boolean indicating whether ACL was changed and a dictionary containing the updated ACL.
1039 """
1040
1041 acl = module.params.get("acl")
1042
1043 try:
1044 bucket_acl = get_s3_bucket_acl(s3_client, name)
1045 current_name = s3_acl_to_name(bucket_acl)
1046 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
1047 if acl is not None:
1048 raise
1049 module.warn(e.message)
1050 return False, None, None
1051
1052 if acl is None or acl == current_name:
1053 return False, current_name, bucket_acl
1054
1055 put_s3_bucket_acl(s3_client, name, acl)
1056 new_acl = get_s3_bucket_acl(s3_client, name)
1057 new_name = s3_acl_to_name(new_acl)
1058 return True, new_name, new_acl
1059
1060
1061 def handle_bucket_object_lock(s3_client: ClientType, module: AnsibleAWSModule, name: str) -> bool:
1062 """
1063 Manage object lock configuration for an S3 bucket.
1064 Parameters:
1065 s3_client (boto3.client): The Boto3 S3 client object.
1066 module (AnsibleAWSModule): The Ansible module object.
1067 name (str): The name of the bucket to handle object lock for.
1068 Returns:
1069 The updated object lock configuration.
1070 """
1071
1072 object_lock_enabled = module.params.get("object_lock_enabled")
1073
1074 try:
1075 object_lock_status = get_bucket_object_lock_enabled(s3_client, name)
1076 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
1077 if object_lock_enabled is not None:
1078 raise
1079 module.warn(e.message)
1080 return False
1081
1082 if object_lock_enabled is None:
1083 return object_lock_status
1084
1085 if not object_lock_enabled and object_lock_status:
1086 raise AnsibleS3Error("Disabling object lock for existing buckets is not supported")
1087 if object_lock_enabled and not object_lock_status:
1088 raise AnsibleS3Error("Enabling object lock for existing buckets is not supported")
1089
1090 return object_lock_status
1091
1092
1093 def handle_bucket_accelerate(s3_client: ClientType, module: AnsibleAWSModule, name: str) -> Tuple[bool, Optional[bool]]:
1094 """
1095 Manage transfer accelerate for an S3 bucket.
1096 Parameters:
1097 s3_client (boto3.client): The Boto3 S3 client object.
1098 module (AnsibleAWSModule): The Ansible module object.
1099 name (str): The name of the bucket to handle transfer accelerate for.
1100 Returns:
1101 A tuple containing a boolean indicating whether transfer accelerate setting was changed
1102 and a boolean indicating the transfer accelerate status.
1103 """
1104
1105 accelerate_enabled = module.params.get("accelerate_enabled")
1106
1107 try:
1108 accelerate_status = get_bucket_accelerate_status(s3_client, name)
1109 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
1110 if accelerate_enabled is not None:
1111 raise
1112 module.warn(e.message)
1113 return False, None
1114
1115 if accelerate_enabled is None:
1116 return False, accelerate_status
1117 if accelerate_enabled == accelerate_status:
1118 return False, accelerate_status
1119
1120 if not accelerate_enabled:
1121 delete_s3_bucket_accelerate_configuration(s3_client, name)
1122 return True, False
1123
1124 put_s3_bucket_accelerate_configuration(s3_client, name)
1125
1126 return True, True
1127
1128
1129 def handle_bucket_object_lock_retention(
1130 s3_client: ClientType, module: AnsibleAWSModule, name: str
1131 ) -> Tuple[bool, Optional[dict]]:
1132 """
1133 Manage object lock retention configuration for an S3 bucket.
1134 Parameters:
1135 s3_client (boto3.client): The Boto3 S3 client object.
1136 module (AnsibleAWSModule): The Ansible module object.
1137 name (str): The name of the bucket to handle object lock for.
1138 Returns:
1139 A tuple containing a boolean indicating whether the bucket object lock
1140 retention configuration was changed and a dictionary containing the change.
1141 """
1142
1143 object_lock_enabled = module.params.get("object_lock_enabled")
1144 object_lock_default_retention = module.params.get("object_lock_default_retention")
1145
1146 try:
1147 if object_lock_enabled:
1148 object_lock_configuration_status = get_object_lock_configuration(s3_client, name)
1149 else:
1150 object_lock_configuration_status = {}
1151 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
1152 if object_lock_default_retention is not None:
1153 raise
1154 module.warn(e.message)
1155 return False, None
1156
1157 if object_lock_default_retention is None:
1158 return False, object_lock_configuration_status
1159
1160 if not object_lock_default_retention and object_lock_configuration_status:
1161 raise AnsibleS3Error("Removing object lock default retention is not supported")
1162
1163 conf = scrub_none_parameters(snake_dict_to_camel_dict(object_lock_default_retention, capitalize_first=True))
1164 if object_lock_configuration_status == conf:
1165 return False, object_lock_configuration_status
1166
1167 put_s3_object_lock_configuration(s3_client, name, conf)
1168 return True, object_lock_default_retention
1169
1170
1171 def handle_bucket_inventory(s3_client: ClientType, module: AnsibleAWSModule, name: str) -> Tuple[bool, Optional[list]]:
1172 """
1173 Manage inventory configuration for an S3 bucket.
1174 Parameters:
1175 s3_client (boto3.client): The Boto3 S3 client object.
1176 module (AnsibleAWSModule): The Ansible module object.
1177 name (str): The name of the bucket to handle inventory for.
1178 Returns:
1179 A tuple containing a boolean indicating whether inventory settings were changed
1180 and a dictionary containing the updated inventory.
1181 """
1182 declared_inventories = module.params.get("inventory")
1183
1184 try:
1185 current_inventories = list_bucket_inventory_configurations(s3_client, name)
1186 present_inventories = {i["Id"]: i for i in current_inventories}
1187 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
1188 if declared_inventories is not None:
1189 raise
1190 module.warn(e.message)
1191 return False, None
1192
1193 if declared_inventories is None:
1194 return (False, current_inventories)
1195
1196 declared_inventories = cast(list, declared_inventories)
1197 bucket_changed = False
1198 results = []
1199
1200 for declared_inventory in declared_inventories:
1201 camel_destination = snake_dict_to_camel_dict(declared_inventory.get("destination", {}), True)
1202 declared_inventory_api = {
1203 "IsEnabled": True,
1204 "Id": declared_inventory.get("id"),
1205 "Destination": {"S3BucketDestination": {k: v for k, v in camel_destination.items() if v is not None}},
1206 "IncludedObjectVersions": declared_inventory.get("included_object_versions"),
1207 "Schedule": {"Frequency": declared_inventory.get("schedule")},
1208 "OptionalFields": [],
1209 }
1210 for field in declared_inventory.get("optional_fields", []):
1211 declared_inventory_api["OptionalFields"].append(field)
1212 if declared_inventory.get("filter") is not None:
1213 declared_inventory_api["Filter"] = {"Prefix": declared_inventory.get("filter")}
1214
1215 present_inventory = present_inventories.pop(declared_inventory_api["Id"], None)
1216
1217 if declared_inventory_api != present_inventory:
1218 put_s3_bucket_inventory(s3_client, name, declared_inventory_api)
1219 bucket_changed = True
1220
1221 results.append(declared_inventory_api)
1222
1223 for inventory_id in present_inventories.keys():
1224 delete_s3_bucket_inventory(s3_client, name, inventory_id)
1225 bucket_changed = True
1226
1227 return bucket_changed, results
1228
1229
1230 def handle_bucket_logging(s3_client: ClientType, module: AnsibleAWSModule, name: str) -> Tuple[bool, Optional[dict]]:
1231 """
1232 Manage logging configuration for an S3 bucket.
1233 Parameters:
1234 s3_client (boto3.client): The Boto3 S3 client object.
1235 module (AnsibleAWSModule): The Ansible module object.
1236 name (str): The name of the bucket to handle logging for.
1237 Returns:
1238 A tuple containing a boolean indicating whether logging settings were changed
1239 and a dictionary containing the updated logging configuration.
1240 """
1241 logging_param = module.params.get("logging")
1242
1243 try:
1244 current_logging = get_s3_bucket_logging(s3_client, name)
1245 except (AnsibleS3PermissionsError, AnsibleS3SupportError) as e:
1246 if logging_param is not None:
1247 raise
1248 module.warn(e.message)
1249 return False, None
1250
1251 # Normalize current logging state
1252 current_normalized = normalize_s3_bucket_logging(current_logging)
1253
1254 # If no logging parameter specified, return current state
1255 if logging_param is None:
1256 return False, current_normalized
1257
1258 # Determine desired state
1259 # Disable logging if empty dict or target_bucket is empty string
1260 if logging_param == {} or logging_param.get("target_bucket") == "":
1261 desired_config = {}
1262 desired_normalized = None
1263 else:
1264 # Enable logging with specified configuration
1265 target_bucket = logging_param.get("target_bucket")
1266 target_prefix = logging_param.get("target_prefix", "")
1267
1268 desired_config = {
1269 "LoggingEnabled": {
1270 "TargetBucket": target_bucket,
1271 "TargetPrefix": target_prefix,
1272 }
1273 }
1274 desired_normalized = {
1275 "target_bucket": target_bucket,
1276 "target_prefix": target_prefix,
1277 }
1278
1279 # Compare current and desired states
1280 if current_normalized == desired_normalized:
1281 return False, current_normalized
1282
1283 # Make the change
1284 put_s3_bucket_logging(s3_client, name, desired_config)
1285
1286 return True, desired_normalized
1287
1288
1289 def create_or_update_bucket(s3_client: ClientType, module: AnsibleAWSModule) -> NoReturn:
1290 """
1291 Create or update an S3 bucket along with its associated configurations.
1292 This function creates a new S3 bucket if it does not already exist, and updates its configurations,
1293 such as versioning, requester pays, public access block configuration, policy, tags, encryption, bucket ownership,
1294 ACL, and object lock settings. It returns whether any changes were made and the updated configurations.
1295 Parameters:
1296 s3_client (boto3.client): The Boto3 S3 client object.
1297 module (AnsibleAWSModule): The Ansible module object.
1298 Returns:
1299 None
1300 """
1301 name = cast(str, module.params.get("name"))
1302 object_lock_enabled = module.params.get("object_lock_enabled")
1303 location = get_s3_bucket_location(module)
1304
1305 changed = False
1306 result: dict = {}
1307
1308 bucket_is_present = s3_bucket_exists(s3_client, name)
1309
1310 if not bucket_is_present:
1311 account_regional = module.params.get("account_regional")
1312 changed = create_bucket(s3_client, name, location, object_lock_enabled, account_regional)
1313 waiter = get_s3_waiter(s3_client, "bucket_exists")
1314 S3ErrorHandler.common_error_handler(f"wait for bucket {name} to be created")(waiter.wait)(Bucket=name)
1315
1316 # Versioning
1317 versioning_changed, versioning_result = handle_bucket_versioning(s3_client, module, name)
1318 result["versioning"] = versioning_result
1319
1320 # Requester pays
1321 requester_pays_changed, requester_pays_result = handle_bucket_requester_pays(s3_client, module, name)
1322 result["requester_pays"] = requester_pays_result
1323
1324 # Public access clock configuration
1325 public_access_config_changed, public_access_config_result = handle_bucket_public_access_config(
1326 s3_client, module, name
1327 )
1328 result["public_access_block"] = public_access_config_result
1329
1330 # Policy
1331 policy_changed, current_policy = handle_bucket_policy(s3_client, module, name)
1332 result["policy"] = current_policy
1333
1334 # Tags
1335 tags_changed, current_tags_dict = handle_bucket_tags(s3_client, module, name)
1336 result["tags"] = current_tags_dict
1337
1338 # Encryption
1339 encryption_changed, current_encryption = handle_bucket_encryption(s3_client, module, name)
1340 result["encryption"] = current_encryption
1341
1342 # -- Bucket ownership
1343 bucket_ownership_changed, object_ownership_result = handle_bucket_ownership(s3_client, module, name)
1344 result["object_ownership"] = object_ownership_result
1345
1346 # -- Bucket ACL
1347 bucket_acl_changed, bucket_acl_result, acl_info = handle_bucket_acl(s3_client, module, name)
1348 result["acl"] = bucket_acl_result
1349 result["acl_grants"] = normalize_s3_bucket_acls(acl_info)
1350
1351 # -- Transfer Acceleration
1352 bucket_accelerate_changed, bucket_accelerate_result = handle_bucket_accelerate(s3_client, module, name)
1353 result["accelerate_enabled"] = bucket_accelerate_result
1354
1355 # TODO - MERGE handle_bucket_object_lock and handle_bucket_object_lock_retention
1356 # -- Object Lock
1357 bucket_object_lock_result = handle_bucket_object_lock(s3_client, module, name)
1358 result["object_lock_enabled"] = bucket_object_lock_result
1359
1360 # -- Object Lock Default Retention
1361 bucket_object_lock_retention_changed, bucket_object_lock_retention_result = handle_bucket_object_lock_retention(
1362 s3_client, module, name
1363 )
1364 result["object_lock_default_retention"] = bucket_object_lock_retention_result
1365 # -- Inventory
1366 bucket_inventory_changed, bucket_inventory_result = handle_bucket_inventory(s3_client, module, name)
1367 result["bucket_inventory"] = bucket_inventory_result
1368
1369 # -- Logging
1370 bucket_logging_changed, bucket_logging_result = handle_bucket_logging(s3_client, module, name)
1371 result["logging"] = bucket_logging_result
1372
1373 # Module exit
1374 changed = (
1375 changed
1376 or versioning_changed
1377 or requester_pays_changed
1378 or public_access_config_changed
1379 or policy_changed
1380 or tags_changed
1381 or encryption_changed
1382 or bucket_ownership_changed
1383 or bucket_acl_changed
1384 or bucket_accelerate_changed
1385 or bucket_object_lock_retention_changed
1386 or bucket_inventory_changed
1387 or bucket_logging_changed
1388 )
1389 module.exit_json(changed=changed, name=name, **result)
1390
1391
1392 @S3ErrorHandler.common_error_handler("create S3 bucket")
1393 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["OperationAborted"])
1394 def _create_bucket(s3_client: ClientType, **params) -> bool:
1395 try:
1396 s3_client.create_bucket(**params)
1397 return True
1398 except is_boto3_error_code("BucketAlreadyOwnedByYou"):
1399 # We should never get here since we check the bucket presence before calling the create_or_update_bucket
1400 # method. However, the AWS Api sometimes fails to report bucket presence, so we catch this exception
1401 return False
1402
1403
1404 def create_bucket(
1405 s3_client: ClientType,
1406 bucket_name: str,
1407 location: str,
1408 object_lock_enabled: Optional[bool] = False,
1409 account_regional: Optional[bool] = None,
1410 ) -> bool:
1411 """
1412 Create an S3 bucket.
1413 Parameters:
1414 s3_client (boto3.client): The Boto3 S3 client object.
1415 bucket_name (str): The name of the bucket to create.
1416 location (str): The AWS region where the bucket should be created. If None, it defaults to "us-east-1".
1417 object_lock_enabled (bool): Whether to enable object lock for the bucket. Defaults to False.
1418 account_regional (bool): Whether to create the bucket in the account-regional namespace. Defaults to None (global namespace).
1419 Returns:
1420 True if the bucket was successfully created, False otherwise.
1421 """
1422 params: dict = {"Bucket": bucket_name}
1423
1424 configuration: dict = {}
1425 if location not in ("us-east-1", None):
1426 configuration["LocationConstraint"] = location
1427
1428 if configuration:
1429 params["CreateBucketConfiguration"] = configuration
1430
1431 if object_lock_enabled is not None:
1432 params["ObjectLockEnabledForBucket"] = object_lock_enabled
1433 if account_regional:
1434 params["BucketNamespace"] = "account-regional"
1435 return _create_bucket(s3_client, **params)
1436
1437
1438 def get_object_lock_configuration(s3_client: ClientType, bucket_name: str) -> Optional[dict]:
1439 """
1440 Get the object lock default retention configuration for an S3 bucket.
1441 Parameters:
1442 s3_client (boto3.client): The Boto3 S3 client object.
1443 bucket_name (str): The name of the S3 bucket.
1444 Returns:
1445 Object lock default retention configuration dictionary.
1446 """
1447 result = get_s3_object_lock_configuration(s3_client, bucket_name)
1448 return result.get("Rule", {}).get("DefaultRetention", {})
1449
1450
1451 def get_bucket_accelerate_status(s3_client: ClientType, bucket_name: str) -> bool:
1452 """
1453 Get transfer accelerate status of the S3 bucket.
1454 Parameters:
1455 s3_client (boto3.client): The Boto3 S3 client object.
1456 bucket_name (str): The name of the S3 bucket.
1457 Returns:
1458 Transfer accelerate status of the S3 bucket.
1459 """
1460 accelerate_configuration = get_s3_bucket_accelerate_configuration(s3_client, bucket_name)
1461 return accelerate_configuration.get("Status") == "Enabled"
1462
1463
1464 def get_bucket_object_lock_enabled(s3_client: ClientType, bucket_name: str) -> bool:
1465 """
1466 Retrieve the object lock configuration status for an S3 bucket.
1467 Parameters:
1468 s3_client (boto3.client): The Boto3 S3 client object.
1469 bucket_name (str): The name of the S3 bucket.
1470 Returns:
1471 True if object lock is enabled for the bucket, False otherwise.
1472 """
1473 object_lock_configuration = get_s3_object_lock_configuration(s3_client, bucket_name)
1474 return object_lock_configuration.get("ObjectLockEnabled") == "Enabled"
1475
1476
1477 def get_bucket_encryption(s3_client: ClientType, bucket_name: str) -> Optional[dict]:
1478 """
1479 Retrieve the encryption configuration for an S3 bucket.
1480 Parameters:
1481 s3_client (boto3.client): The Boto3 S3 client object.
1482 bucket_name (str): The name of the S3 bucket.
1483 Returns:
1484 Encryption configuration of the bucket.
1485 """
1486 try:
1487 result = get_s3_bucket_encryption(s3_client, bucket_name)
1488 return result.get("Rules", [])[0].get("ApplyServerSideEncryptionByDefault")
1489 except (IndexError, KeyError):
1490 return None
1491
1492
1493 def get_bucket_key_enabled(s3_client: ClientType, bucket_name: str) -> Optional[bool]:
1494 """
1495 Retrieve the status of server-side encryption for an S3 bucket.
1496 Parameters:
1497 s3_client (boto3.client): The Boto3 S3 client object.
1498 bucket_name (str): The name of the S3 bucket.
1499 Returns:
1500 Whether or not if server-side encryption is enabled for the bucket.
1501 """
1502 try:
1503 result = get_s3_bucket_encryption(s3_client, bucket_name)
1504 return result.get("Rules", [])[0].get("BucketKeyEnabled")
1505 except (IndexError, KeyError):
1506 return None
1507
1508
1509 def put_bucket_encryption_with_retry(s3_client: ClientType, name: str, expected_encryption: dict) -> dict:
1510 """
1511 Set the encryption configuration for an S3 bucket with retry logic.
1512 Parameters:
1513 s3_client (boto3.client): The Boto3 S3 client object.
1514 name (str): The name of the S3 bucket.
1515 expected_encryption (dict): A dictionary containing the expected encryption configuration.
1516 Returns:
1517 Updated encryption configuration of the bucket.
1518 """
1519 max_retries = 3
1520 for retries in range(1, max_retries + 1):
1521 put_s3_bucket_encryption(s3_client, name, expected_encryption)
1522 current_encryption = wait_encryption_is_applied(
1523 s3_client, name, expected_encryption, should_fail=(retries == max_retries), retries=5
1524 )
1525 if current_encryption == expected_encryption:
1526 return current_encryption
1527
1528 # We shouldn't get here, the only time this should happen is if
1529 # current_encryption != expected_encryption and retries == max_retries
1530 raise AnsibleS3Error("Failed to set bucket encryption configuration")
1531
1532
1533 def put_bucket_key_with_retry(s3_client: ClientType, name: str, expected_encryption: bool) -> None:
1534 """
1535 Set the status of server-side encryption for an S3 bucket.
1536 Parameters:
1537 module (AnsibleAWSModule): The Ansible module object.
1538 s3_client (boto3.client): The Boto3 S3 client object.
1539 name (str): The name of the S3 bucket.
1540 expected_encryption (bool): The expected status of server-side encryption using AWS KMS.
1541 Returns:
1542 The updated status of server-side encryption using AWS KMS for the bucket.
1543 """
1544 max_retries = 3
1545 for retries in range(1, max_retries + 1):
1546 put_bucket_key(s3_client, name, expected_encryption)
1547 try:
1548 wait_bucket_key_is_applied(s3_client, name, expected_encryption, retries=5)
1549 return
1550 except AnsibleS3Error:
1551 if retries == max_retries:
1552 raise
1553 pass
1554
1555 # We shouldn't get here, the only time this should happen is if
1556 # current_encryption != expected_encryption and retries == max_retries
1557 raise AnsibleS3Error("Failed to set bucket key")
1558
1559
1560 @S3ErrorHandler.common_error_handler("set bucket key based encryption")
1561 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
1562 def put_bucket_key(s3_client: ClientType, bucket_name: str, encryption: bool) -> None:
1563 """
1564 Set the status of server-side encryption for an S3 bucket.
1565 Parameters:
1566 s3_client (boto3.client): The Boto3 S3 client object.
1567 bucket_name (str): The name of the S3 bucket.
1568 encryption (bool): The status of server-side encryption using AWS KMS.
1569 Returns:
1570 None
1571 """
1572 # server_side_encryption_configuration ={'Rules': [{'BucketKeyEnabled': encryption}]}
1573 encryption_status = get_s3_bucket_encryption(s3_client, bucket_name)
1574 encryption_status["Rules"][0]["BucketKeyEnabled"] = encryption
1575 s3_client.put_bucket_encryption(Bucket=bucket_name, ServerSideEncryptionConfiguration=encryption_status)
1576
1577
1578 def wait_policy_is_applied(
1579 s3_client: ClientType, bucket_name: str, expected_policy: dict, should_fail: bool = True
1580 ) -> Optional[dict]:
1581 """
1582 Wait for a bucket policy to be applied to an S3 bucket.
1583 Parameters:
1584 module (AnsibleAWSModule): The Ansible module object.
1585 s3_client (boto3.client): The Boto3 S3 client object.
1586 bucket_name (str): The name of the S3 bucket.
1587 expected_policy (dict): The expected bucket policy.
1588 should_fail (bool): Flag indicating whether to fail if the policy is not applied within the expected time. Default is True.
1589 Returns:
1590 The current policy applied to the bucket, or None if the policy failed to apply within the expected time.
1591 """
1592 for dummy in range(0, 12):
1593 current_policy = get_s3_bucket_policy(s3_client, bucket_name)
1594 if not compare_policies(current_policy, expected_policy):
1595 return current_policy
1596 time.sleep(5)
1597
1598 if should_fail:
1599 raise AnsibleS3Error(message="Bucket policy failed to apply in the expected time")
1600 return None
1601
1602
1603 def wait_payer_is_applied(
1604 s3_client: ClientType, bucket_name: str, expected_payer: str, should_fail=True
1605 ) -> Optional[str]:
1606 """
1607 Wait for the requester pays setting to be applied to an S3 bucket.
1608 Parameters:
1609 s3_client (boto3.client): The Boto3 S3 client object.
1610 bucket_name (str): The name of the S3 bucket.
1611 expected_payer (bool): The expected status of the requester pays setting.
1612 should_fail (bool): Flag indicating whether to fail if the setting is not applied within the expected time. Default is True.
1613 Returns:
1614 The current status of the requester pays setting applied to the bucket.
1615 """
1616 for dummy in range(0, 12):
1617 requester_pays_status = get_s3_bucket_request_payment(s3_client, bucket_name)
1618 if requester_pays_status == expected_payer:
1619 return requester_pays_status
1620 time.sleep(5)
1621
1622 if should_fail:
1623 raise AnsibleS3Error(message="Bucket request payer setting failed to apply in the expected time")
1624 return None
1625
1626
1627 def wait_encryption_is_applied(
1628 s3_client: ClientType,
1629 bucket_name: str,
1630 expected_encryption: Optional[dict],
1631 should_fail: bool = True,
1632 retries: int = 12,
1633 ) -> Optional[dict]:
1634 """
1635 Wait for the encryption setting to be applied to an S3 bucket.
1636 Parameters:
1637 module (AnsibleAWSModule): The Ansible module object.
1638 s3_client (boto3.client): The Boto3 S3 client object.
1639 bucket_name (str): The name of the S3 bucket.
1640 expected_encryption(dict): The expected encryption setting.
1641 should_fail (bool): Flag indicating whether to fail if the setting is not applied within the expected time. Default is True.
1642 retries (int): The number of retries to attempt. Default is 12.
1643 Returns:
1644 The current encryption setting applied to the bucket.
1645 """
1646 for dummy in range(0, retries):
1647 encryption = get_bucket_encryption(s3_client, bucket_name)
1648 if encryption != expected_encryption:
1649 time.sleep(5)
1650 else:
1651 return encryption
1652
1653 if should_fail:
1654 raise AnsibleS3Error("Bucket encryption failed to apply in the expected time")
1655
1656 return encryption
1657
1658
1659 def wait_bucket_key_is_applied(
1660 s3_client: ClientType, bucket_name: str, expected_encryption: bool, retries: int = 12
1661 ) -> None:
1662 """
1663 Wait for the bucket key setting to be applied to an S3 bucket.
1664 Parameters:
1665 module (AnsibleAWSModule): The Ansible module object.
1666 s3_client (boto3.client): The Boto3 S3 client object.
1667 bucket_name (str): The name of the S3 bucket.
1668 expected_encryption (bool): The expected bucket key setting.
1669 should_fail (bool): Flag indicating whether to fail if the setting is not applied within the expected time. Default is True.
1670 retries (int): The number of retries to attempt. Default is 12.
1671 Returns:
1672 The current bucket key setting applied to the bucket.
1673 """
1674 extension = "enabled" if expected_encryption else "disabled"
1675 waiter_name = f"bucket_key_encryption_{extension}"
1676 waiter = get_s3_waiter(s3_client, waiter_name)
1677 S3ErrorHandler.common_error_handler(f"wait for bucket key encryption to be {extension}")(waiter.wait)(
1678 Bucket=bucket_name
1679 )
1680
1681
1682 def wait_versioning_is_applied(s3_client: ClientType, bucket_name: str, required_versioning: str) -> None:
1683 """
1684 Wait for the versioning setting to be applied to an S3 bucket.
1685 Parameters:
1686 s3_client (boto3.client): The Boto3 S3 client object.
1687 bucket_name (str): The name of the S3 bucket.
1688 required_versioning (dict): The required versioning status.
1689 Returns:
1690 The current versioning status applied to the bucket.
1691 """
1692 waiter_name = "bucket_versioning_enabled" if required_versioning == "Enabled" else "bucket_versioning_suspended"
1693 waiter = get_s3_waiter(s3_client, waiter_name)
1694 S3ErrorHandler.common_error_handler(f"wait for bucket versioning to be {required_versioning}")(waiter.wait)(
1695 Bucket=bucket_name
1696 )
1697
1698
1699 def wait_tags_are_applied(s3_client: ClientType, bucket_name: str, expected_tags_dict: dict) -> dict:
1700 """
1701 Wait for the tags to be applied to an S3 bucket.
1702 Parameters:
1703 s3_client (boto3.client): The Boto3 S3 client object.
1704 bucket_name (str): The name of the S3 bucket.
1705 expected_tags_dict (dict): The expected tags dictionary.
1706 Returns:
1707 The current tags dictionary applied to the bucket.
1708 """
1709 for dummy in range(0, 12):
1710 current_tags_dict = get_s3_bucket_tagging(s3_client, bucket_name)
1711 if current_tags_dict == expected_tags_dict:
1712 return current_tags_dict
1713 time.sleep(5)
1714
1715 raise AnsibleS3Error(message="Bucket tags failed to apply in the expected time")
1716
1717
1718 def get_bucket_ownership_cntrl(s3_client, bucket_name: str) -> Optional[str]:
1719 """
1720 Get the current bucket ownership controls.
1721 Parameters:
1722 s3_client (boto3.client): The Boto3 S3 client object.
1723 bucket_name (str): The name of the S3 bucket.
1724 Returns:
1725 The object ownership rule
1726 """
1727 result = get_s3_bucket_ownership_controls(s3_client, bucket_name)
1728 if not result:
1729 return None
1730 try:
1731 return result["Rules"][0]["ObjectOwnership"]
1732 except (KeyError, IndexError) as e:
1733 raise AnsibleS3SupportError(message="Failed to parse bucket object ownership settings") from e
1734
1735
1736 def paginated_list(s3_client: ClientType, **pagination_params) -> Iterator[List[str]]:
1737 """
1738 Paginate through the list of objects in an S3 bucket.
1739 This function yields the keys of objects in the S3 bucket, paginating through the results.
1740 Parameters:
1741 s3_client (boto3.client): The Boto3 S3 client object.
1742 **pagination_params: Additional parameters to pass to the paginator.
1743 Yields:
1744 list: A list of keys of objects in the bucket for each page of results.
1745 """
1746 pg = s3_client.get_paginator("list_objects_v2")
1747 for page in pg.paginate(**pagination_params):
1748 yield [data["Key"] for data in page.get("Contents", [])]
1749
1750
1751 def paginated_versions_list(s3_client: ClientType, **pagination_params) -> Iterator[List[Tuple[str, str]]]:
1752 """
1753 Paginate through the list of object versions in an S3 bucket.
1754 This function yields the keys and version IDs of object versions in the S3 bucket, paginating through the results.
1755 Parameters:
1756 s3_client (boto3.client): The Boto3 S3 client object.
1757 **pagination_params: Additional parameters to pass to the paginator.
1758 Yields:
1759 list: A list of tuples containing keys and version IDs of object versions in the bucket for each page of results.
1760 """
1761 try:
1762 pg = s3_client.get_paginator("list_object_versions")
1763 for page in pg.paginate(**pagination_params):
1764 # We have to merge the Versions and DeleteMarker lists here, as DeleteMarkers can still prevent a bucket deletion
1765 yield [
1766 (data["Key"], data["VersionId"]) for data in (page.get("Versions", []) + page.get("DeleteMarkers", []))
1767 ]
1768 except is_boto3_error_code("NoSuchBucket"):
1769 yield []
1770
1771
1772 @S3ErrorHandler.deletion_error_handler("delete objects in bucket")
1773 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["OperationAborted"])
1774 def delete_objects(s3_client: ClientType, module: AnsibleAWSModule, name: str) -> None:
1775 """
1776 Delete objects from an S3 bucket.
1777 Parameters:
1778 s3_client (boto3.client): The Boto3 S3 client object.
1779 module (AnsibleAWSModule): The Ansible module object.
1780 name (str): The name of the S3 bucket.
1781 Returns:
1782 None
1783 """
1784 for key_version_pairs in paginated_versions_list(s3_client, Bucket=name):
1785 formatted_keys = [{"Key": key, "VersionId": version} for key, version in key_version_pairs]
1786 for fk in formatted_keys:
1787 # remove VersionId from cases where they are `None` so that
1788 # unversioned objects are deleted using `DeleteObject`
1789 # rather than `DeleteObjectVersion`, improving backwards
1790 # compatibility with older IAM policies.
1791 if not fk.get("VersionId") or fk.get("VersionId") == "null":
1792 fk.pop("VersionId")
1793 if formatted_keys:
1794 resp = s3_client.delete_objects(Bucket=name, Delete={"Objects": formatted_keys})
1795 if resp.get("Errors"):
1796 objects_to_delete = ", ".join([k["Key"] for k in resp["Errors"]])
1797 raise AnsibleS3Error(
1798 f"Could not empty bucket before deleting. Could not delete objects: {objects_to_delete}",
1799 errors=resp["Errors"],
1800 )
1801
1802
1803 def destroy_bucket(s3_client: ClientType, module: AnsibleAWSModule) -> None:
1804 """
1805 This function destroys an S3 bucket.
1806 Parameters:
1807 s3_client (boto3.client): The Boto3 S3 client object.
1808 module (AnsibleAWSModule): The Ansible module object.
1809 Returns:
1810 None
1811 """
1812 force = module.params.get("force")
1813 name = cast(str, module.params.get("name"))
1814 bucket_is_present = s3_bucket_exists(s3_client, name)
1815
1816 if not bucket_is_present:
1817 module.exit_json(changed=False)
1818
1819 if force:
1820 # if there are contents then we need to delete them (including versions) before we can delete the bucket
1821 delete_objects(s3_client, module, name)
1822
1823 delete_s3_bucket(s3_client, name)
1824 waiter = get_s3_waiter(s3_client, "bucket_not_exists")
1825 S3ErrorHandler.deletion_error_handler(f"wait for bucket f{name} to be deleted")(waiter.wait)(Bucket=name)
1826
1827 module.exit_json(changed=True)
1828
1829
1830 def main():
1831 argument_spec = dict(
1832 name=dict(required=True),
1833 validate_bucket_name=dict(type="bool", default=True),
1834 dualstack=dict(default=False, type="bool"),
1835 state=dict(default="present", choices=["present", "absent"]),
1836 ceph=dict(default=False, type="bool", aliases=["rgw"]),
1837 account_regional=dict(type="bool"),
1838 # ** Warning **
1839 # we support non-AWS implementations, only force/purge options should have a
1840 # default set for any top-level option. We need to be able to identify
1841 # unset options where we can ignore NotImplemented exceptions.
1842 tags=dict(type="dict", aliases=["resource_tags"]),
1843 purge_tags=dict(type="bool", default=True),
1844 force=dict(default=False, type="bool"),
1845 policy=dict(type="json"),
1846 versioning=dict(type="bool"),
1847 requester_pays=dict(type="bool"),
1848 encryption=dict(choices=["none", "AES256", "aws:kms"]),
1849 encryption_key_id=dict(),
1850 bucket_key_enabled=dict(type="bool"),
1851 public_access=dict(
1852 type="dict",
1853 options=dict(
1854 block_public_acls=dict(type="bool", default=False),
1855 ignore_public_acls=dict(type="bool", default=False),
1856 block_public_policy=dict(type="bool", default=False),
1857 restrict_public_buckets=dict(type="bool", default=False),
1858 ),
1859 ),
1860 delete_public_access=dict(type="bool", default=False),
1861 object_ownership=dict(type="str", choices=["BucketOwnerEnforced", "BucketOwnerPreferred", "ObjectWriter"]),
1862 delete_object_ownership=dict(type="bool", default=False),
1863 acl=dict(type="str", choices=["private", "public-read", "public-read-write", "authenticated-read"]),
1864 accelerate_enabled=dict(type="bool"),
1865 object_lock_enabled=dict(type="bool"),
1866 object_lock_default_retention=dict(
1867 type="dict",
1868 options=dict(
1869 mode=dict(type="str", choices=["GOVERNANCE", "COMPLIANCE"], required=True),
1870 years=dict(type="int"),
1871 days=dict(type="int"),
1872 ),
1873 mutually_exclusive=[("days", "years")],
1874 required_one_of=[("days", "years")],
1875 ),
1876 inventory=dict(
1877 type="list",
1878 elements="dict",
1879 options=dict(
1880 destination=dict(
1881 type="dict",
1882 options=dict(
1883 account_id=dict(type="str"),
1884 bucket=dict(type="str", required=True),
1885 format=dict(type="str", choices=["CSV", "ORC", "Parquet"], required=True),
1886 prefix=dict(type="str"),
1887 ),
1888 required=True,
1889 ),
1890 filter=dict(type="str"),
1891 optional_fields=dict(
1892 type="list",
1893 elements="str",
1894 choices=[
1895 "Size",
1896 "LastModifiedDate",
1897 "StorageClass",
1898 "ETag",
1899 "IsMultipartUploaded",
1900 "ReplicationStatus",
1901 "EncryptionStatus",
1902 "ObjectLockRetainUntilDate",
1903 "ObjectLockMode",
1904 "ObjectLockLegalHoldStatus",
1905 "IntelligentTieringAccessTier",
1906 "BucketKeyStatus",
1907 "ChecksumAlgorithm",
1908 "ObjectAccessControlList",
1909 "ObjectOwner",
1910 ],
1911 ),
1912 id=dict(type="str", required=True),
1913 schedule=dict(type="str", choices=["Daily", "Weekly"], required=True),
1914 included_object_versions=dict(type="str", choices=["All", "Current"], required=True),
1915 ),
1916 ),
1917 logging=dict(
1918 type="dict",
1919 options=dict(
1920 target_bucket=dict(type="str", required=True),
1921 target_prefix=dict(type="str", default=""),
1922 ),
1923 ),
1924 )
1925
1926 required_by = dict(
1927 encryption_key_id=("encryption",),
1928 object_lock_default_retention=("object_lock_enabled",),
1929 )
1930
1931 mutually_exclusive = [
1932 ["public_access", "delete_public_access"],
1933 ["delete_object_ownership", "object_ownership"],
1934 ["dualstack", "endpoint_url"],
1935 ]
1936
1937 required_if = [
1938 ["ceph", True, ["endpoint_url"]],
1939 ]
1940
1941 module = AnsibleAWSModule(
1942 argument_spec=argument_spec,
1943 required_by=required_by,
1944 required_if=required_if,
1945 mutually_exclusive=mutually_exclusive,
1946 )
1947
1948 # Parameter validation
1949 encryption = module.params.get("encryption")
1950 encryption_key_id = module.params.get("encryption_key_id")
1951 if encryption_key_id is not None and encryption != "aws:kms":
1952 module.fail_json(
1953 msg="Only 'aws:kms' is a valid option for encryption parameter when you specify encryption_key_id."
1954 )
1955
1956 extra_params = s3_extra_params(module.params)
1957 retry_decorator = AWSRetry.jittered_backoff(
1958 max_delay=120,
1959 catch_extra_error_codes=["NoSuchBucket", "OperationAborted"],
1960 )
1961 s3_client = module.client("s3", retry_decorator=retry_decorator, **extra_params)
1962
1963 if module.params.get("validate_bucket_name"):
1964 err = validate_bucket_name(module.params["name"])
1965 if err:
1966 module.fail_json(msg=err)
1967
1968 account_regional = module.params.get("account_regional")
1969 if account_regional:
1970 region = module.params.get("region") or module.region
1971 err = validate_account_regional_bucket_name(module.params["name"], region)
1972 if err:
1973 module.fail_json(msg=err)
1974
1975 state = module.params.get("state")
1976
1977 try:
1978 if state == "present":
1979 create_or_update_bucket(s3_client, module)
1980 elif state == "absent":
1981 destroy_bucket(s3_client, module)
1982 except AnsibleS3Error as e:
1983 module.fail_json_aws_error(e)
1984
1985
1986 if __name__ == "__main__":
1987 main()