Debian Codegraph @

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

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2018 Red Hat, Inc.
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8 import json
9 import string
10 import typing
11
12 if typing.TYPE_CHECKING:
13 from typing import Any
14 from typing import Dict
15 from typing import Generator
16 from typing import List
17 from typing import Optional
18 from typing import Tuple
19
20 from .botocore import ClientType
21 from .modules import AnsibleAWSModule
22
23 from urllib.parse import urlparse
24
25 try:
26 from hashlib import md5
27
28 HAS_MD5 = True
29 except ImportError:
30 HAS_MD5 = False
31
32 try:
33 import botocore
34 except ImportError:
35 pass # Handled by the calling module
36
37
38 from ansible.module_utils.basic import to_text
39
40 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
41 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
42 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
43 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
44
45 IGNORE_S3_DROP_IN_EXCEPTIONS = ["XNotImplemented", "NotImplemented", "AccessControlListNotSupported"]
46
47 from ._s3 import common as _common
48 from ._s3 import transformations as _transformations
49 from ._s3 import waiters as _waiters
50
51 S3ErrorHandler = _common.S3ErrorHandler
52
53 AnsibleS3Error = _common.AnsibleS3Error
54 AnsibleS3Sigv4RequiredError = _common.AnsibleS3Error
55 AnsibleS3PermissionsError = _common.AnsibleS3PermissionsError
56 AnsibleS3SupportError = _common.AnsibleS3SupportError
57 AnsibleS3ACLSupportError = _common.AnsibleS3ACLSupportError
58 AnsibleS3RegionSupportError = _common.AnsibleS3RegionSupportError
59
60 normalize_s3_bucket_versioning = _transformations.normalize_s3_bucket_versioning
61 normalize_s3_bucket_public_access = _transformations.normalize_s3_bucket_public_access
62 normalize_s3_bucket_acls = _transformations.normalize_s3_bucket_acls
63 normalize_s3_bucket_logging = _transformations.normalize_s3_bucket_logging
64 s3_acl_to_name = _transformations.s3_acl_to_name
65 merge_tags = _transformations.merge_tags
66
67
68 # ========================================
69 # S3 Client Wrappers - Bucket Operations
70 # ========================================
71
72
73 def get_s3_waiter(client: ClientType, waiter_name: str) -> Any:
74 return _waiters.waiter_factory.get_waiter(client, waiter_name)
75
76
77 @S3ErrorHandler.list_error_handler("get bucket accelerate configuration", {})
78 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
79 def get_s3_bucket_accelerate_configuration(client: ClientType, bucket_name: str) -> Dict:
80 """
81 Get transfer accelerate configuration of the S3 bucket.
82 Parameters:
83 client (boto3.client): The Boto3 S3 client object.
84 bucket_name (str): The name of the S3 bucket.
85 Returns:
86 Transfer accelerate status of the S3 bucket.
87 """
88 try:
89 return client.get_bucket_accelerate_configuration(Bucket=bucket_name)
90 except is_boto3_error_code(["UnsupportedArgument", "MethodNotAllowed"]) as e:
91 # aws-gov throws UnsupportedArgument (consistently)
92 # aws throws MethodNotAllowed where acceleration isn't available /yet/
93 raise AnsibleS3RegionSupportError(
94 message="Failed to get bucket accelerate configuration (not available in S3 bucket region)", exception=e
95 ) from e
96
97
98 @S3ErrorHandler.list_error_handler("get bucket ACLs", {})
99 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
100 def get_s3_bucket_acl(client: ClientType, bucket_name: str) -> Dict:
101 """
102 Get ACLs of the S3 bucket.
103 Parameters:
104 client (boto3.client): The Boto3 S3 client object.
105 bucket_name (str): The name of the S3 bucket.
106 Returns:
107 ACL configuration of the S3 bucket.
108 """
109 return client.get_bucket_acl(Bucket=bucket_name)
110
111
112 @S3ErrorHandler.list_error_handler("get bucket encryption settings", {})
113 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
114 def get_s3_bucket_encryption(client: ClientType, bucket_name: str) -> Dict:
115 """
116 Retrieve the encryption configuration for an S3 bucket.
117 Parameters:
118 client (boto3.client): The Boto3 S3 client object.
119 bucket_name (str): The name of the S3 bucket.
120 Returns:
121 Encryption configuration of the bucket.
122 """
123 return client.get_bucket_encryption(Bucket=bucket_name).get("ServerSideEncryptionConfiguration")
124
125
126 @S3ErrorHandler.list_error_handler("get bucket ownership settings", {})
127 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
128 def get_s3_bucket_ownership_controls(client: ClientType, bucket_name: str) -> Dict:
129 """
130 Retrieve bucket ownership controls for S3 bucket
131 Parameters:
132 client (boto3.client): The Boto3 S3 client object.
133 bucket_name (str): The name of the S3 bucket.
134 Returns:
135 Bucket ownership controls of the bucket.
136 """
137 return client.get_bucket_ownership_controls(Bucket=bucket_name).get("OwnershipControls")
138
139
140 @S3ErrorHandler.list_error_handler("get bucket policy", {})
141 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
142 def get_s3_bucket_policy(client: ClientType, bucket_name: str) -> Dict:
143 """
144 Retrieve bucket policy for an S3 bucket
145 Parameters:
146 client (boto3.client): The Boto3 S3 client object.
147 bucket_name (str): The name of the S3 bucket.
148 Returns:
149 Bucket policy controls of the bucket.
150 """
151 policy = client.get_bucket_policy(Bucket=bucket_name).get("Policy")
152 try:
153 return json.loads(policy)
154 except ValueError as e:
155 raise AnsibleS3Error(exception=e, message="Unable to parse current bucket policy") from e
156
157
158 @S3ErrorHandler.list_error_handler("get bucket public access block settings", {})
159 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
160 def get_s3_bucket_public_access_block(client: ClientType, bucket_name: str) -> Dict:
161 """
162 Get current public access block configuration for a bucket.
163 Parameters:
164 client (boto3.client): The Boto3 S3 client object.
165 bucket_name (str): The name of the S3 bucket.
166 Returns:
167 The current public access block configuration for the bucket.
168 """
169 return client.get_public_access_block(Bucket=bucket_name).get("PublicAccessBlockConfiguration")
170
171
172 @S3ErrorHandler.list_error_handler("get bucket request payment settings", {})
173 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
174 def get_s3_bucket_request_payment(client: ClientType, bucket_name: str) -> Dict:
175 """
176 Retrieve bucket request payment settings for an S3 bucket
177 Parameters:
178 client (boto3.client): The Boto3 S3 client object.
179 bucket_name (str): The name of the S3 bucket.
180 Returns:
181 Request payment settings of the bucket.
182 """
183 return client.get_bucket_request_payment(Bucket=bucket_name).get("Payer")
184
185
186 @S3ErrorHandler.list_error_handler("get bucket tags", {})
187 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
188 def get_s3_bucket_tagging(client: ClientType, bucket_name: str) -> Dict:
189 """
190 Retrieve tagging for an S3 bucket
191 Parameters:
192 client (boto3.client): The Boto3 S3 client object.
193 bucket_name (str): The name of the S3 bucket.
194 Returns:
195 The current tags dictionary applied to the bucket.
196 """
197 current_tags = client.get_bucket_tagging(Bucket=bucket_name).get("TagSet")
198 return boto3_tag_list_to_ansible_dict(current_tags)
199
200
201 @S3ErrorHandler.list_error_handler("get bucket versioning settings", {})
202 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
203 def get_s3_bucket_versioning(client: ClientType, bucket_name: str) -> Dict:
204 """
205 Retrieve bucket versioning settings for an S3 bucket
206 Parameters:
207 client (boto3.client): The Boto3 S3 client object.
208 bucket_name (str): The name of the S3 bucket.
209 Returns:
210 Versioning settings of the bucket.
211 """
212 return client.get_bucket_versioning(Bucket=bucket_name)
213
214
215 @S3ErrorHandler.list_error_handler("get bucket logging configuration", {})
216 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
217 def get_s3_bucket_logging(client: ClientType, bucket_name: str) -> Dict:
218 """
219 Retrieve bucket logging configuration for an S3 bucket.
220 Parameters:
221 client (boto3.client): The Boto3 S3 client object.
222 bucket_name (str): The name of the S3 bucket.
223 Returns:
224 Logging configuration of the bucket.
225 """
226 return client.get_bucket_logging(Bucket=bucket_name)
227
228
229 @S3ErrorHandler.list_error_handler("get bucket object lock settings", {})
230 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
231 def get_s3_object_lock_configuration(client: ClientType, bucket_name: str) -> Dict:
232 """
233 Retrieve object lock configuration for an S3 bucket.
234 Parameters:
235 client (boto3.client): The Boto3 S3 client object.
236 bucket_name (str): The name of the S3 bucket.
237 Returns:
238 The object lock configuration of the bucket.
239 """
240 return client.get_object_lock_configuration(Bucket=bucket_name).get("ObjectLockConfiguration")
241
242
243 @S3ErrorHandler.list_error_handler("determine if bucket exists", {})
244 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["OperationAborted"])
245 def head_s3_bucket(client: ClientType, bucket_name: str) -> Dict:
246 """
247 Retrieve basic information about an S3 bucket
248 Parameters:
249 client (boto3.client): The Boto3 S3 client object.
250 bucket_name (str): The name of the S3 bucket.
251 Returns:
252 Basic information about the bucket.
253 """
254 return client.head_bucket(Bucket=bucket_name)
255
256
257 @S3ErrorHandler.list_error_handler("get bucket location", {})
258 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
259 def get_bucket_location(client: ClientType, bucket_name: str) -> Dict:
260 """
261 Retrieve the AWS region where an S3 bucket is located.
262
263 Parameters:
264 client (boto3.client): The Boto3 S3 client object.
265 bucket_name (str): The name of the S3 bucket.
266
267 Returns:
268 Dict: Bucket location information containing 'LocationConstraint'.
269 Returns {} if bucket doesn't exist (404).
270 Note: LocationConstraint is None for us-east-1 buckets.
271
272 Raises:
273 AnsibleS3PermissionsError: If access is denied (403).
274 AnsibleS3Error: For other S3 errors.
275 """
276 return client.get_bucket_location(Bucket=bucket_name)
277
278
279 @AWSRetry.jittered_backoff()
280 def s3_bucket_exists(client: ClientType, bucket_name: str) -> bool:
281 """
282 Check if an S3 bucket exists.
283
284 Parameters:
285 client (boto3.client): The Boto3 S3 client object.
286 bucket_name (str): The name of the S3 bucket.
287
288 Returns:
289 bool: True if bucket exists, False otherwise.
290
291 Raises:
292 AnsibleS3PermissionsError: If access is denied (403).
293 AnsibleS3Error: For other S3 errors.
294 """
295 result = head_s3_bucket(client, bucket_name)
296 return bool(result)
297
298
299 @S3ErrorHandler.list_error_handler("list buckets", [])
300 @AWSRetry.jittered_backoff()
301 def list_s3_buckets(client: ClientType) -> List[Dict]:
302 """
303 List all S3 buckets in the account.
304
305 Parameters:
306 client (boto3.client): The Boto3 S3 client object.
307
308 Returns:
309 List[Dict]: List of bucket information dictionaries containing 'Name' and 'CreationDate'.
310 Returns [] on error.
311
312 Raises:
313 AnsibleS3PermissionsError: If access is denied (403).
314 AnsibleS3Error: For other S3 errors.
315 """
316 return client.list_buckets().get("Buckets", [])
317
318
319 @S3ErrorHandler.list_error_handler("get bucket inventory settings", {})
320 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
321 def _list_bucket_inventory_configurations(client: ClientType, **params) -> Dict:
322 return client.list_bucket_inventory_configurations(**params)
323
324
325 # _list_bucket_inventory_configurations is a workaround for a missing paginator for listing
326 # bucket inventory configuration in boto3:
327 # https://github.com/boto/botocore/blob/1.34.141/botocore/data/s3/2006-03-01/paginators-1.json
328 def list_bucket_inventory_configurations(client: ClientType, bucket_name: str) -> list:
329 first_iteration_completed = False
330 next_token = None
331
332 response = _list_bucket_inventory_configurations(client, Bucket=bucket_name)
333 next_token = response.get("NextToken", None)
334
335 if next_token is None:
336 return response.get("InventoryConfigurationList", [])
337
338 entries = []
339 while next_token is not None:
340 if first_iteration_completed:
341 response = _list_bucket_inventory_configurations(client, NextToken=next_token, Bucket=bucket_name)
342 first_iteration_completed = True
343 entries.extend(response["InventoryConfigurationList"])
344 next_token = response.get("NextToken")
345 return entries
346
347
348 @S3ErrorHandler.common_error_handler("set object lock configuration")
349 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
350 def put_s3_object_lock_configuration(client: ClientType, bucket_name: str, object_lock_default_retention: str) -> None:
351 """
352 Set object lock configuration for an S3 bucket.
353 Parameters:
354 client (boto3.client): The Boto3 S3 client object.
355 bucket_name (str): The name of the S3 bucket.
356 object_lock_default_retention (dict): A dictionary containing the object
357 lock default retention configuration to be set on the bucket.
358 Returns:
359 None
360 """
361 conf = {"ObjectLockEnabled": "Enabled", "Rule": {"DefaultRetention": object_lock_default_retention}}
362 client.put_object_lock_configuration(Bucket=bucket_name, ObjectLockConfiguration=conf)
363
364
365 @S3ErrorHandler.common_error_handler("set bucket acceleration configuration")
366 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
367 def put_s3_bucket_accelerate_configuration(client: ClientType, bucket_name: str) -> None:
368 """
369 Enable transfer accelerate for the S3 bucket.
370 Parameters:
371 client (boto3.client): The Boto3 S3 client object.
372 bucket_name (str): The name of the S3 bucket.
373 Returns:
374 None
375 """
376 client.put_bucket_accelerate_configuration(Bucket=bucket_name, AccelerateConfiguration={"Status": "Enabled"})
377
378
379 @S3ErrorHandler.common_error_handler("set bucket inventory configuration")
380 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
381 def put_s3_bucket_inventory(client: ClientType, bucket_name: str, inventory: dict) -> None:
382 """
383 Set inventory settings for an S3 bucket.
384 Parameters:
385 client (boto3.client): The Boto3 S3 client object.
386 bucket_name (str): The name of the S3 bucket.
387 inventory (dict): A dictionary containing the inventory settings to be set on the bucket.
388 Returns:
389 None
390 """
391 try:
392 client.put_bucket_inventory_configuration(
393 Bucket=bucket_name, InventoryConfiguration=inventory, Id=inventory.get("Id")
394 )
395 except is_boto3_error_code("InvalidS3DestinationBucket") as e:
396 raise AnsibleS3Error("Invalid destination bucket ARN") from e
397
398
399 @S3ErrorHandler.common_error_handler("set bucket tagging")
400 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
401 def put_s3_bucket_tagging(client: ClientType, bucket_name: str, tags: dict) -> None:
402 """
403 Set tags for an S3 bucket.
404 Parameters:
405 client (boto3.client): The Boto3 S3 client object.
406 bucket_name (str): The name of the S3 bucket.
407 tags (dict): A dictionary containing the tags to be set on the bucket.
408 Returns:
409 None
410 """
411 client.put_bucket_tagging(Bucket=bucket_name, Tagging={"TagSet": ansible_dict_to_boto3_tag_list(tags)})
412
413
414 @S3ErrorHandler.common_error_handler("set bucket policy")
415 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
416 def put_s3_bucket_policy(client: ClientType, bucket_name: str, policy: dict) -> None:
417 """
418 Set the policy for an S3 bucket.
419 Parameters:
420 client (boto3.client): The Boto3 S3 client object.
421 bucket_name (str): The name of the S3 bucket.
422 policy (dict): A dictionary containing the policy to be set on the bucket.
423 Returns:
424 None
425 """
426 client.put_bucket_policy(Bucket=bucket_name, Policy=json.dumps(policy))
427
428
429 @S3ErrorHandler.common_error_handler("set bucket request payment configuration")
430 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
431 def put_s3_bucket_request_payment(client: ClientType, bucket_name: str, payer: str) -> None:
432 """
433 Set the request payment configuration for an S3 bucket.
434 Parameters:
435 client (boto3.client): The Boto3 S3 client object.
436 bucket_name (str): The name of the S3 bucket.
437 payer (str): The entity responsible for charges related to fulfilling the request.
438 Returns:
439 None
440 """
441 client.put_bucket_request_payment(Bucket=bucket_name, RequestPaymentConfiguration={"Payer": payer})
442
443
444 @S3ErrorHandler.common_error_handler("set bucket versioning configuration")
445 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
446 def put_s3_bucket_versioning(client: ClientType, bucket_name: str, required_versioning: str) -> None:
447 """
448 Set the versioning configuration for an S3 bucket.
449 Parameters:
450 client (boto3.client): The Boto3 S3 client object.
451 bucket_name (str): The name of the S3 bucket.
452 required_versioning (str): The desired versioning state for the bucket ("Enabled", "Suspended").
453 Returns:
454 None
455 """
456 client.put_bucket_versioning(Bucket=bucket_name, VersioningConfiguration={"Status": required_versioning})
457
458
459 @S3ErrorHandler.common_error_handler("set bucket logging configuration")
460 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
461 def put_s3_bucket_logging(client: ClientType, bucket_name: str, logging_config: dict) -> None:
462 """
463 Set the logging configuration for an S3 bucket.
464 Parameters:
465 client (boto3.client): The Boto3 S3 client object.
466 bucket_name (str): The name of the S3 bucket.
467 logging_config (dict): The logging configuration to set.
468 Returns:
469 None
470 """
471 client.put_bucket_logging(Bucket=bucket_name, BucketLoggingStatus=logging_config)
472
473
474 @S3ErrorHandler.common_error_handler("set bucket encryption")
475 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
476 def put_s3_bucket_encryption(client: ClientType, bucket_name: str, encryption: dict) -> None:
477 """
478 Set the encryption configuration for an S3 bucket.
479 Parameters:
480 client (boto3.client): The Boto3 S3 client object.
481 bucket_name (str): The name of the S3 bucket.
482 encryption (dict): A dictionary containing the encryption configuration.
483 Returns:
484 None
485 """
486 server_side_encryption_configuration = {"Rules": [{"ApplyServerSideEncryptionByDefault": encryption}]}
487 client.put_bucket_encryption(
488 Bucket=bucket_name, ServerSideEncryptionConfiguration=server_side_encryption_configuration
489 )
490
491
492 @S3ErrorHandler.common_error_handler("set public access block configuration")
493 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
494 def put_s3_bucket_public_access(client: ClientType, bucket_name: str, public_access_config: dict) -> None:
495 """
496 Put new public access block to S3 bucket
497 Parameters:
498 client (boto3.client): The Boto3 S3 client object.
499 bucket_name (str): The name of the S3 bucket.
500 public_access_config (dict): The public access block configuration.
501 Returns:
502 None
503 """
504 client.put_public_access_block(Bucket=bucket_name, PublicAccessBlockConfiguration=public_access_config)
505
506
507 @S3ErrorHandler.common_error_handler("set bucket ACL")
508 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
509 def put_s3_bucket_acl(client: ClientType, bucket_name: str, acl: str) -> None:
510 """
511 Applies a canned ACL to an S3 bucket
512 Parameters:
513 client (boto3.client): The Boto3 S3 client object.
514 bucket_name (str): The name of the S3 bucket.
515 acl (str): The ACL
516 Returns:
517 None
518 """
519 client.put_bucket_acl(Bucket=bucket_name, ACL=acl)
520
521
522 @S3ErrorHandler.common_error_handler("set bucket ownership controls")
523 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
524 def put_s3_bucket_ownership(client: ClientType, bucket_name: str, object_ownership: str) -> None:
525 """
526 Put bucket ownership controls for S3 bucket
527 Parameters:
528 client (boto3.client): The Boto3 S3 client object.
529 bucket_name (str): The name of the S3 bucket.
530 object_ownership (str): The object ownership control setting.
531 Returns:
532 None
533 """
534 client.put_bucket_ownership_controls(
535 Bucket=bucket_name, OwnershipControls={"Rules": [{"ObjectOwnership": object_ownership}]}
536 )
537
538
539 @S3ErrorHandler.deletion_error_handler("set bucket acceleration configuration")
540 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
541 def delete_s3_bucket_accelerate_configuration(client: ClientType, bucket_name: str) -> None:
542 """
543 Disable transfer accelerate for the S3 bucket.
544 Parameters:
545 client (boto3.client): The Boto3 S3 client object.
546 bucket_name (str): The name of the S3 bucket.
547 Returns:
548 None
549 """
550 client.put_bucket_accelerate_configuration(Bucket=bucket_name, AccelerateConfiguration={"Status": "Suspended"})
551
552
553 @S3ErrorHandler.deletion_error_handler("delete bucket inventory configuration")
554 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
555 def delete_s3_bucket_inventory(client: ClientType, bucket_name: str, inventory_id: str) -> None:
556 """
557 Delete the inventory settings for an S3 bucket.
558 Parameters:
559 client (boto3.client): The Boto3 S3 client object.
560 bucket_name (str): The name of the S3 bucket.
561 inventory_id (str): The ID used to identify the inventory configuration
562 Returns:
563 None
564 """
565 client.delete_bucket_inventory_configuration(Bucket=bucket_name, Id=inventory_id)
566
567
568 @S3ErrorHandler.deletion_error_handler("delete bucket tagging")
569 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
570 def delete_s3_bucket_tagging(client: ClientType, bucket_name: str) -> None:
571 """
572 Delete the tagging configuration of an S3 bucket.
573 Parameters:
574 client (boto3.client): The Boto3 S3 client object.
575 bucket_name (str): The name of the S3 bucket.
576 Returns:
577 None
578 """
579 client.delete_bucket_tagging(Bucket=bucket_name)
580
581
582 @S3ErrorHandler.deletion_error_handler("delete bucket encryption")
583 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
584 def delete_s3_bucket_encryption(client: ClientType, bucket_name: str) -> None:
585 """
586 Delete the encryption configuration of an S3 bucket.
587 Parameters:
588 client (boto3.client): The Boto3 S3 client object.
589 bucket_name (str): The name of the S3 bucket.
590 Returns:
591 None
592 """
593 client.delete_bucket_encryption(Bucket=bucket_name)
594
595
596 @S3ErrorHandler.deletion_error_handler("delete bucket")
597 @AWSRetry.jittered_backoff(max_delay=240, catch_extra_error_codes=["OperationAborted"])
598 def delete_s3_bucket(client: ClientType, bucket_name: str) -> None:
599 """
600 Delete an S3 bucket.
601 Parameters:
602 client (boto3.client): The Boto3 S3 client object.
603 bucket_name (str): The name of the S3 bucket.
604 Returns:
605 None
606 """
607 client.delete_bucket(Bucket=bucket_name)
608
609
610 @S3ErrorHandler.deletion_error_handler("delete bucket policy")
611 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
612 def delete_s3_bucket_policy(client: ClientType, bucket_name: str) -> None:
613 """
614 Delete policy from S3 bucket
615 Parameters:
616 client (boto3.client): The Boto3 S3 client object.
617 bucket_name (str): The name of the S3 bucket.
618 Returns:
619 None
620 """
621 client.delete_bucket_policy(Bucket=bucket_name)
622
623
624 @S3ErrorHandler.deletion_error_handler("delete public access block configuration")
625 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
626 def delete_s3_bucket_public_access(client: ClientType, bucket_name: str) -> None:
627 """
628 Delete public access block from S3 bucket
629 Parameters:
630 client (boto3.client): The Boto3 S3 client object.
631 bucket_name (str): The name of the S3 bucket.
632 Returns:
633 None
634 """
635 client.delete_public_access_block(Bucket=bucket_name)
636
637
638 @S3ErrorHandler.deletion_error_handler("delete bucket ownership controls")
639 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
640 def delete_s3_bucket_ownership(client: ClientType, bucket_name: str) -> None:
641 """
642 Delete bucket ownership controls from S3 bucket
643 Parameters:
644 client (boto3.client): The Boto3 S3 client object.
645 bucket_name (str): The name of the S3 bucket.
646 Returns:
647 None
648 """
649 client.delete_bucket_ownership_controls(Bucket=bucket_name)
650
651
652 # ========================================
653 # S3 Client Wrappers - Object Operations
654 # ========================================
655
656
657 @S3ErrorHandler.list_error_handler("get object metadata", {})
658 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
659 def head_s3_object(
660 client: ClientType, bucket_name: str, object_key: str, version_id: Optional[str] = None, **kwargs
661 ) -> Dict:
662 """
663 Retrieve metadata about an S3 object without downloading the object itself.
664
665 Parameters:
666 client (boto3.client): The Boto3 S3 client object.
667 bucket_name (str): The name of the S3 bucket.
668 object_key (str): The key of the S3 object.
669 version_id (str, optional): The version ID of the object.
670 **kwargs: Additional parameters to pass to head_object (e.g., ExpectedBucketOwner).
671
672 Returns:
673 Dict: Object metadata including ETag, ContentLength, LastModified, etc.
674 Returns {} if object does not exist (404).
675 """
676 params = {"Bucket": bucket_name, "Key": object_key}
677 if version_id:
678 params["VersionId"] = version_id
679 params.update(kwargs)
680 return client.head_object(**params)
681
682
683 @AWSRetry.jittered_backoff()
684 def s3_head_objects(
685 client: ClientType, parts: int, bucket: str, obj: str, versionId: Optional[str]
686 ) -> Generator[Dict, None, None]:
687 """
688 Generator that yields HEAD object responses for each part of a multipart upload.
689
690 Parameters:
691 client (boto3.client): The Boto3 S3 client object.
692 parts (int): Number of parts in the multipart upload.
693 bucket (str): The S3 bucket name.
694 obj (str): The S3 object key.
695 versionId (str): Optional version ID of the object.
696
697 Yields:
698 HEAD object response dict for each part.
699 """
700 args = {"Bucket": bucket, "Key": obj}
701 if versionId:
702 args["VersionId"] = versionId
703
704 for part in range(1, parts + 1):
705 args["PartNumber"] = part
706 yield client.head_object(**args)
707
708
709 @S3ErrorHandler.list_error_handler("get object content", None)
710 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
711 def get_s3_object_content(
712 client: ClientType, bucket_name: str, object_key: str, version_id: Optional[str] = None, **kwargs
713 ) -> Optional[bytes]:
714 """
715 Download the content of an S3 object.
716
717 Parameters:
718 client (boto3.client): The Boto3 S3 client object.
719 bucket_name (str): The name of the S3 bucket.
720 object_key (str): The key of the S3 object.
721 version_id (str, optional): The version ID of the object.
722 **kwargs: Additional parameters to pass to get_object.
723
724 Returns:
725 bytes: The object content, or None if object does not exist (404).
726 """
727 params = {"Bucket": bucket_name, "Key": object_key}
728 if version_id:
729 params["VersionId"] = version_id
730 params.update(kwargs)
731 response = client.get_object(**params)
732 return response["Body"].read()
733
734
735 @S3ErrorHandler.list_error_handler("get object tags", {})
736 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
737 def get_s3_object_tagging(
738 client: ClientType, bucket_name: str, object_key: str, version_id: Optional[str] = None, **kwargs
739 ) -> Dict:
740 """
741 Retrieve tags for an S3 object.
742
743 Parameters:
744 client (boto3.client): The Boto3 S3 client object.
745 bucket_name (str): The name of the S3 bucket.
746 object_key (str): The key of the S3 object.
747 version_id (str, optional): The version ID of the object.
748 **kwargs: Additional parameters to pass to get_object_tagging (e.g., ExpectedBucketOwner).
749
750 Returns:
751 Dict: The current tags dictionary applied to the object.
752 Returns {} if object has no tags or does not exist.
753 """
754 params = {"Bucket": bucket_name, "Key": object_key}
755 if version_id:
756 params["VersionId"] = version_id
757 params.update(kwargs)
758 current_tags = client.get_object_tagging(**params).get("TagSet", [])
759 return boto3_tag_list_to_ansible_dict(current_tags)
760
761
762 @S3ErrorHandler.list_error_handler("get object ACL", {})
763 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
764 def get_s3_object_acl(
765 client: ClientType, bucket_name: str, object_key: str, version_id: Optional[str] = None, **kwargs
766 ) -> Dict:
767 """
768 Retrieve ACL for an S3 object.
769
770 Parameters:
771 client (boto3.client): The Boto3 S3 client object.
772 bucket_name (str): The name of the S3 bucket.
773 object_key (str): The key of the S3 object.
774 version_id (str, optional): The version ID of the object.
775 **kwargs: Additional parameters to pass to get_object_acl.
776
777 Returns:
778 Dict: ACL information including Owner and Grants.
779 Returns {} if object does not exist.
780 """
781 params = {"Bucket": bucket_name, "Key": object_key}
782 if version_id:
783 params["VersionId"] = version_id
784 params.update(kwargs)
785 return client.get_object_acl(**params)
786
787
788 @S3ErrorHandler.list_error_handler("get object legal hold status", {})
789 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
790 def get_s3_object_legal_hold(
791 client: ClientType, bucket_name: str, object_key: str, version_id: Optional[str] = None, **kwargs
792 ) -> Dict:
793 """
794 Retrieve legal hold status for an S3 object.
795
796 Parameters:
797 client (boto3.client): The Boto3 S3 client object.
798 bucket_name (str): The name of the S3 bucket.
799 object_key (str): The key of the S3 object.
800 version_id (str, optional): The version ID of the object.
801 **kwargs: Additional parameters to pass to get_object_legal_hold.
802
803 Returns:
804 Dict: Legal hold configuration.
805 Returns {} if not configured or object does not exist.
806 """
807 params = {"Bucket": bucket_name, "Key": object_key}
808 if version_id:
809 params["VersionId"] = version_id
810 params.update(kwargs)
811 result = client.get_object_legal_hold(**params)
812 return result.get("LegalHold", {})
813
814
815 @S3ErrorHandler.list_error_handler("get object retention settings", {})
816 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
817 def get_s3_object_retention(
818 client: ClientType, bucket_name: str, object_key: str, version_id: Optional[str] = None, **kwargs
819 ) -> Dict:
820 """
821 Retrieve retention settings for an S3 object.
822
823 Parameters:
824 client (boto3.client): The Boto3 S3 client object.
825 bucket_name (str): The name of the S3 bucket.
826 object_key (str): The key of the S3 object.
827 version_id (str, optional): The version ID of the object.
828 **kwargs: Additional parameters to pass to get_object_retention.
829
830 Returns:
831 Dict: Retention configuration.
832 Returns {} if not configured or object does not exist.
833 """
834 params = {"Bucket": bucket_name, "Key": object_key}
835 if version_id:
836 params["VersionId"] = version_id
837 params.update(kwargs)
838 result = client.get_object_retention(**params)
839 return result.get("Retention", {})
840
841
842 @S3ErrorHandler.list_error_handler("get object attributes", {})
843 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
844 def get_s3_object_attributes(
845 client: ClientType,
846 bucket_name: str,
847 object_key: str,
848 object_attributes: List[str],
849 version_id: Optional[str] = None,
850 **kwargs,
851 ) -> Dict:
852 """
853 Retrieve specific attributes for an S3 object.
854
855 Parameters:
856 client (boto3.client): The Boto3 S3 client object.
857 bucket_name (str): The name of the S3 bucket.
858 object_key (str): The key of the S3 object.
859 object_attributes (list): List of object attributes to retrieve
860 (e.g., ['ETag', 'Checksum', 'ObjectParts', 'StorageClass', 'ObjectSize']).
861 version_id (str, optional): The version ID of the object.
862 **kwargs: Additional parameters to pass to get_object_attributes.
863
864 Returns:
865 Dict: Requested object attributes.
866 Returns {} if object does not exist.
867 """
868 params = {
869 "Bucket": bucket_name,
870 "Key": object_key,
871 "ObjectAttributes": object_attributes,
872 }
873 if version_id:
874 params["VersionId"] = version_id
875 params.update(kwargs)
876 return client.get_object_attributes(**params)
877
878
879 @AWSRetry.jittered_backoff()
880 def s3_object_exists(
881 client: ClientType,
882 bucket_name: str,
883 object_key: str,
884 version_id: Optional[str] = None,
885 ) -> bool:
886 """
887 Check if an S3 object exists.
888
889 Parameters:
890 client (boto3.client): The Boto3 S3 client object.
891 bucket_name (str): The name of the S3 bucket.
892 object_key (str): The key of the S3 object.
893 version_id (str, optional): The version ID of the object.
894
895 Returns:
896 bool: True if object exists, False otherwise.
897
898 Raises:
899 AnsibleS3PermissionsError: If access is denied (403).
900 AnsibleS3Error: For other S3 errors.
901 """
902 result = head_s3_object(client, bucket_name, object_key, version_id)
903 return bool(result)
904
905
906 @S3ErrorHandler.deletion_error_handler("delete object")
907 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
908 def delete_s3_object(client: ClientType, bucket_name: str, object_key: str, **kwargs) -> Dict:
909 """
910 Delete an S3 object.
911
912 Parameters:
913 client (boto3.client): The Boto3 S3 client object.
914 bucket_name (str): The name of the S3 bucket.
915 object_key (str): The key of the S3 object to delete.
916 **kwargs: Additional parameters to pass to delete_object.
917
918 Returns:
919 Dict: Response from the delete operation.
920 """
921 params = {"Bucket": bucket_name, "Key": object_key}
922 params.update(kwargs)
923 return client.delete_object(**params)
924
925
926 @S3ErrorHandler.common_error_handler("update object tags")
927 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
928 def put_s3_object_tagging(
929 client: ClientType,
930 bucket_name: str,
931 object_key: str,
932 tags: Dict,
933 **kwargs,
934 ) -> Dict:
935 """
936 Set tags on an S3 object.
937
938 Parameters:
939 client (boto3.client): The Boto3 S3 client object.
940 bucket_name (str): The name of the S3 bucket.
941 object_key (str): The key of the S3 object.
942 tags (dict): Dictionary of tags to apply (e.g., {'Environment': 'prod', 'Owner': 'team'}).
943 **kwargs: Additional parameters to pass to put_object_tagging.
944
945 Returns:
946 Dict: Response from the put operation.
947 """
948 params = {
949 "Bucket": bucket_name,
950 "Key": object_key,
951 "Tagging": {"TagSet": ansible_dict_to_boto3_tag_list(tags)},
952 }
953 params.update(kwargs)
954 return client.put_object_tagging(**params)
955
956
957 @S3ErrorHandler.deletion_error_handler("delete object tags")
958 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
959 def delete_s3_object_tagging(client: ClientType, bucket_name: str, object_key: str, **kwargs) -> Dict:
960 """
961 Remove all tags from an S3 object.
962
963 Parameters:
964 client (boto3.client): The Boto3 S3 client object.
965 bucket_name (str): The name of the S3 bucket.
966 object_key (str): The key of the S3 object.
967 **kwargs: Additional parameters to pass to delete_object_tagging.
968
969 Returns:
970 Dict: Response from the delete operation.
971 """
972 params = {"Bucket": bucket_name, "Key": object_key}
973 params.update(kwargs)
974 return client.delete_object_tagging(**params)
975
976
977 @S3ErrorHandler.common_error_handler("update object ACL")
978 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
979 def put_s3_object_acl(client: ClientType, bucket_name: str, object_key: str, acl: str, **kwargs) -> Dict:
980 """
981 Set ACL on an S3 object.
982
983 Parameters:
984 client (boto3.client): The Boto3 S3 client object.
985 bucket_name (str): The name of the S3 bucket.
986 object_key (str): The key of the S3 object.
987 acl (str): The canned ACL to apply (e.g., 'private', 'public-read', 'authenticated-read').
988 **kwargs: Additional parameters to pass to put_object_acl.
989
990 Returns:
991 Dict: Response from the put operation.
992 """
993 params = {"Bucket": bucket_name, "Key": object_key, "ACL": acl}
994 params.update(kwargs)
995 return client.put_object_acl(**params)
996
997
998 @S3ErrorHandler.common_error_handler("put object")
999 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
1000 def put_s3_object(client: ClientType, **params) -> Dict:
1001 """
1002 Upload an object to S3 using put_object.
1003
1004 Parameters:
1005 client (boto3.client): The Boto3 S3 client object.
1006 **params: Parameters to pass to put_object (must include Bucket, Key, and typically Body).
1007
1008 Returns:
1009 Dict: Response from the put operation.
1010 """
1011 return client.put_object(**params)
1012
1013
1014 @S3ErrorHandler.common_error_handler("upload file")
1015 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
1016 def upload_s3_file(
1017 client: ClientType,
1018 filename: str,
1019 bucket_name: str,
1020 object_key: str,
1021 extra_args: Optional[Dict] = None,
1022 ) -> None:
1023 """
1024 Upload a file to S3 using upload_file (transfer manager).
1025
1026 Parameters:
1027 client (boto3.client): The Boto3 S3 client object.
1028 filename (str): Path to the file to upload.
1029 bucket_name (str): The name of the S3 bucket.
1030 object_key (str): The key for the S3 object.
1031 extra_args (dict, optional): Extra arguments for the upload (e.g., ContentType, Metadata).
1032
1033 Returns:
1034 None
1035 """
1036 if extra_args is None:
1037 extra_args = {}
1038 client.upload_file(Filename=filename, Bucket=bucket_name, Key=object_key, ExtraArgs=extra_args)
1039
1040
1041 @S3ErrorHandler.common_error_handler("download file")
1042 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
1043 def download_s3_file(
1044 client: ClientType,
1045 bucket_name: str,
1046 object_key: str,
1047 filename: str,
1048 extra_args: Optional[Dict] = None,
1049 ) -> None:
1050 """
1051 Download a file from S3 using download_file (transfer manager).
1052
1053 Parameters:
1054 client (boto3.client): The Boto3 S3 client object.
1055 bucket_name (str): The name of the S3 bucket.
1056 object_key (str): The key of the S3 object.
1057 filename (str): Path where the file should be saved.
1058 extra_args (dict, optional): Extra arguments for the download (e.g., VersionId).
1059
1060 Returns:
1061 None
1062 """
1063 if extra_args is None:
1064 extra_args = {}
1065 client.download_file(Bucket=bucket_name, Key=object_key, Filename=filename, ExtraArgs=extra_args)
1066
1067
1068 @S3ErrorHandler.common_error_handler("copy object")
1069 @AWSRetry.jittered_backoff(max_delay=120, catch_extra_error_codes=["NoSuchBucket", "OperationAborted"])
1070 def copy_s3_object(
1071 client: ClientType,
1072 copy_source: Dict,
1073 dest_bucket_name: str,
1074 dest_object_key: str,
1075 extra_args: Optional[Dict] = None,
1076 ) -> None:
1077 """
1078 Copy an object within S3 using managed copy (automatically handles multipart for large objects).
1079
1080 Parameters:
1081 client (boto3.client): The Boto3 S3 client object.
1082 copy_source (dict): Source object specification with 'Bucket', 'Key', and optionally 'VersionId'.
1083 dest_bucket_name (str): The destination bucket name.
1084 dest_object_key (str): The destination object key.
1085 extra_args (dict, optional): Extra arguments for the copy operation (e.g., ACL, Metadata).
1086
1087 Returns:
1088 None
1089 """
1090 if extra_args is None:
1091 extra_args = {}
1092 client.copy(copy_source, dest_bucket_name, dest_object_key, ExtraArgs=extra_args)
1093
1094
1095 @AWSRetry.jittered_backoff()
1096 def ensure_s3_object_tags(
1097 client: ClientType,
1098 bucket_name: str,
1099 object_key: str,
1100 desired_tags: Optional[Dict],
1101 purge_tags: bool = True,
1102 _max_attempts: int = 12,
1103 _sleep_time: float = 5.0,
1104 ) -> Tuple[Dict, bool]:
1105 """
1106 Ensure S3 object has desired tags, optionally purging unspecified tags.
1107
1108 This function handles the complete tag management workflow:
1109 - Retrieves current tags
1110 - Compares with desired state
1111 - Updates or deletes tags as needed
1112 - Waits for tags to be applied
1113
1114 Handles S3-compatible services that don't support tagging by returning empty tags
1115 when desired_tags is None.
1116
1117 Parameters:
1118 client (boto3.client): The Boto3 S3 client object.
1119 bucket_name (str): The name of the S3 bucket.
1120 object_key (str): The key of the S3 object.
1121 desired_tags (dict or None): Dictionary of desired tags. If None, tags are not modified.
1122 purge_tags (bool): If True, remove tags not in desired_tags. If False, merge with existing tags.
1123 _max_attempts (int): Maximum retry attempts for eventual consistency (internal/testing parameter).
1124 _sleep_time (float): Sleep time between retries in seconds (internal/testing parameter).
1125
1126 Returns:
1127 Tuple[Dict, bool]: (current_tags, changed) - The current tags and whether changes were made.
1128
1129 Raises:
1130 AnsibleS3Error: If tag operations fail and desired_tags is not None.
1131 AnsibleS3SupportError: If tagging is not supported and desired_tags is not None.
1132 """
1133 import time
1134
1135 # Get current tags, handling S3-compatible services that don't support tagging
1136 try:
1137 current_tags_dict = get_s3_object_tagging(client, bucket_name, object_key)
1138 except AnsibleS3SupportError:
1139 # If tags weren't requested, silently handle unsupported tagging
1140 if desired_tags is None:
1141 return {}, False
1142 # If tags were requested, re-raise to indicate tagging is not supported
1143 raise
1144
1145 # If no tags were requested, return current tags without changes
1146 if desired_tags is None:
1147 return current_tags_dict, False
1148
1149 # Compute final tags using existing merge_tags helper
1150 final_tags = merge_tags(current_tags_dict, desired_tags, purge_tags)
1151
1152 # Nothing to change
1153 if current_tags_dict == final_tags:
1154 return current_tags_dict, False
1155
1156 # Apply tag changes
1157 if final_tags:
1158 put_s3_object_tagging(client, bucket_name, object_key, final_tags)
1159 else:
1160 delete_s3_object_tagging(client, bucket_name, object_key)
1161
1162 # Wait for tags to be applied (eventual consistency)
1163 for _attempt in range(_max_attempts):
1164 current_tags_dict = get_s3_object_tagging(client, bucket_name, object_key)
1165 if current_tags_dict == final_tags:
1166 return current_tags_dict, True
1167 time.sleep(_sleep_time)
1168
1169 # Tags didn't apply in time, but return what we have
1170 return current_tags_dict, True
1171
1172
1173 @S3ErrorHandler.common_error_handler("generate presigned URL")
1174 @AWSRetry.jittered_backoff()
1175 def generate_s3_presigned_url(
1176 client: ClientType,
1177 bucket_name: str,
1178 object_key: str,
1179 client_method: str,
1180 expiry: int = 600,
1181 **params,
1182 ) -> str:
1183 """
1184 Generate a presigned URL for S3 object operations.
1185
1186 Parameters:
1187 client (boto3.client): The Boto3 S3 client object.
1188 bucket_name (str): The name of the S3 bucket.
1189 object_key (str): The key of the S3 object.
1190 client_method (str): The boto3 client method name ('get_object', 'put_object', etc.).
1191 expiry (int): URL expiration time in seconds (default: 600).
1192 **params: Additional parameters for the presigned URL.
1193
1194 Returns:
1195 str: The presigned URL, or empty string on error.
1196
1197 Raises:
1198 AnsibleS3Error: If URL generation fails.
1199 """
1200 url_params = {"Bucket": bucket_name, "Key": object_key}
1201 url_params.update(params)
1202
1203 return client.generate_presigned_url(ClientMethod=client_method, Params=url_params, ExpiresIn=expiry)
1204
1205
1206 @AWSRetry.jittered_backoff()
1207 def _list_objects_v2(client: ClientType, **params) -> Dict:
1208 params = {k: v for k, v in params.items() if v is not None}
1209 # For practical purposes, the paginator ignores MaxKeys, if we've been passed MaxKeys we need to
1210 # explicitly call list_objects_v3 rather than re-use the paginator
1211 if params.get("MaxKeys", None) is not None:
1212 return client.list_objects_v2(**params)
1213
1214 paginator = client.get_paginator("list_objects_v2")
1215 return paginator.paginate(**params).build_full_result()
1216
1217
1218 @S3ErrorHandler.list_error_handler("list bucket objects", [])
1219 def list_bucket_object_keys(
1220 client: ClientType,
1221 bucket: str,
1222 prefix: Optional[str] = None,
1223 max_keys: Optional[int] = None,
1224 start_after: Optional[str] = None,
1225 ) -> List[str]:
1226 """
1227 List object keys in an S3 bucket with optional filtering.
1228
1229 Parameters:
1230 client (boto3.client): The Boto3 S3 client object.
1231 bucket (str): The name of the S3 bucket.
1232 prefix (str, optional): Limits the response to keys that begin with the specified prefix.
1233 max_keys (int, optional): Maximum number of keys to return.
1234 start_after (str, optional): StartAfter key for pagination.
1235
1236 Returns:
1237 List[str]: List of object keys. Returns [] if bucket has no objects or on 404.
1238
1239 Raises:
1240 AnsibleS3PermissionsError: If access is denied (403).
1241 AnsibleS3Error: For other S3 errors.
1242 """
1243 response = _list_objects_v2(client, Bucket=bucket, Prefix=prefix, StartAfter=start_after, MaxKeys=max_keys)
1244 return [c["Key"] for c in response.get("Contents", [])]
1245
1246
1247 # ==========================================
1248 # Transformation and Helper Functions
1249 # ==========================================
1250
1251
1252 def calculate_checksum_with_file(
1253 client: ClientType, parts: int, bucket: str, obj: str, versionId: Optional[str], filename: str
1254 ) -> str:
1255 """
1256 Calculate MD5 checksum for a multipart upload using a local file.
1257
1258 Parameters:
1259 client (boto3.client): The Boto3 S3 client object.
1260 parts (int): Number of parts in the multipart upload.
1261 bucket (str): The S3 bucket name.
1262 obj (str): The S3 object key.
1263 versionId (str): Optional version ID of the object.
1264 filename (str): Path to the local file.
1265
1266 Returns:
1267 The ETag for the multipart upload in the format "{md5hash}-{parts}".
1268 """
1269 digests = []
1270 with open(filename, "rb") as f:
1271 for head in s3_head_objects(client, parts, bucket, obj, versionId):
1272 digests.append(md5(f.read(int(head["ContentLength"]))).digest())
1273
1274 digest_squared = b"".join(digests)
1275 return f'"{md5(digest_squared).hexdigest()}-{len(digests)}"'
1276
1277
1278 def calculate_checksum_with_content(
1279 client: ClientType, parts: int, bucket: str, obj: str, versionId: Optional[str], content: bytes
1280 ) -> str:
1281 """
1282 Calculate MD5 checksum for a multipart upload using in-memory content.
1283
1284 Parameters:
1285 client (boto3.client): The Boto3 S3 client object.
1286 parts (int): Number of parts in the multipart upload.
1287 bucket (str): The S3 bucket name.
1288 obj (str): The S3 object key.
1289 versionId (str): Optional version ID of the object.
1290 content (bytes): The content bytes.
1291
1292 Returns:
1293 The ETag for the multipart upload in the format "{md5hash}-{parts}".
1294 """
1295 digests = []
1296 offset = 0
1297 for head in s3_head_objects(client, parts, bucket, obj, versionId):
1298 length = int(head["ContentLength"])
1299 digests.append(md5(content[offset:offset + length]).digest()) # fmt: skip
1300 offset += length
1301
1302 digest_squared = b"".join(digests)
1303 return f'"{md5(digest_squared).hexdigest()}-{len(digests)}"'
1304
1305
1306 def calculate_etag(
1307 module: AnsibleAWSModule,
1308 filename: str,
1309 etag: Optional[str],
1310 client: ClientType,
1311 bucket: str,
1312 obj: str,
1313 version: Optional[str] = None,
1314 ) -> Optional[str]:
1315 """
1316 Calculate the ETag for a local file, handling both single-part and multipart uploads.
1317
1318 Parameters:
1319 module (AnsibleAWSModule): The Ansible module object.
1320 filename (str): Path to the local file.
1321 etag (str): The ETag from S3 to determine if multipart.
1322 client (boto3.client): The Boto3 S3 client object.
1323 bucket (str): The S3 bucket name.
1324 obj (str): The S3 object key.
1325 version (str): Optional version ID of the object.
1326
1327 Returns:
1328 The calculated ETag string, or None if MD5 is not available.
1329 """
1330 if not HAS_MD5:
1331 return None
1332
1333 if etag is not None and "-" in etag:
1334 # Multi-part ETag; a hash of the hashes of each part.
1335 parts = int(etag[1:-1].split("-")[1])
1336 try:
1337 return calculate_checksum_with_file(client, parts, bucket, obj, version, filename)
1338 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1339 raise AnsibleS3Error(message="Failed to calculate object ETag", exception=e) from e
1340 else: # Compute the MD5 sum normally
1341 return f'"{module.md5(filename)}"'
1342
1343
1344 def calculate_etag_content(
1345 module: AnsibleAWSModule,
1346 content: bytes,
1347 etag: Optional[str],
1348 client: ClientType,
1349 bucket: str,
1350 obj: str,
1351 version: Optional[str] = None,
1352 ) -> Optional[str]:
1353 """
1354 Calculate the ETag for in-memory content, handling both single-part and multipart uploads.
1355
1356 Parameters:
1357 module (AnsibleAWSModule): The Ansible module object.
1358 content (bytes): The content bytes.
1359 etag (str): The ETag from S3 to determine if multipart.
1360 client (boto3.client): The Boto3 S3 client object.
1361 bucket (str): The S3 bucket name.
1362 obj (str): The S3 object key.
1363 version (str): Optional version ID of the object.
1364
1365 Returns:
1366 The calculated ETag string, or None if MD5 is not available.
1367 """
1368 if not HAS_MD5:
1369 return None
1370
1371 if etag is not None and "-" in etag:
1372 # Multi-part ETag; a hash of the hashes of each part.
1373 parts = int(etag[1:-1].split("-")[1])
1374 try:
1375 return calculate_checksum_with_content(client, parts, bucket, obj, version, content)
1376 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
1377 raise AnsibleS3Error(message="Failed to calculate object ETag", exception=e) from e
1378 else: # Compute the MD5 sum normally
1379 return f'"{md5(content).hexdigest()}"'
1380
1381
1382 def validate_bucket_name(name: str) -> Optional[str]:
1383 """
1384 Validate S3 bucket name against AWS naming rules.
1385
1386 Parameters:
1387 name (str): The bucket name to validate.
1388
1389 Returns:
1390 Error message string if validation fails, or None if valid.
1391 """
1392 # See: https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html
1393 if len(name) < 3:
1394 return "the length of an S3 bucket must be at least 3 characters"
1395 if len(name) > 63:
1396 return "the length of an S3 bucket cannot exceed 63 characters"
1397
1398 legal_characters = string.ascii_lowercase + ".-" + string.digits
1399 illegal_characters = [c for c in name if c not in legal_characters]
1400 if illegal_characters:
1401 return "invalid character(s) found in the bucket name"
1402 if name[-1] not in string.ascii_lowercase + string.digits:
1403 return "bucket names must begin and end with a letter or number"
1404 return None
1405
1406
1407 def validate_account_regional_bucket_name(name: str, region: Optional[str] = None) -> Optional[str]:
1408 """
1409 Validate S3 bucket name for account-regional namespace.
1410
1411 Account-regional bucket names must follow the format:
1412 prefix-{accountId}-{region}-an
1413
1414 Parameters:
1415 name (str): The bucket name to validate.
1416 region (str): The AWS region (optional, used for validation if provided).
1417
1418 Returns:
1419 Error message string if validation fails, or None if valid.
1420 """
1421 import re
1422
1423 if len(name) < 3:
1424 return "account-regional bucket name must be at least 3 characters"
1425 if len(name) > 63:
1426 return "account-regional bucket name cannot exceed 63 characters"
1427
1428 if not name.endswith("-an"):
1429 return "account-regional bucket name must end with '-an'"
1430
1431 pattern = r"^(.+)-(\d{12})-([a-z]{2}-[a-z]+-\d)-an$"
1432 match = re.match(pattern, name)
1433
1434 if not match:
1435 return "account-regional bucket name must follow format: prefix-{12-digit-account-id}-{region}-an"
1436
1437 prefix, account_id, bucket_region = match.groups()
1438
1439 if not prefix:
1440 return "account-regional bucket name must have a prefix before the account ID"
1441
1442 if len(account_id) != 12:
1443 return "account ID in bucket name must be exactly 12 digits"
1444
1445 if region and bucket_region != region:
1446 return f"bucket name region '{bucket_region}' does not match the bucket's configured region '{region}'"
1447
1448 return None
1449
1450
1451 # Spot special case of fakes3.
1452 def is_fakes3(url: Optional[str]) -> bool:
1453 """Return True if endpoint_url has scheme fakes3://"""
1454 result = False
1455 if url is not None:
1456 result = urlparse(url).scheme in ("fakes3", "fakes3s")
1457 return result
1458
1459
1460 def parse_fakes3_endpoint(url: str) -> Dict:
1461 """
1462 Parse a FakeS3 endpoint URL and extract connection parameters.
1463
1464 Parameters:
1465 url (str): The FakeS3 endpoint URL (fakes3:// or fakes3s://).
1466
1467 Returns:
1468 Dict with 'endpoint' URL and 'use_ssl' boolean.
1469 """
1470 fakes3 = urlparse(url)
1471 protocol = "http"
1472 port = fakes3.port or 80
1473 if fakes3.scheme == "fakes3s":
1474 protocol = "https"
1475 port = fakes3.port or 443
1476 endpoint_url = f"{protocol}://{fakes3.hostname}:{to_text(port)}"
1477 use_ssl = bool(fakes3.scheme == "fakes3s")
1478 return {"endpoint": endpoint_url, "use_ssl": use_ssl}
1479
1480
1481 def parse_ceph_endpoint(url: str) -> Dict:
1482 """
1483 Parse a Ceph endpoint URL and extract connection parameters.
1484
1485 Parameters:
1486 url (str): The Ceph endpoint URL.
1487
1488 Returns:
1489 Dict with 'endpoint' URL and 'use_ssl' boolean.
1490 """
1491 ceph = urlparse(url)
1492 use_ssl = bool(ceph.scheme == "https")
1493 return {"endpoint": url, "use_ssl": use_ssl}
1494
1495
1496 def parse_s3_endpoint(options: Dict) -> Tuple[bool, Dict]:
1497 """
1498 Parse S3 endpoint options and determine connection parameters.
1499
1500 Parameters:
1501 options (dict): Dictionary containing endpoint_url, ceph flag, etc.
1502
1503 Returns:
1504 Tuple of (is_aws_s3, connection_params_dict).
1505 """
1506 endpoint_url = options.get("endpoint_url")
1507 if options.get("ceph"):
1508 return False, parse_ceph_endpoint(endpoint_url)
1509 if is_fakes3(endpoint_url):
1510 return False, parse_fakes3_endpoint(endpoint_url)
1511 return True, {"endpoint": endpoint_url}
1512
1513
1514 def s3_extra_params(options: Dict, sigv4: bool = False) -> Dict:
1515 """
1516 Build extra parameters for S3 client connection.
1517
1518 Parameters:
1519 options (dict): Dictionary containing connection options.
1520 sigv4 (bool): Whether to use signature version 4.
1521
1522 Returns:
1523 Dict of extra connection parameters for boto3 client.
1524 """
1525 aws, extra_params = parse_s3_endpoint(options)
1526 if not aws:
1527 return extra_params
1528 dualstack = options.get("dualstack")
1529 if not dualstack and not sigv4:
1530 return extra_params
1531 config: dict = {}
1532 if dualstack:
1533 config["use_dualstack_endpoint"] = True
1534 if sigv4:
1535 config["signature_version"] = "s3v4"
1536 extra_params["config"] = config
1537 return extra_params
1538
1539
1540 def get_s3_bucket_location(module: AnsibleAWSModule) -> str:
1541 """
1542 Determine the S3 bucket location/region from module parameters.
1543
1544 Parameters:
1545 module (AnsibleAWSModule): The Ansible module object.
1546
1547 Returns:
1548 The region string for the S3 bucket location.
1549 """
1550 if module.params.get("ceph") is True:
1551 return module.params.get("region")
1552 return module.region or "us-east-1"