Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/s3_bucket_info.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 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 ---
11 module: s3_bucket_info
12 version_added: 1.0.0
13 version_added_collection: community.aws
14 author:
15 - "Gerben Geijteman (@hyperized)"
16 short_description: Lists S3 buckets in AWS
17 description:
18 - Lists S3 buckets and details about those buckets.
19 - Prior to release 5.0.0 this module was called M(community.aws.aws_s3_bucket_info).
20 The usage did not change.
21 options:
22 name:
23 description:
24 - Name of bucket to query.
25 type: str
26 default: ""
27 version_added: 1.4.0
28 name_filter:
29 description:
30 - Limits buckets to only buckets who's name contain the string in O(name_filter).
31 type: str
32 default: ""
33 version_added: 1.4.0
34 bucket_facts:
35 description:
36 - Retrieve requested S3 bucket detailed information.
37 - Each bucket_X option executes one API call, hence many options being set to V(true) will cause slower module execution.
38 - You can limit buckets by using the O(name) or O(name_filter) option.
39 suboptions:
40 bucket_accelerate_configuration:
41 description: Retrieve S3 accelerate configuration.
42 type: bool
43 default: False
44 bucket_location:
45 description: Retrieve S3 bucket location.
46 type: bool
47 default: False
48 bucket_replication:
49 description: Retrieve S3 bucket replication.
50 type: bool
51 default: False
52 bucket_acl:
53 description: Retrieve S3 bucket ACLs.
54 type: bool
55 default: False
56 bucket_logging:
57 description: Retrieve S3 bucket logging.
58 type: bool
59 default: False
60 bucket_request_payment:
61 description: Retrieve S3 bucket request payment.
62 type: bool
63 default: False
64 bucket_tagging:
65 description: Retrieve S3 bucket tagging.
66 type: bool
67 default: False
68 bucket_cors:
69 description: Retrieve S3 bucket CORS configuration.
70 type: bool
71 default: False
72 bucket_notification_configuration:
73 description: Retrieve S3 bucket notification configuration.
74 type: bool
75 default: False
76 bucket_encryption:
77 description: Retrieve S3 bucket encryption.
78 type: bool
79 default: False
80 bucket_ownership_controls:
81 description:
82 - Retrieve S3 ownership controls.
83 type: bool
84 default: False
85 bucket_website:
86 description: Retrieve S3 bucket website.
87 type: bool
88 default: False
89 bucket_policy:
90 description: Retrieve S3 bucket policy.
91 type: bool
92 default: False
93 bucket_policy_status:
94 description: Retrieve S3 bucket policy status.
95 type: bool
96 default: False
97 bucket_lifecycle_configuration:
98 description: Retrieve S3 bucket lifecycle configuration.
99 type: bool
100 default: False
101 public_access_block:
102 description: Retrieve S3 bucket public access block.
103 type: bool
104 default: False
105 bucket_versioning:
106 description:
107 - Retrieve the versioning state of a bucket.
108 - To retrieve the versioning state of a bucket, you must be the bucket owner.
109 type: bool
110 default: False
111 version_added: 7.3.0
112 type: dict
113 version_added: 1.4.0
114 transform_location:
115 description:
116 - S3 bucket location for default us-east-1 is normally reported as C(null).
117 - Setting this option to V(true) will return V(us-east-1) instead.
118 - Affects only queries with O(bucket_facts=true) and O(bucket_facts.bucket_location=true).
119 type: bool
120 default: False
121 version_added: 1.4.0
122 extends_documentation_fragment:
123 - amazon.aws.common.modules
124 - amazon.aws.region.modules
125 - amazon.aws.boto3
126 """
127
128 EXAMPLES = r"""
129 # Note: These examples do not set authentication details, see the AWS Guide for details.
130
131 # Note: Only AWS S3 is currently supported
132
133 # Lists all S3 buckets
134 - amazon.aws.s3_bucket_info:
135 register: result
136
137 # Retrieve detailed bucket information
138 - amazon.aws.s3_bucket_info:
139 # Show only buckets with name matching
140 name_filter: your.testing
141 # Choose facts to retrieve
142 bucket_facts:
143 # bucket_accelerate_configuration: true
144 bucket_acl: true
145 bucket_cors: true
146 bucket_encryption: true
147 # bucket_lifecycle_configuration: true
148 bucket_location: true
149 # bucket_logging: true
150 # bucket_notification_configuration: true
151 # bucket_ownership_controls: true
152 # bucket_policy: true
153 # bucket_policy_status: true
154 # bucket_replication: true
155 # bucket_request_payment: true
156 # bucket_tagging: true
157 # bucket_website: true
158 # public_access_block: true
159 transform_location: true
160 register: result
161
162 # Print out result
163 - name: List buckets
164 ansible.builtin.debug:
165 msg: "{{ result['buckets'] }}"
166 """
167
168 RETURN = r"""
169 buckets:
170 description: A list of S3 buckets.
171 returned: always
172 type: complex
173 contains:
174 bucket_accelerate_configuration:
175 description: The accelerate configuration of the bucket.
176 returned: when O(bucket_facts=true) and RV(buckets.bucket_accelerate_configuration=true).
177 type: dict
178 sample: {
179 'Status': 'Enabled',
180 'RequestCharged': 'requester'
181 }
182 name:
183 description: Bucket name.
184 returned: always
185 type: str
186 sample: "a-testing-bucket-name"
187 creation_date:
188 description: Bucket creation date timestamp.
189 returned: always
190 type: str
191 sample: "2021-01-21T12:44:10+00:00"
192 public_access_block:
193 description: Bucket public access block configuration.
194 returned: when O(bucket_facts=true) and RV(buckets.public_access_block=true).
195 type: dict
196 sample: {
197 "PublicAccessBlockConfiguration": {
198 "BlockPublicAcls": true,
199 "BlockPublicPolicy": true,
200 "IgnorePublicAcls": true,
201 "RestrictPublicBuckets": true
202 }
203 }
204 contains:
205 PublicAccessBlockConfiguration:
206 description: PublicAccessBlockConfiguration data.
207 returned: when PublicAccessBlockConfiguration is defined for the bucket
208 type: complex
209 contains:
210 BlockPublicAcls:
211 description: BlockPublicAcls setting value.
212 type: bool
213 BlockPublicPolicy:
214 description: BlockPublicPolicy setting value.
215 type: bool
216 IgnorePublicAcls:
217 description: IgnorePublicAcls setting value.
218 type: bool
219 RestrictPublicBuckets:
220 description: RestrictPublicBuckets setting value.
221 type: bool
222 bucket_name_filter:
223 description: String used to limit buckets. See I(name_filter).
224 returned: when O(name_filter) is defined
225 type: str
226 sample: "filter-by-this-string"
227 bucket_acl:
228 description: Bucket ACL configuration.
229 returned: when O(bucket_facts=true) and RV(buckets.bucket_acl=true).
230 type: complex
231 contains:
232 Grants:
233 description: List of ACL grants.
234 type: list
235 elements: dict
236 sample: [
237 {
238 "Grantee": {
239 "DisplayName": "abc-aws-root+721234567890",
240 "ID": "1234567890cbc0f1234567890f1234567890c123456789012123456789091234",
241 "Type": "CanonicalUser"
242 },
243 "Permission": "FULL_CONTROL"
244 }
245 ]
246 contains:
247 Grantee:
248 description: The person being granted permissions.
249 type: dict
250 contains:
251 DisplayName:
252 description: Screen name of the grantee.
253 type: str
254 ID:
255 description: The canonical user ID of the grantee.
256 type: str
257 Type:
258 description: Type of grantee.
259 type: str
260 Permission:
261 description: Specifies the permission given to the grantee.
262 type: str
263 Owner:
264 description: Bucket owner information.
265 type: dict
266 sample: {
267 "DisplayName": "abc-aws-root+721234567890",
268 "ID": "1234567890cbc0f1234567890f1234567890c123456789012123456789091234"
269 }
270 contains:
271 DisplayName:
272 description: Bucket owner user display name.
273 type: str
274 ID:
275 description: Bucket owner user ID.
276 type: str
277 bucket_cors:
278 description: Bucket CORS configuration.
279 returned: when O(bucket_facts=true) and RV(buckets.bucket_cors=true)
280 type: complex
281 contains:
282 CORSRules:
283 description: Bucket CORS configuration.
284 returned: When CORS rules are defined for the bucket
285 type: list
286 sample: []
287 bucket_encryption:
288 description: Bucket encryption configuration.
289 returned: when O(bucket_facts=true) and RV(buckets.bucket_encryption=true).
290 type: complex
291 sample: {
292 "ServerSideEncryptionConfiguration": {
293 "Rules": [
294 {
295 "ApplyServerSideEncryptionByDefault": {
296 "SSEAlgorithm": "AES256"
297 },
298 "BucketKeyEnabled": true
299 }
300 ]
301 }
302 }
303 contains:
304 ServerSideEncryptionConfiguration:
305 description: ServerSideEncryptionConfiguration configuration.
306 returned: when encryption is enabled on the bucket.
307 type: complex
308 contains:
309 Rules:
310 description: List of applied encryptio rules.
311 returned: when encryption is enabled on the bucket.
312 type: list
313 elements: dict
314 contains:
315 ApplyServerSideEncryptionByDefault:
316 description: Specifies the default server-side encryption to apply to new objects in the bucket.
317 type: dict
318 contains:
319 SSEAlgorithm:
320 description: Server-side encryption algorithm to use for the default encryption.
321 type: str
322 KMSMasterKeyID:
323 description: Amazon Web Services Key Management Service (KMS) customer Amazon Web Services KMS key ID to use for the default encryption.
324 type: str
325 BucketKeyEnabled:
326 description:
327 - Specifies whether Amazon S3 should use an S3 Bucket Key with server-side encryption using KMS (SSE-KMS) for new objects in the bucket.
328 type: bool
329 bucket_lifecycle_configuration:
330 description: Bucket lifecycle configuration settings.
331 returned: when O(bucket_facts=true) and RV(buckets.bucket_lifecycle_configuration=true).
332 type: list
333 elements: dict
334 contains:
335 Rules:
336 description: List of lifecycle management rules.
337 returned: when lifecycle configuration is present.
338 type: list
339 sample: [
340 {
341 "Status": "Enabled",
342 "ID": "example-rule"
343 }
344 ]
345 bucket_location:
346 description: Bucket location.
347 returned: when O(bucket_facts=true) and RV(buckets.bucket_location=true).
348 type: dict
349 sample: {
350 "LocationConstraint": "us-east-1"
351 }
352 contains:
353 LocationConstraint:
354 description: AWS region.
355 returned: always
356 type: str
357 bucket_logging:
358 description: Server access logging configuration.
359 returned: when O(bucket_facts=true) and RV(buckets.bucket_logging=true).
360 type: complex
361 contains:
362 LoggingEnabled:
363 description: Server access logging configuration.
364 returned: when server access logging is defined for the bucket.
365 type: complex
366 contains:
367 TargetBucket:
368 description: Target bucket name.
369 returned: always
370 type: str
371 sample: "logging-bucket-name"
372 TargetPrefix:
373 description: Prefix in target bucket.
374 returned: always
375 type: str
376 sample: ""
377 bucket_notification_configuration:
378 description: Bucket notification settings.
379 returned: when O(bucket_facts=true) and RV(buckets.bucket_notification_configuration=true).
380 type: complex
381 contains:
382 TopicConfigurations:
383 description: List of notification events configurations.
384 returned: when at least one notification is configured.
385 type: list
386 sample: [
387 {
388 'Id': 'topic-config-dev001',
389 'TopicArn': 'arn:aws:sns:us-west-1:721234567890:sns-dev001-topic',
390 'Events': [
391 "s3:ObjectCreated:Copy"
392 ],
393 'Filter': {
394 'Key': {
395 'FilterRules': [
396 {
397 "Name": "Prefix",
398 "Value": "test/"
399 },
400 ]
401 }
402 }
403 },
404 ]
405 bucket_ownership_controls:
406 description: Preffered object ownership settings.
407 returned: when O(bucket_facts=true) and RV(buckets.bucket_ownership_controls=true)
408 type: complex
409 sample: {
410 "OwnershipControls": {
411 "Rules": [
412 {
413 "ObjectOwnership": "BucketOwnerEnforced"
414 }
415 ]
416 }
417 }
418 contains:
419 OwnershipControls:
420 description: Object ownership settings.
421 returned: when ownership controls are defined for the bucket.
422 type: complex
423 contains:
424 Rules:
425 description: List of ownership rules.
426 returned: when ownership rule is defined.
427 type: list
428 bucket_policy:
429 description: Bucket policy contents.
430 returned: when O(bucket_facts=true) and RV(buckets.bucket_policy=true).
431 type: str
432 sample: '{"Version":"2012-10-17","Statement":[{"Sid":"AddCannedAcl","Effect":"Allow",..}}]}'
433 bucket_policy_status:
434 description: Status of bucket policy.
435 returned: when O(bucket_facts=true) and RV(buckets.bucket_policy_status=true).
436 type: dict
437 contains:
438 PolicyStatus:
439 description: Status of bucket policy.
440 returned: when bucket policy is present.
441 type: dict
442 contains:
443 IsPublic:
444 description: Report bucket policy public status.
445 returned: when bucket policy is present.
446 type: bool
447 sample: True
448 bucket_replication:
449 description: Replication configuration settings.
450 returned: when O(bucket_facts=true) and RV(buckets.bucket_replication=true).
451 type: complex
452 contains:
453 Role:
454 description: IAM role used for replication.
455 returned: when replication rule is defined.
456 type: str
457 sample: "arn:aws:iam::123:role/example-role"
458 Rules:
459 description: List of replication rules.
460 returned: when replication rule is defined.
461 type: list
462 sample: [{ "ID": "rule-1", "Filter": "{}" }]
463 bucket_request_payment:
464 description: Requester pays setting.
465 returned: when O(bucket_facts=true) and RV(buckets.bucket_request_payment=true)
466 type: complex
467 sample: {
468 "Payer": "BucketOwner"
469 }
470 contains:
471 Payer:
472 description: Current payer.
473 returned: always
474 type: str
475 bucket_tagging:
476 description: Bucket tags.
477 returned: when O(bucket_facts=true) and RV(buckets.bucket_tagging=true).
478 type: dict
479 sample: { "Tag1": "Value1", "Tag2": "Value2" }
480 bucket_website:
481 description: Static website hosting.
482 returned: when O(bucket_facts=true) and RV(buckets.bucket_website=true).
483 type: complex
484 contains:
485 ErrorDocument:
486 description: Object serving as HTTP error page.
487 returned: when static website hosting is enabled.
488 type: dict
489 sample: { "Key": "error.html" }
490 IndexDocument:
491 description: Object serving as HTTP index page.
492 returned: when static website hosting is enabled.
493 type: dict
494 sample: { "Suffix": "error.html" }
495 RedirectAllRequestsTo:
496 description: Website redict settings.
497 returned: when redirect requests is configured.
498 type: complex
499 contains:
500 HostName:
501 description: Hostname to redirect.
502 returned: always
503 type: str
504 sample: "www.example.com"
505 Protocol:
506 description: Protocol used for redirect.
507 returned: always
508 type: str
509 sample: "https"
510 bucket_versioning:
511 description:
512 - The versioning state of the bucket.
513 - This will also specify whether MFA delete is enabled in the bucket versioning configuration.
514 if only the bucket has been configured with MFA delete.
515 returned: when O(bucket_facts=true) and RV(buckets.bucket_versioning=true).
516 type: dict
517 sample: { "Status": "Enabled" }
518 version_added: 7.2.0
519 """
520
521 import typing
522
523 if typing.TYPE_CHECKING:
524 from typing import Dict
525 from typing import List
526
527 from ansible_collections.amazon.aws.plugins.module_utils.botocore import ClientType
528
529 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
530
531 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
532 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
533 from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3Error
534 from ansible_collections.amazon.aws.plugins.module_utils.s3 import S3ErrorHandler
535 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_bucket_location
536 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_accelerate_configuration
537 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_acl
538 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_encryption
539 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_ownership_controls
540 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_policy
541 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_public_access_block
542 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_request_payment
543 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_tagging
544 from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_versioning
545 from ansible_collections.amazon.aws.plugins.module_utils.s3 import list_s3_buckets
546
547
548 def get_bucket_list(
549 module: AnsibleAWSModule,
550 connection: ClientType,
551 name: str = "",
552 name_filter: str = "",
553 ) -> List[Dict]:
554 """
555 Return result of list_buckets json encoded
556 Filter only buckets matching 'name' or name_filter if defined
557 :param module:
558 :param connection:
559 :return:
560 """
561 buckets = []
562 filtered_buckets = []
563 final_buckets = []
564
565 # Get all buckets
566 # camel_dict_to_snake_dict doesn't support being passed a list,
567 # so we wrap the bucket list in a dictionary temporarily
568 buckets = camel_dict_to_snake_dict({"Buckets": list_s3_buckets(connection)})["buckets"]
569
570 # Filter buckets if requested
571 if name_filter:
572 for bucket in buckets:
573 if name_filter in bucket["name"]:
574 filtered_buckets.append(bucket)
575 elif name:
576 for bucket in buckets:
577 if name == bucket["name"]:
578 filtered_buckets.append(bucket)
579
580 # Return proper list (filtered or all)
581 if name or name_filter:
582 final_buckets = filtered_buckets
583 else:
584 final_buckets = buckets
585 return final_buckets
586
587
588 def get_buckets_facts(
589 connection: ClientType, buckets: List[Dict], requested_facts: Dict, transform_location: bool
590 ) -> List[Dict]:
591 """
592 Retrieve additional information about S3 buckets
593 """
594 full_bucket_list = []
595 # Iterate over all buckets and append Retrieved facts to bucket
596 for bucket in buckets:
597 bucket.update(get_bucket_details(connection, bucket["name"], requested_facts, transform_location))
598 full_bucket_list.append(bucket)
599
600 return full_bucket_list
601
602
603 def get_bucket_details(connection: ClientType, name: str, requested_facts: Dict, transform_location: bool) -> Dict:
604 """
605 Execute all enabled S3API get calls for selected bucket using module_utils functions.
606 """
607 # Map bucket_facts keys to module_utils functions
608 bucket_function_map = {
609 "bucket_accelerate_configuration": get_s3_bucket_accelerate_configuration,
610 "bucket_acl": get_s3_bucket_acl,
611 "bucket_encryption": get_s3_bucket_encryption,
612 "bucket_ownership_controls": get_s3_bucket_ownership_controls,
613 "bucket_policy": get_s3_bucket_policy,
614 "public_access_block": get_s3_bucket_public_access_block,
615 "bucket_request_payment": get_s3_bucket_request_payment,
616 "bucket_tagging": get_s3_bucket_tagging,
617 "bucket_versioning": get_s3_bucket_versioning,
618 }
619
620 all_facts = {}
621
622 for key in requested_facts:
623 if not requested_facts[key]:
624 continue
625
626 all_facts[key] = {}
627 try:
628 if key == "bucket_location":
629 # Special handling for bucket_location with transform_location parameter
630 location_data = get_bucket_location(connection, name)
631 # Transform 'None' LocationConstraint to 'us-east-1' if requested
632 if transform_location and location_data.get("LocationConstraint") is None:
633 location_data["LocationConstraint"] = "us-east-1"
634 all_facts[key] = location_data
635 elif key in bucket_function_map:
636 # Use module_utils function
637 all_facts[key] = bucket_function_map[key](connection, name)
638 else:
639 # For properties not in module_utils, use dynamic call
640 all_facts[key] = get_bucket_property(name, connection, key)
641 except AnsibleS3Error:
642 # Silent failure for missing/inaccessible bucket properties (backward compatibility)
643 pass
644
645 return all_facts
646
647
648 @S3ErrorHandler.list_error_handler("get bucket property", {})
649 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
650 def get_bucket_property(name: str, connection: ClientType, get_api_name: str) -> Dict:
651 """
652 Get bucket property
653 """
654 api_call = "get_" + get_api_name
655 api_function = getattr(connection, api_call)
656 data = api_function(Bucket=name)
657
658 # Strip response metadata (not needed)
659 data.pop("ResponseMetadata", None)
660 return data
661
662
663 def main() -> None:
664 """
665 Get list of S3 buckets
666 :return:
667 """
668 argument_spec = dict(
669 name=dict(type="str", default=""),
670 name_filter=dict(type="str", default=""),
671 bucket_facts=dict(
672 type="dict",
673 options=dict(
674 bucket_accelerate_configuration=dict(type="bool", default=False),
675 bucket_acl=dict(type="bool", default=False),
676 bucket_cors=dict(type="bool", default=False),
677 bucket_encryption=dict(type="bool", default=False),
678 bucket_lifecycle_configuration=dict(type="bool", default=False),
679 bucket_location=dict(type="bool", default=False),
680 bucket_logging=dict(type="bool", default=False),
681 bucket_notification_configuration=dict(type="bool", default=False),
682 bucket_ownership_controls=dict(type="bool", default=False),
683 bucket_policy=dict(type="bool", default=False),
684 bucket_policy_status=dict(type="bool", default=False),
685 bucket_replication=dict(type="bool", default=False),
686 bucket_request_payment=dict(type="bool", default=False),
687 bucket_tagging=dict(type="bool", default=False),
688 bucket_website=dict(type="bool", default=False),
689 public_access_block=dict(type="bool", default=False),
690 bucket_versioning=dict(type="bool", default=False),
691 ),
692 ),
693 transform_location=dict(type="bool", default=False),
694 )
695
696 # Ensure we have an empty dict
697 result = {}
698
699 # Define mutually exclusive options
700 mutually_exclusive = [
701 ["name", "name_filter"],
702 ]
703
704 # Including ec2 argument spec
705 module = AnsibleAWSModule(
706 argument_spec=argument_spec,
707 supports_check_mode=True,
708 mutually_exclusive=mutually_exclusive,
709 )
710
711 # Get parameters
712 name = module.params.get("name")
713 name_filter = module.params.get("name_filter")
714 requested_facts = module.params.get("bucket_facts")
715 transform_location = module.params.get("transform_location")
716
717 # Set up connection
718 connection = module.client("s3")
719
720 # Get basic bucket list (name + creation date)
721 bucket_list = get_bucket_list(module, connection, name, name_filter)
722
723 # Add information about name/name_filter to result
724 if name:
725 result["bucket_name"] = name
726 elif name_filter:
727 result["bucket_name_filter"] = name_filter
728
729 # Gather detailed information about buckets if requested
730 bucket_facts = module.params.get("bucket_facts")
731 if bucket_facts:
732 result["buckets"] = get_buckets_facts(connection, bucket_list, requested_facts, transform_location)
733 else:
734 result["buckets"] = bucket_list
735
736 module.exit_json(msg="Retrieved s3 info.", **result)
737
738
739 # MAIN
740 if __name__ == "__main__":
741 main()