| 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_object |
| 12 |
version_added: 1.0.0 |
| 13 |
short_description: Manage objects in S3 |
| 14 |
description: |
| 15 |
- This module allows the user to manage the objects and directories within S3 buckets. Includes |
| 16 |
support for creating and deleting objects and directories, retrieving objects as files or |
| 17 |
strings, generating download links and copying objects that are already stored in Amazon S3. |
| 18 |
- S3 buckets can be created or deleted using the M(amazon.aws.s3_bucket) module. |
| 19 |
- Compatible with AWS, DigitalOcean, Ceph, Walrus, FakeS3 and StorageGRID. |
| 20 |
- When using non-AWS services, O(endpoint_url) should be specified. |
| 21 |
options: |
| 22 |
bucket: |
| 23 |
description: |
| 24 |
- Bucket name. |
| 25 |
required: true |
| 26 |
type: str |
| 27 |
dest: |
| 28 |
description: |
| 29 |
- The destination file path when downloading an object/key when O(mode=get). |
| 30 |
- Ignored when O(mode) is not V(get). |
| 31 |
type: path |
| 32 |
encrypt: |
| 33 |
description: |
| 34 |
- Asks for server-side encryption of the objects when O(mode=put) or O(mode=copy). |
| 35 |
- Ignored when O(mode) is neither V(put) nor V(copy). |
| 36 |
default: true |
| 37 |
type: bool |
| 38 |
encryption_mode: |
| 39 |
description: |
| 40 |
- The encryption mode to use if O(encrypt=true). |
| 41 |
default: AES256 |
| 42 |
choices: |
| 43 |
- AES256 |
| 44 |
- aws:kms |
| 45 |
type: str |
| 46 |
expiry: |
| 47 |
description: |
| 48 |
- Time limit (in seconds) for the URL generated and returned by S3/Walrus when performing a |
| 49 |
O(mode=put) or O(mode=geturl) operation. |
| 50 |
- Ignored when O(mode) is neither V(put) nor V(geturl). |
| 51 |
default: 600 |
| 52 |
aliases: ['expiration'] |
| 53 |
type: int |
| 54 |
headers: |
| 55 |
description: |
| 56 |
- Custom headers to use when O(mode=put) as a dictionary of key value pairs. |
| 57 |
- Keys that match supported S3 object arguments are promoted to top‑level ExtraArgs. Supported keys include |
| 58 |
C(ContentType), C(Content-Disposition), C(ContentEncoding), C(ContentLanguage), C(CacheControl), C(Expires), |
| 59 |
C(ACL), C(GrantFullControl), C(GrantRead), C(GrantReadACP), C(GrantWriteACP), C(StorageClass), |
| 60 |
C(ServerSideEncryption), C(SSECustomerAlgorithm), C(SSECustomerKey), C(SSECustomerKeyMD5), C(SSEKMSKeyId), |
| 61 |
and C(WebsiteRedirectLocation). Remaining keys are stored under C(Metadata). |
| 62 |
- Both header name styles C(ContentType) and C(Content-Type) are supported. Underscore variants like |
| 63 |
C(content_type) are not promoted and will be placed under C(Metadata). |
| 64 |
- If C(ContentType) is not provided, a type is guessed from C(src) when uploading from a file. When uploading |
| 65 |
using C(content) or C(content_base64) the default is C(binary/octet-stream). |
| 66 |
- Ignored when O(mode) is not V(put). |
| 67 |
type: dict |
| 68 |
marker: |
| 69 |
description: |
| 70 |
- Specifies the key to start with when using list mode. Object keys are returned in |
| 71 |
alphabetical order, starting with key after the marker in order. |
| 72 |
type: str |
| 73 |
max_keys: |
| 74 |
description: |
| 75 |
- Max number of results to return when O(mode=list) |
| 76 |
- When not set, B(all) keys will be returned. |
| 77 |
- Ignored when O(mode) is not V(list). |
| 78 |
type: int |
| 79 |
metadata: |
| 80 |
description: |
| 81 |
- Metadata to use when O(mode=copy), O(mode=create) or O(mode=put) as a dictionary of key value pairs. |
| 82 |
- Keys that match supported S3 object arguments are promoted to top‑level ExtraArgs (for example C(ContentType)). |
| 83 |
Remaining keys are applied as user metadata under C(Metadata). |
| 84 |
type: dict |
| 85 |
mode: |
| 86 |
description: |
| 87 |
- Switches the module behaviour between |
| 88 |
- 'V(put): upload' |
| 89 |
- 'V(get): download' |
| 90 |
- 'V(geturl): return download URL' |
| 91 |
- 'V(getstr): download object as string' |
| 92 |
- 'V(list): list keys' |
| 93 |
- 'V(create): create bucket directories' |
| 94 |
- 'V(delobj): delete object' |
| 95 |
- 'V(copy): copy object that is already stored in another bucket' |
| 96 |
- Support for creating and deleting buckets was removed in release 6.0.0. |
| 97 |
To create and manage the bucket itself please use the M(amazon.aws.s3_bucket) module. |
| 98 |
- Support for V(list) has been deprecated and will be removed in a release after 2026-11-01. |
| 99 |
The M(amazon.aws.s3_object_info) module should be used instead of V(list). |
| 100 |
required: true |
| 101 |
choices: ['get', 'put', 'create', 'geturl', 'getstr', 'delobj', 'list', 'copy'] |
| 102 |
type: str |
| 103 |
object: |
| 104 |
description: |
| 105 |
- Key name of the object inside the bucket. |
| 106 |
- Can be used to create "virtual directories", see examples. |
| 107 |
- Object key names should not include the leading C(/), see |
| 108 |
U(https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html) for more |
| 109 |
information. |
| 110 |
type: str |
| 111 |
sig_v4: |
| 112 |
description: |
| 113 |
- Forces the Boto SDK to use Signature Version 4. |
| 114 |
- Only applies to get modes, O(mode=get), O(mode=getstr), O(mode=geturl). |
| 115 |
default: true |
| 116 |
type: bool |
| 117 |
version_added: 5.0.0 |
| 118 |
permission: |
| 119 |
description: |
| 120 |
- This option lets the user set the canned permissions on the object/bucket that are created. |
| 121 |
The permissions that can be set are V(private), V(public-read), V(public-read-write), |
| 122 |
V(authenticated-read) for a bucket or V(private), V(public-read), V(public-read-write), |
| 123 |
V(aws-exec-read), V(authenticated-read), V(bucket-owner-read), V(bucket-owner-full-control) |
| 124 |
for an object. Multiple permissions can be specified as a list; although only the first one |
| 125 |
will be used during the initial upload of the file. |
| 126 |
- For a full list of permissions see the AWS documentation |
| 127 |
U(https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html#canned-acl). |
| 128 |
default: ['private'] |
| 129 |
choices: |
| 130 |
- "private" |
| 131 |
- "public-read" |
| 132 |
- "public-read-write" |
| 133 |
- "aws-exec-read" |
| 134 |
- "authenticated-read" |
| 135 |
- "bucket-owner-read" |
| 136 |
- "bucket-owner-full-control" |
| 137 |
type: list |
| 138 |
elements: str |
| 139 |
prefix: |
| 140 |
description: |
| 141 |
- Limits the response to keys that begin with the specified prefix for list mode. |
| 142 |
default: "" |
| 143 |
type: str |
| 144 |
version: |
| 145 |
description: |
| 146 |
- Version ID of the object inside the bucket. Can be used to get a specific version of a file |
| 147 |
if versioning is enabled in the target bucket. |
| 148 |
type: str |
| 149 |
overwrite: |
| 150 |
description: |
| 151 |
- Force overwrite either locally on the filesystem or remotely with the object/key. |
| 152 |
- Used when O(mode=put) or O(mode=get). |
| 153 |
- Ignored when when O(mode) is neither V(put) nor V(get). |
| 154 |
- Must be a Boolean, V(always), V(never), V(different) or V(latest). |
| 155 |
- V(true) is the same as V(always). |
| 156 |
- V(false) is equal to V(never). |
| 157 |
- When this is set to C(different) the MD5 sum of the local file is compared with the 'ETag' |
| 158 |
of the object/key in S3. The ETag may or may not be an MD5 digest of the object data. See |
| 159 |
the ETag response header here |
| 160 |
U(https://docs.aws.amazon.com/AmazonS3/latest/API/RESTCommonResponseHeaders.html). |
| 161 |
- When O(mode=get) and O(overwrite=latest) the last modified timestamp of local file |
| 162 |
is compared with the 'LastModified' of the object/key in S3. |
| 163 |
default: 'different' |
| 164 |
aliases: ['force'] |
| 165 |
type: str |
| 166 |
retries: |
| 167 |
description: |
| 168 |
- On recoverable failure, how many times to retry before actually failing. |
| 169 |
default: 0 |
| 170 |
type: int |
| 171 |
aliases: ['retry'] |
| 172 |
dualstack: |
| 173 |
description: |
| 174 |
- Enables Amazon S3 Dual-Stack Endpoints, allowing S3 communications using both IPv4 and IPv6. |
| 175 |
- Support for passing O(dualstack) and O(endpoint_url) at the same time has been deprecated, |
| 176 |
the dualstack endpoints are automatically configured using the configured O(region). |
| 177 |
Support will be removed in a release after 2024-12-01. |
| 178 |
type: bool |
| 179 |
default: false |
| 180 |
ceph: |
| 181 |
description: |
| 182 |
- Enable API compatibility with Ceph RGW. |
| 183 |
- It takes into account the S3 API subset working with Ceph in order to provide the same module |
| 184 |
behaviour where possible. |
| 185 |
- Requires O(endpoint_url) if O(ceph=true). |
| 186 |
aliases: ['rgw'] |
| 187 |
default: false |
| 188 |
type: bool |
| 189 |
src: |
| 190 |
description: |
| 191 |
- The source file path when performing a C(put) operation. |
| 192 |
- One of O(content), O(content_base64) or O(src) must be specified when O(mode=put) |
| 193 |
otherwise ignored. |
| 194 |
type: path |
| 195 |
content: |
| 196 |
description: |
| 197 |
- The content to C(put) into an object. |
| 198 |
- The parameter value will be treated as a string and converted to UTF-8 before sending it to |
| 199 |
S3. |
| 200 |
- To send binary data, use the O(content_base64) parameter instead. |
| 201 |
- One of O(content), O(content_base64) or O(src) must be specified when O(mode=put) |
| 202 |
otherwise ignored. |
| 203 |
version_added: "1.3.0" |
| 204 |
type: str |
| 205 |
content_base64: |
| 206 |
description: |
| 207 |
- The base64-encoded binary data to C(put) into an object. |
| 208 |
- Use this if you need to put raw binary data, and don't forget to encode in base64. |
| 209 |
- One of O(content), O(content_base64) or O(src) must be specified when O(mode=put) |
| 210 |
otherwise ignored. |
| 211 |
version_added: "1.3.0" |
| 212 |
type: str |
| 213 |
ignore_nonexistent_bucket: |
| 214 |
description: |
| 215 |
- Overrides initial bucket lookups in case bucket or IAM policies are restrictive. |
| 216 |
- This can be useful when a user may have the C(GetObject) permission but no other |
| 217 |
permissions. In which case using O(mode=get) will fail unless |
| 218 |
O(ignore_nonexistent_bucket=true) is specified. |
| 219 |
type: bool |
| 220 |
default: false |
| 221 |
encryption_kms_key_id: |
| 222 |
description: |
| 223 |
- KMS key id to use when encrypting objects using O(encryption_mode=aws:kms). |
| 224 |
- Ignored if O(encryption_mode) is not V(aws:kms). |
| 225 |
type: str |
| 226 |
copy_src: |
| 227 |
description: |
| 228 |
- The source details of the object to copy. |
| 229 |
- Required if O(mode=copy). |
| 230 |
type: dict |
| 231 |
version_added: 2.0.0 |
| 232 |
suboptions: |
| 233 |
bucket: |
| 234 |
type: str |
| 235 |
description: |
| 236 |
- The name of the source bucket. |
| 237 |
required: true |
| 238 |
object: |
| 239 |
type: str |
| 240 |
description: |
| 241 |
- key name of the source object. |
| 242 |
- if not specified, all the objects of the O(copy_src.bucket) will be copied into the specified bucket. |
| 243 |
required: false |
| 244 |
version_id: |
| 245 |
type: str |
| 246 |
description: |
| 247 |
- version ID of the source object. |
| 248 |
prefix: |
| 249 |
description: |
| 250 |
- Copy all the keys that begin with the specified prefix. |
| 251 |
- Ignored if O(copy_src.object) is supplied. |
| 252 |
default: "" |
| 253 |
type: str |
| 254 |
version_added: 6.2.0 |
| 255 |
validate_bucket_name: |
| 256 |
description: |
| 257 |
- Whether the bucket name should be validated to conform to AWS S3 naming rules. |
| 258 |
- On by default, this may be disabled for S3 backends that do not enforce these rules. |
| 259 |
- See the Amazon documentation for more information about bucket naming rules |
| 260 |
U(https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html). |
| 261 |
type: bool |
| 262 |
version_added: 3.1.0 |
| 263 |
default: True |
| 264 |
expected_bucket_owner: |
| 265 |
description: |
| 266 |
- The account ID of the expected bucket owner. |
| 267 |
- If the account ID that you provide does not match the actual owner of the bucket, |
| 268 |
the request fails with the HTTP status code 403 Forbidden (access denied). |
| 269 |
type: str |
| 270 |
version_added: 8.2.0 |
| 271 |
author: |
| 272 |
- "Lester Wade (@lwade)" |
| 273 |
- "Sloane Hertel (@s-hertel)" |
| 274 |
- "Alina Buzachis (@alinabuzachis)" |
| 275 |
notes: |
| 276 |
- Support for O(tags) and O(purge_tags) was added in release 2.0.0. |
| 277 |
- For Walrus O(endpoint_url) should be set to the FQDN of the endpoint with neither scheme nor path. |
| 278 |
- Support for creating and deleting buckets was removed in release 6.0.0. |
| 279 |
extends_documentation_fragment: |
| 280 |
- amazon.aws.common.modules |
| 281 |
- amazon.aws.region.modules |
| 282 |
- amazon.aws.tags |
| 283 |
- amazon.aws.boto3 |
| 284 |
""" |
| 285 |
|
| 286 |
EXAMPLES = r""" |
| 287 |
- name: Simple PUT operation |
| 288 |
amazon.aws.s3_object: |
| 289 |
bucket: mybucket |
| 290 |
object: /my/desired/key.txt |
| 291 |
src: /usr/local/myfile.txt |
| 292 |
mode: put |
| 293 |
|
| 294 |
- name: PUT operation from a rendered template |
| 295 |
amazon.aws.s3_object: |
| 296 |
bucket: mybucket |
| 297 |
object: /object.yaml |
| 298 |
content: "{{ lookup('template', 'templates/object.yaml.j2') }}" |
| 299 |
mode: put |
| 300 |
|
| 301 |
- name: PUT content with explicit ContentType and ContentDisposition |
| 302 |
amazon.aws.s3_object: |
| 303 |
bucket: mybucket |
| 304 |
object: /index.html |
| 305 |
content: "<html>Hello</html>\n" |
| 306 |
mode: put |
| 307 |
headers: |
| 308 |
ContentType: "text/html; charset=utf-8" |
| 309 |
ContentDisposition: inline |
| 310 |
|
| 311 |
- name: Simple PUT operation in Ceph RGW S3 |
| 312 |
amazon.aws.s3_object: |
| 313 |
bucket: mybucket |
| 314 |
object: /my/desired/key.txt |
| 315 |
src: /usr/local/myfile.txt |
| 316 |
mode: put |
| 317 |
ceph: true |
| 318 |
endpoint_url: "http://localhost:8000" |
| 319 |
|
| 320 |
- name: Simple GET operation |
| 321 |
amazon.aws.s3_object: |
| 322 |
bucket: mybucket |
| 323 |
object: /my/desired/key.txt |
| 324 |
dest: /usr/local/myfile.txt |
| 325 |
mode: get |
| 326 |
|
| 327 |
- name: Get a specific version of an object. |
| 328 |
amazon.aws.s3_object: |
| 329 |
bucket: mybucket |
| 330 |
object: /my/desired/key.txt |
| 331 |
version: 48c9ee5131af7a716edc22df9772aa6f |
| 332 |
dest: /usr/local/myfile.txt |
| 333 |
mode: get |
| 334 |
|
| 335 |
- name: PUT/upload with metadata |
| 336 |
amazon.aws.s3_object: |
| 337 |
bucket: mybucket |
| 338 |
object: /my/desired/key.txt |
| 339 |
src: /usr/local/myfile.txt |
| 340 |
mode: put |
| 341 |
metadata: |
| 342 |
Content-Encoding: gzip |
| 343 |
Cache-Control: no-cache |
| 344 |
|
| 345 |
- name: PUT/upload with custom headers |
| 346 |
amazon.aws.s3_object: |
| 347 |
bucket: mybucket |
| 348 |
object: /my/desired/key.txt |
| 349 |
src: /usr/local/myfile.txt |
| 350 |
mode: put |
| 351 |
headers: |
| 352 |
GrantFullControl: "[email protected]" |
| 353 |
|
| 354 |
- name: List keys simple |
| 355 |
amazon.aws.s3_object: |
| 356 |
bucket: mybucket |
| 357 |
mode: list |
| 358 |
|
| 359 |
- name: List keys all options |
| 360 |
amazon.aws.s3_object: |
| 361 |
bucket: mybucket |
| 362 |
mode: list |
| 363 |
prefix: /my/desired/ |
| 364 |
marker: /my/desired/0023.txt |
| 365 |
max_keys: 472 |
| 366 |
|
| 367 |
- name: GET an object but don't download if the file checksums match. New in 2.0 |
| 368 |
amazon.aws.s3_object: |
| 369 |
bucket: mybucket |
| 370 |
object: /my/desired/key.txt |
| 371 |
dest: /usr/local/myfile.txt |
| 372 |
mode: get |
| 373 |
overwrite: different |
| 374 |
|
| 375 |
- name: Delete an object from a bucket |
| 376 |
amazon.aws.s3_object: |
| 377 |
bucket: mybucket |
| 378 |
object: /my/desired/key.txt |
| 379 |
mode: delobj |
| 380 |
|
| 381 |
- name: Copy an object already stored in another bucket |
| 382 |
amazon.aws.s3_object: |
| 383 |
bucket: mybucket |
| 384 |
object: /my/desired/key.txt |
| 385 |
mode: copy |
| 386 |
copy_src: |
| 387 |
bucket: srcbucket |
| 388 |
object: /source/key.txt |
| 389 |
|
| 390 |
- name: Copy all the objects with name starting with 'ansible_' |
| 391 |
amazon.aws.s3_object: |
| 392 |
bucket: mybucket |
| 393 |
mode: copy |
| 394 |
copy_src: |
| 395 |
bucket: srcbucket |
| 396 |
prefix: 'ansible_' |
| 397 |
""" |
| 398 |
|
| 399 |
RETURN = r""" |
| 400 |
msg: |
| 401 |
description: Message indicating the status of the operation. |
| 402 |
returned: always |
| 403 |
type: str |
| 404 |
sample: "PUT operation complete" |
| 405 |
url: |
| 406 |
description: URL of the object. |
| 407 |
returned: (for put and geturl operations) |
| 408 |
type: str |
| 409 |
sample: "https://my-bucket.s3.amazonaws.com/my-key.txt?AWSAccessKeyId=<access-key>&Expires=1506888865&Signature=<signature>" |
| 410 |
expiry: |
| 411 |
description: Number of seconds the presigned url is valid for. |
| 412 |
returned: (for geturl operation) |
| 413 |
type: int |
| 414 |
sample: 600 |
| 415 |
contents: |
| 416 |
description: Contents of the object as string. |
| 417 |
returned: (for getstr operation) |
| 418 |
type: str |
| 419 |
sample: "Hello, world!" |
| 420 |
s3_keys: |
| 421 |
description: List of object keys. |
| 422 |
returned: (for list operation) |
| 423 |
type: list |
| 424 |
elements: str |
| 425 |
sample: |
| 426 |
- prefix1/ |
| 427 |
- prefix1/key1 |
| 428 |
- prefix1/key2 |
| 429 |
tags: |
| 430 |
description: Tags of the s3 object. |
| 431 |
returned: always |
| 432 |
type: dict |
| 433 |
sample: { |
| 434 |
"Owner": "dev001", |
| 435 |
"env": "test" |
| 436 |
} |
| 437 |
""" |
| 438 |
|
| 439 |
import base64 |
| 440 |
import copy |
| 441 |
import mimetypes |
| 442 |
import os |
| 443 |
import typing |
| 444 |
|
| 445 |
if typing.TYPE_CHECKING: |
| 446 |
from typing import Any |
| 447 |
from typing import Dict |
| 448 |
from typing import List |
| 449 |
from typing import Optional |
| 450 |
from typing import Tuple |
| 451 |
|
| 452 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import ClientType |
| 453 |
|
| 454 |
from ansible.module_utils.basic import to_native |
| 455 |
|
| 456 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 457 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 458 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import HAS_MD5 |
| 459 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3ACLSupportError |
| 460 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3Error |
| 461 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3PermissionsError |
| 462 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3Sigv4RequiredError |
| 463 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3SupportError |
| 464 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import calculate_etag |
| 465 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import calculate_etag_content |
| 466 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import copy_s3_object |
| 467 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import delete_s3_object |
| 468 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import download_s3_file |
| 469 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import ensure_s3_object_tags |
| 470 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import generate_s3_presigned_url |
| 471 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_ownership_controls |
| 472 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_object_content |
| 473 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_object_tagging |
| 474 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import head_s3_object |
| 475 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import list_bucket_object_keys |
| 476 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_object |
| 477 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_object_acl |
| 478 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import s3_bucket_exists |
| 479 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import s3_extra_params |
| 480 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import s3_object_exists |
| 481 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import upload_s3_file |
| 482 |
from ansible_collections.amazon.aws.plugins.module_utils.s3 import validate_bucket_name |
| 483 |
|
| 484 |
|
| 485 |
def key_check( |
| 486 |
module: AnsibleAWSModule, |
| 487 |
s3: ClientType, |
| 488 |
bucket: str, |
| 489 |
obj: str, |
| 490 |
version: Optional[str] = None, |
| 491 |
validate: bool = True, |
| 492 |
) -> bool: |
| 493 |
"""Check if object exists with optional validation.""" |
| 494 |
try: |
| 495 |
exists = s3_object_exists(s3, bucket, obj, version_id=version) |
| 496 |
return exists |
| 497 |
except AnsibleS3PermissionsError: |
| 498 |
if validate: |
| 499 |
raise # Let the original AnsibleS3PermissionsError propagate |
| 500 |
return False # If not validating, treat permission errors as "doesn't exist" |
| 501 |
# Let other AnsibleS3Error exceptions propagate naturally |
| 502 |
|
| 503 |
|
| 504 |
def etag_compare( |
| 505 |
module: AnsibleAWSModule, |
| 506 |
s3: ClientType, |
| 507 |
bucket: str, |
| 508 |
obj: str, |
| 509 |
version: Optional[str] = None, |
| 510 |
local_file: Optional[str] = None, |
| 511 |
content: Optional[bytes] = None, |
| 512 |
) -> bool: |
| 513 |
s3_etag = head_s3_object(s3, bucket, obj, version_id=version).get("ETag") |
| 514 |
if local_file is not None: |
| 515 |
local_etag = calculate_etag(module, local_file, s3_etag, s3, bucket, obj, version) |
| 516 |
else: |
| 517 |
local_etag = calculate_etag_content(module, content, s3_etag, s3, bucket, obj, version) |
| 518 |
return s3_etag == local_etag |
| 519 |
|
| 520 |
|
| 521 |
def get_s3_last_modified_timestamp( |
| 522 |
s3: ClientType, |
| 523 |
bucket: str, |
| 524 |
obj: str, |
| 525 |
version: Optional[str] = None, |
| 526 |
) -> Optional[float]: |
| 527 |
last_modified = None |
| 528 |
obj_info = head_s3_object(s3, bucket, obj, version_id=version) |
| 529 |
if obj_info: |
| 530 |
last_modified = obj_info["LastModified"].timestamp() |
| 531 |
return last_modified |
| 532 |
|
| 533 |
|
| 534 |
def is_local_object_latest( |
| 535 |
s3: ClientType, |
| 536 |
bucket: str, |
| 537 |
obj: str, |
| 538 |
version: Optional[str] = None, |
| 539 |
local_file: Optional[str] = None, |
| 540 |
) -> bool: |
| 541 |
s3_last_modified = get_s3_last_modified_timestamp(s3, bucket, obj, version) |
| 542 |
if not os.path.exists(local_file): |
| 543 |
return False |
| 544 |
local_last_modified = os.path.getmtime(local_file) |
| 545 |
return s3_last_modified <= local_last_modified |
| 546 |
|
| 547 |
|
| 548 |
def bucket_check(module: AnsibleAWSModule, s3: ClientType, bucket: str, validate: bool = True) -> None: |
| 549 |
"""Check if bucket exists and is accessible.""" |
| 550 |
try: |
| 551 |
exists = s3_bucket_exists(s3, bucket) |
| 552 |
if not exists and validate: |
| 553 |
raise AnsibleS3Error( |
| 554 |
message=f"Bucket '{bucket}' not found. " |
| 555 |
"Support for automatically creating buckets was removed in release 6.0.0. " |
| 556 |
"The amazon.aws.s3_bucket module can be used to create buckets." |
| 557 |
) |
| 558 |
except AnsibleS3PermissionsError: |
| 559 |
if validate: |
| 560 |
raise # Let the original AnsibleS3PermissionsError propagate |
| 561 |
# If not validating, silently ignore permission errors |
| 562 |
# Let other AnsibleS3Error exceptions propagate naturally |
| 563 |
|
| 564 |
|
| 565 |
def put_object_acl( |
| 566 |
module: AnsibleAWSModule, |
| 567 |
s3: ClientType, |
| 568 |
bucket: str, |
| 569 |
obj: str, |
| 570 |
params: Optional[Dict] = None, |
| 571 |
) -> None: |
| 572 |
if params: |
| 573 |
put_s3_object(s3, **params) |
| 574 |
|
| 575 |
for acl in module.params.get("permission"): |
| 576 |
try: |
| 577 |
put_s3_object_acl(s3, bucket, obj, acl) |
| 578 |
except AnsibleS3ACLSupportError: |
| 579 |
module.warn("PutObjectAcl operation : The bucket does not allow ACLs.") |
| 580 |
return |
| 581 |
except AnsibleS3SupportError: |
| 582 |
# S3 drop-ins (MinIO, Ceph, etc.) may not support ACL operations |
| 583 |
module.warn( |
| 584 |
"Setting object ACLs is not supported by your storage provider. " |
| 585 |
"Set the 'permission' parameter to an empty list to avoid this warning." |
| 586 |
) |
| 587 |
return # Don't try other ACLs if this one failed |
| 588 |
|
| 589 |
|
| 590 |
def create_dirkey( |
| 591 |
module: AnsibleAWSModule, |
| 592 |
s3: ClientType, |
| 593 |
bucket: str, |
| 594 |
obj: str, |
| 595 |
encrypt: bool, |
| 596 |
expiry: int, |
| 597 |
metadata: Optional[Dict], |
| 598 |
) -> None: |
| 599 |
if module.check_mode: |
| 600 |
module.exit_json(msg="PUT operation skipped - running in check mode", changed=True) |
| 601 |
params = {"Bucket": bucket, "Key": obj, "Body": b""} |
| 602 |
params.update( |
| 603 |
get_extra_params( |
| 604 |
encrypt, |
| 605 |
module.params.get("encryption_mode"), |
| 606 |
module.params.get("encryption_kms_key_id"), |
| 607 |
metadata, |
| 608 |
) |
| 609 |
) |
| 610 |
put_object_acl(module, s3, bucket, obj, params) |
| 611 |
|
| 612 |
# Tags |
| 613 |
tags, _changed = ensure_s3_object_tags(s3, bucket, obj, module.params.get("tags"), module.params.get("purge_tags")) |
| 614 |
|
| 615 |
url = generate_s3_presigned_url(s3, bucket, obj, client_method="put_object", expiry=expiry) |
| 616 |
|
| 617 |
module.exit_json( |
| 618 |
msg=f"Virtual directory {obj} created in bucket {bucket}", |
| 619 |
url=url, |
| 620 |
tags=tags, |
| 621 |
changed=True, |
| 622 |
) |
| 623 |
|
| 624 |
|
| 625 |
def guess_content_type(src: Optional[str]) -> str: |
| 626 |
if src: |
| 627 |
content_type = mimetypes.guess_type(src)[0] |
| 628 |
if content_type: |
| 629 |
return content_type |
| 630 |
|
| 631 |
# S3 default content type |
| 632 |
return "binary/octet-stream" |
| 633 |
|
| 634 |
|
| 635 |
def get_extra_params( |
| 636 |
encrypt: Optional[bool] = None, |
| 637 |
encryption_mode: Optional[str] = None, |
| 638 |
encryption_kms_key_id: Optional[str] = None, |
| 639 |
metadata: Optional[Dict] = None, |
| 640 |
) -> Dict: |
| 641 |
extra = {} |
| 642 |
if encrypt: |
| 643 |
extra["ServerSideEncryption"] = encryption_mode |
| 644 |
if encryption_kms_key_id and encryption_mode == "aws:kms": |
| 645 |
extra["SSEKMSKeyId"] = encryption_kms_key_id |
| 646 |
if metadata: |
| 647 |
extra["Metadata"] = {} |
| 648 |
# determine object metadata and extra arguments |
| 649 |
for option in metadata: |
| 650 |
extra_args_option = option_in_extra_args(option) |
| 651 |
if extra_args_option: |
| 652 |
extra[extra_args_option] = metadata[option] |
| 653 |
else: |
| 654 |
extra["Metadata"][option] = metadata[option] |
| 655 |
return extra |
| 656 |
|
| 657 |
|
| 658 |
def option_in_extra_args(option: str) -> Optional[str]: |
| 659 |
temp_option = option.replace("-", "").lower() |
| 660 |
|
| 661 |
allowed_extra_args = { |
| 662 |
"acl": "ACL", |
| 663 |
"cachecontrol": "CacheControl", |
| 664 |
"contentdisposition": "ContentDisposition", |
| 665 |
"contentencoding": "ContentEncoding", |
| 666 |
"contentlanguage": "ContentLanguage", |
| 667 |
"contenttype": "ContentType", |
| 668 |
"expires": "Expires", |
| 669 |
"grantfullcontrol": "GrantFullControl", |
| 670 |
"grantread": "GrantRead", |
| 671 |
"grantreadacp": "GrantReadACP", |
| 672 |
"grantwriteacp": "GrantWriteACP", |
| 673 |
"metadata": "Metadata", |
| 674 |
"requestpayer": "RequestPayer", |
| 675 |
"serversideencryption": "ServerSideEncryption", |
| 676 |
"storageclass": "StorageClass", |
| 677 |
"ssecustomeralgorithm": "SSECustomerAlgorithm", |
| 678 |
"ssecustomerkey": "SSECustomerKey", |
| 679 |
"ssecustomerkeymd5": "SSECustomerKeyMD5", |
| 680 |
"ssekmskeyid": "SSEKMSKeyId", |
| 681 |
"websiteredirectlocation": "WebsiteRedirectLocation", |
| 682 |
} |
| 683 |
|
| 684 |
if temp_option in allowed_extra_args: |
| 685 |
return allowed_extra_args[temp_option] |
| 686 |
return None |
| 687 |
|
| 688 |
|
| 689 |
def upload_s3file( |
| 690 |
module: AnsibleAWSModule, |
| 691 |
s3: ClientType, |
| 692 |
bucket: str, |
| 693 |
obj: str, |
| 694 |
expiry: int, |
| 695 |
metadata: Optional[Dict], |
| 696 |
encrypt: bool, |
| 697 |
headers: Optional[Dict], |
| 698 |
src: Optional[str] = None, |
| 699 |
content: Optional[bytes] = None, |
| 700 |
acl_disabled: bool = False, |
| 701 |
) -> None: |
| 702 |
if module.check_mode: |
| 703 |
module.exit_json(msg="PUT operation skipped - running in check mode", changed=True) |
| 704 |
extra = get_extra_params( |
| 705 |
encrypt, |
| 706 |
module.params.get("encryption_mode"), |
| 707 |
module.params.get("encryption_kms_key_id"), |
| 708 |
metadata, |
| 709 |
) |
| 710 |
# Promote supported headers to boto3 ExtraArgs and place unknown ones under Metadata |
| 711 |
if headers: |
| 712 |
if not isinstance(headers, dict): |
| 713 |
module.warn("'headers' must be a dict; ignoring non-dict value") |
| 714 |
else: |
| 715 |
for option, value in headers.items(): |
| 716 |
extra_arg_key = option_in_extra_args(option) |
| 717 |
if extra_arg_key: |
| 718 |
extra[extra_arg_key] = value |
| 719 |
else: |
| 720 |
# Fall back to Metadata for non-ExtraArgs headers |
| 721 |
extra.setdefault("Metadata", {}) |
| 722 |
extra["Metadata"][option] = value |
| 723 |
if module.params.get("permission"): |
| 724 |
permissions = module.params["permission"] |
| 725 |
if isinstance(permissions, str): |
| 726 |
extra["ACL"] = permissions |
| 727 |
elif isinstance(permissions, list): |
| 728 |
extra["ACL"] = permissions[0] |
| 729 |
|
| 730 |
if "ContentType" not in extra: |
| 731 |
extra["ContentType"] = guess_content_type(src) |
| 732 |
|
| 733 |
if src: |
| 734 |
upload_s3_file(s3, src, bucket, obj, extra) |
| 735 |
else: |
| 736 |
# For in-memory content uploads, use put_object so promoted headers |
| 737 |
# (e.g. ContentType, ContentDisposition, CacheControl) are applied consistently |
| 738 |
params = {"Bucket": bucket, "Key": obj, "Body": content} |
| 739 |
params.update(extra) |
| 740 |
put_s3_object(s3, **params) |
| 741 |
|
| 742 |
if not acl_disabled: |
| 743 |
put_object_acl(module, s3, bucket, obj) |
| 744 |
|
| 745 |
# Tags |
| 746 |
tags, _changed = ensure_s3_object_tags(s3, bucket, obj, module.params.get("tags"), module.params.get("purge_tags")) |
| 747 |
|
| 748 |
url = generate_s3_presigned_url(s3, bucket, obj, client_method="put_object", expiry=expiry) |
| 749 |
|
| 750 |
module.exit_json(msg="PUT operation complete", url=url, tags=tags, changed=True) |
| 751 |
|
| 752 |
|
| 753 |
def download_s3file( |
| 754 |
module: AnsibleAWSModule, |
| 755 |
s3: ClientType, |
| 756 |
bucket: str, |
| 757 |
obj: str, |
| 758 |
dest: str, |
| 759 |
retries: int, |
| 760 |
version: Optional[str] = None, |
| 761 |
) -> None: |
| 762 |
if module.check_mode: |
| 763 |
module.exit_json(msg="GET operation skipped - running in check mode", changed=True) |
| 764 |
|
| 765 |
extra_args = {"VersionId": version} if version else {} |
| 766 |
download_s3_file(s3, bucket, obj, dest, extra_args) |
| 767 |
module.exit_json(msg="GET operation complete", changed=True) |
| 768 |
|
| 769 |
|
| 770 |
def download_s3str( |
| 771 |
module: AnsibleAWSModule, |
| 772 |
s3: ClientType, |
| 773 |
bucket: str, |
| 774 |
obj: str, |
| 775 |
version: Optional[str] = None, |
| 776 |
) -> None: |
| 777 |
if module.check_mode: |
| 778 |
module.exit_json(msg="GET operation skipped - running in check mode", changed=True) |
| 779 |
contents = to_native(get_s3_object_content(s3, bucket, obj, version_id=version)) |
| 780 |
module.exit_json(msg="GET operation complete", contents=contents, changed=True) |
| 781 |
|
| 782 |
|
| 783 |
def get_download_url( |
| 784 |
module: AnsibleAWSModule, |
| 785 |
s3: ClientType, |
| 786 |
bucket: str, |
| 787 |
obj: str, |
| 788 |
expiry: int, |
| 789 |
tags: Optional[Dict] = None, |
| 790 |
changed: bool = True, |
| 791 |
) -> None: |
| 792 |
url = generate_s3_presigned_url(s3, bucket, obj, client_method="get_object", expiry=expiry) |
| 793 |
module.exit_json( |
| 794 |
msg="Download url:", |
| 795 |
url=url, |
| 796 |
tags=tags, |
| 797 |
expiry=expiry, |
| 798 |
changed=changed, |
| 799 |
) |
| 800 |
|
| 801 |
|
| 802 |
def get_current_object_tags_dict( |
| 803 |
module: AnsibleAWSModule, |
| 804 |
s3: ClientType, |
| 805 |
bucket: str, |
| 806 |
obj: str, |
| 807 |
version: Optional[str] = None, |
| 808 |
) -> Dict: |
| 809 |
"""Get object tags with module-specific parameter handling.""" |
| 810 |
kwargs = {} |
| 811 |
if module.params.get("expected_bucket_owner"): |
| 812 |
kwargs["ExpectedBucketOwner"] = module.params["expected_bucket_owner"] |
| 813 |
|
| 814 |
try: |
| 815 |
return get_s3_object_tagging(s3, bucket, obj, version_id=version, **kwargs) |
| 816 |
except AnsibleS3SupportError: |
| 817 |
module.warn("GetObjectTagging is not implemented by your storage provider.") |
| 818 |
return {} |
| 819 |
# Let other AnsibleS3Error exceptions propagate naturally |
| 820 |
|
| 821 |
|
| 822 |
def get_binary_content(s3_vars: Dict) -> Optional[bytes]: |
| 823 |
# the content will be uploaded as a byte string, so we must encode it first |
| 824 |
bincontent = None |
| 825 |
if s3_vars.get("content") is not None: |
| 826 |
bincontent = s3_vars["content"].encode("utf-8") |
| 827 |
if s3_vars.get("content_base64") is not None: |
| 828 |
bincontent = base64.standard_b64decode(s3_vars["content_base64"]) |
| 829 |
return bincontent |
| 830 |
|
| 831 |
|
| 832 |
def do_s3_object_get(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None: |
| 833 |
keyrtn = key_check( |
| 834 |
module, |
| 835 |
connection, |
| 836 |
s3_vars["bucket"], |
| 837 |
s3_vars["object"], |
| 838 |
version=s3_vars["version"], |
| 839 |
validate=s3_vars["validate"], |
| 840 |
) |
| 841 |
if not keyrtn: |
| 842 |
if s3_vars["version"]: |
| 843 |
module.fail_json(msg=f"Key {s3_vars['object']} with version id {s3_vars['version']} does not exist.") |
| 844 |
module.fail_json(msg=f"Key {s3_vars['object']} does not exist.") |
| 845 |
if s3_vars["dest"] and os.path.exists(s3_vars["dest"]) and s3_vars["overwrite"] != "always": |
| 846 |
if s3_vars["overwrite"] == "never": |
| 847 |
module.exit_json( |
| 848 |
msg="Local object already exists and overwrite is disabled.", |
| 849 |
changed=False, |
| 850 |
) |
| 851 |
if s3_vars["overwrite"] == "different" and etag_compare( |
| 852 |
module, |
| 853 |
connection, |
| 854 |
s3_vars["bucket"], |
| 855 |
s3_vars["object"], |
| 856 |
version=s3_vars["version"], |
| 857 |
local_file=s3_vars["dest"], |
| 858 |
): |
| 859 |
module.exit_json( |
| 860 |
msg="Local and remote object are identical, ignoring. Use overwrite=always parameter to force.", |
| 861 |
changed=False, |
| 862 |
) |
| 863 |
if s3_vars["overwrite"] == "latest" and is_local_object_latest( |
| 864 |
connection, |
| 865 |
s3_vars["bucket"], |
| 866 |
s3_vars["object"], |
| 867 |
version=s3_vars["version"], |
| 868 |
local_file=s3_vars["dest"], |
| 869 |
): |
| 870 |
module.exit_json( |
| 871 |
msg="Local object is latest, ignoreing. Use overwrite=always parameter to force.", |
| 872 |
changed=False, |
| 873 |
) |
| 874 |
|
| 875 |
download_s3file( |
| 876 |
module, |
| 877 |
connection, |
| 878 |
s3_vars["bucket"], |
| 879 |
s3_vars["object"], |
| 880 |
s3_vars["dest"], |
| 881 |
s3_vars["retries"], |
| 882 |
version=s3_vars["version"], |
| 883 |
) |
| 884 |
|
| 885 |
module.exit_json(failed=False) |
| 886 |
|
| 887 |
|
| 888 |
def do_s3_object_put(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None: |
| 889 |
# if putting an object in a bucket yet to be created, acls for the bucket and/or the object may be specified |
| 890 |
# these were separated into the variables bucket_acl and object_acl above |
| 891 |
|
| 892 |
if s3_vars["src"] is not None and not os.path.exists(s3_vars["src"]): |
| 893 |
module.fail_json(msg=f'Local object "{s3_vars["src"]}" does not exist for PUT operation') |
| 894 |
|
| 895 |
keyrtn = key_check( |
| 896 |
module, |
| 897 |
connection, |
| 898 |
s3_vars["bucket"], |
| 899 |
s3_vars["object"], |
| 900 |
version=s3_vars["version"], |
| 901 |
validate=s3_vars["validate"], |
| 902 |
) |
| 903 |
|
| 904 |
# the content will be uploaded as a byte string, so we must encode it first |
| 905 |
bincontent = get_binary_content(s3_vars) |
| 906 |
|
| 907 |
if keyrtn and s3_vars["overwrite"] != "always": |
| 908 |
if s3_vars["overwrite"] == "never" or etag_compare( |
| 909 |
module, |
| 910 |
connection, |
| 911 |
s3_vars["bucket"], |
| 912 |
s3_vars["object"], |
| 913 |
version=s3_vars["version"], |
| 914 |
local_file=s3_vars["src"], |
| 915 |
content=bincontent, |
| 916 |
): |
| 917 |
# Return the download URL for the existing object and ensure tags are updated |
| 918 |
tags, tags_update = ensure_s3_object_tags( |
| 919 |
connection, |
| 920 |
s3_vars["bucket"], |
| 921 |
s3_vars["object"], |
| 922 |
module.params.get("tags"), |
| 923 |
module.params.get("purge_tags"), |
| 924 |
) |
| 925 |
get_download_url( |
| 926 |
module, |
| 927 |
connection, |
| 928 |
s3_vars["bucket"], |
| 929 |
s3_vars["object"], |
| 930 |
s3_vars["expiry"], |
| 931 |
tags, |
| 932 |
changed=tags_update, |
| 933 |
) |
| 934 |
|
| 935 |
# only use valid object acls for the upload_s3file function |
| 936 |
if not s3_vars["acl_disabled"]: |
| 937 |
s3_vars["permission"] = s3_vars["object_acl"] |
| 938 |
upload_s3file( |
| 939 |
module, |
| 940 |
connection, |
| 941 |
s3_vars["bucket"], |
| 942 |
s3_vars["object"], |
| 943 |
s3_vars["expiry"], |
| 944 |
s3_vars["metadata"], |
| 945 |
s3_vars["encrypt"], |
| 946 |
s3_vars["headers"], |
| 947 |
src=s3_vars["src"], |
| 948 |
content=bincontent, |
| 949 |
acl_disabled=s3_vars["acl_disabled"], |
| 950 |
) |
| 951 |
module.exit_json(failed=False) |
| 952 |
|
| 953 |
|
| 954 |
def do_s3_object_delobj(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None: |
| 955 |
if module.check_mode: |
| 956 |
module.exit_json( |
| 957 |
msg="DELETE operation skipped - running in check mode", |
| 958 |
changed=True, |
| 959 |
) |
| 960 |
delete_s3_object( |
| 961 |
connection, |
| 962 |
s3_vars["bucket"], |
| 963 |
s3_vars["object"], |
| 964 |
) |
| 965 |
module.exit_json(msg=f"Object {s3_vars['object']} deleted from bucket {s3_vars['bucket']}.", changed=True) |
| 966 |
|
| 967 |
|
| 968 |
def do_s3_object_list(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None: |
| 969 |
# If the bucket does not exist then bail out |
| 970 |
keys = list_bucket_object_keys( |
| 971 |
connection, |
| 972 |
s3_vars["bucket"], |
| 973 |
prefix=s3_vars["prefix"], |
| 974 |
start_after=s3_vars["marker"], |
| 975 |
max_keys=s3_vars["max_keys"], |
| 976 |
) |
| 977 |
module.exit_json(msg="LIST operation complete", s3_keys=keys) |
| 978 |
|
| 979 |
|
| 980 |
def do_s3_object_create(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None: |
| 981 |
# if both creating a bucket and putting an object in it, acls for the bucket and/or the object may be specified |
| 982 |
# these were separated above into the variables bucket_acl and object_acl |
| 983 |
|
| 984 |
if not s3_vars["object"].endswith("/"): |
| 985 |
s3_vars["object"] = s3_vars["object"] + "/" |
| 986 |
|
| 987 |
if key_check(module, connection, s3_vars["bucket"], s3_vars["object"]): |
| 988 |
module.exit_json( |
| 989 |
msg=f"Bucket {s3_vars['bucket']} and key {s3_vars['object']} already exists.", |
| 990 |
changed=False, |
| 991 |
) |
| 992 |
if not s3_vars["acl_disabled"]: |
| 993 |
# setting valid object acls for the create_dirkey function |
| 994 |
s3_vars["permission"] = s3_vars["object_acl"] |
| 995 |
create_dirkey( |
| 996 |
module, |
| 997 |
connection, |
| 998 |
s3_vars["bucket"], |
| 999 |
s3_vars["object"], |
| 1000 |
s3_vars["encrypt"], |
| 1001 |
s3_vars["expiry"], |
| 1002 |
s3_vars["metadata"], |
| 1003 |
) |
| 1004 |
|
| 1005 |
|
| 1006 |
def do_s3_object_geturl(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None: |
| 1007 |
if key_check( |
| 1008 |
module, |
| 1009 |
connection, |
| 1010 |
s3_vars["bucket"], |
| 1011 |
s3_vars["object"], |
| 1012 |
version=s3_vars["version"], |
| 1013 |
validate=s3_vars["validate"], |
| 1014 |
): |
| 1015 |
tags = get_current_object_tags_dict( |
| 1016 |
module, |
| 1017 |
connection, |
| 1018 |
s3_vars["bucket"], |
| 1019 |
s3_vars["object"], |
| 1020 |
version=s3_vars["version"], |
| 1021 |
) |
| 1022 |
get_download_url( |
| 1023 |
module, |
| 1024 |
connection, |
| 1025 |
s3_vars["bucket"], |
| 1026 |
s3_vars["object"], |
| 1027 |
s3_vars["expiry"], |
| 1028 |
tags, |
| 1029 |
) |
| 1030 |
module.fail_json(msg=f"Key {s3_vars['object']} does not exist.") |
| 1031 |
|
| 1032 |
|
| 1033 |
def do_s3_object_getstr(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None: |
| 1034 |
if s3_vars["bucket"] and s3_vars["object"]: |
| 1035 |
if key_check( |
| 1036 |
module, |
| 1037 |
connection, |
| 1038 |
s3_vars["bucket"], |
| 1039 |
s3_vars["object"], |
| 1040 |
version=s3_vars["version"], |
| 1041 |
validate=s3_vars["validate"], |
| 1042 |
): |
| 1043 |
download_s3str( |
| 1044 |
module, |
| 1045 |
connection, |
| 1046 |
s3_vars["bucket"], |
| 1047 |
s3_vars["object"], |
| 1048 |
version=s3_vars["version"], |
| 1049 |
) |
| 1050 |
elif s3_vars["version"]: |
| 1051 |
module.fail_json(msg=f"Key {s3_vars['object']} with version id {s3_vars['version']} does not exist.") |
| 1052 |
else: |
| 1053 |
module.fail_json(msg=f"Key {s3_vars['object']} does not exist.") |
| 1054 |
|
| 1055 |
|
| 1056 |
def check_object_tags(module: AnsibleAWSModule, connection: ClientType, bucket: str, obj: str) -> bool: |
| 1057 |
tags = module.params.get("tags") |
| 1058 |
purge_tags = module.params.get("purge_tags") |
| 1059 |
diff = False |
| 1060 |
if tags: |
| 1061 |
current_tags_dict = get_current_object_tags_dict(module, connection, bucket, obj) |
| 1062 |
if not purge_tags: |
| 1063 |
# Ensure existing tags that aren't updated by desired tags remain |
| 1064 |
current_tags_dict.update(tags) |
| 1065 |
diff = current_tags_dict != tags |
| 1066 |
return diff |
| 1067 |
|
| 1068 |
|
| 1069 |
def calculate_object_etag( |
| 1070 |
module: AnsibleAWSModule, s3: ClientType, bucket: str, obj: str, head_etag: str, version: Optional[str] = None |
| 1071 |
) -> str: |
| 1072 |
etag = head_etag |
| 1073 |
if "-" in etag: |
| 1074 |
# object has been created using multipart upload, compute ETag using |
| 1075 |
# object content to ensure idempotency. |
| 1076 |
contents = get_s3_object_content(s3, bucket, obj, version_id=version) |
| 1077 |
# Set ETag to None, to force function to compute ETag from content |
| 1078 |
etag = calculate_etag_content(module, contents, None, s3, bucket, obj) |
| 1079 |
return etag |
| 1080 |
|
| 1081 |
|
| 1082 |
def copy_object_to_bucket( |
| 1083 |
module: AnsibleAWSModule, |
| 1084 |
s3: ClientType, |
| 1085 |
bucket: str, |
| 1086 |
obj: str, |
| 1087 |
encrypt: bool, |
| 1088 |
metadata: Optional[Dict], |
| 1089 |
validate: bool, |
| 1090 |
src_bucket: str, |
| 1091 |
src_obj: str, |
| 1092 |
versionId: Optional[str] = None, |
| 1093 |
) -> Tuple[bool, Dict]: |
| 1094 |
if not key_check(module, s3, src_bucket, src_obj, version=versionId, validate=validate): |
| 1095 |
# Key does not exist in source bucket |
| 1096 |
module.exit_json( |
| 1097 |
msg=f"Key {src_obj} does not exist in bucket {src_bucket}.", |
| 1098 |
changed=False, |
| 1099 |
) |
| 1100 |
|
| 1101 |
s_obj_info = head_s3_object(s3, src_bucket, src_obj, version_id=versionId) |
| 1102 |
d_obj_info = head_s3_object(s3, bucket, obj, version_id=None) |
| 1103 |
do_match = True |
| 1104 |
diff_msg = None |
| 1105 |
if d_obj_info: |
| 1106 |
src_etag = calculate_object_etag(module, s3, src_bucket, src_obj, s_obj_info.get("ETag"), versionId) |
| 1107 |
dst_etag = calculate_object_etag(module, s3, bucket, obj, d_obj_info.get("ETag")) |
| 1108 |
if src_etag != dst_etag: |
| 1109 |
# Source and destination objects ETag differ |
| 1110 |
do_match = False |
| 1111 |
diff_msg = "ETag from source and destination differ" |
| 1112 |
if do_match and metadata and metadata != d_obj_info.get("Metadata"): |
| 1113 |
# Metadata from module inputs differs from what has been retrieved from object header |
| 1114 |
diff_msg = "Would have update object Metadata if not running in check mode." |
| 1115 |
do_match = False |
| 1116 |
else: |
| 1117 |
# The destination object does not exists |
| 1118 |
do_match = False |
| 1119 |
diff_msg = "Would have copy object if not running in check mode." |
| 1120 |
|
| 1121 |
if do_match: |
| 1122 |
# S3 objects are equals, ensure tags will not be updated |
| 1123 |
if module.check_mode: |
| 1124 |
changed = check_object_tags(module, s3, bucket, obj) |
| 1125 |
result = {} |
| 1126 |
if changed: |
| 1127 |
result.update({"msg": "Would have update object tags if not running in check mode."}) |
| 1128 |
return changed, result |
| 1129 |
|
| 1130 |
# Ensure tags |
| 1131 |
tags, changed = ensure_s3_object_tags( |
| 1132 |
s3, bucket, obj, module.params.get("tags"), module.params.get("purge_tags") |
| 1133 |
) |
| 1134 |
result = {"msg": "ETag from source and destination are the same"} |
| 1135 |
if changed: |
| 1136 |
result = {"msg": "tags successfully updated.", "tags": tags} |
| 1137 |
return changed, result |
| 1138 |
# S3 objects differ |
| 1139 |
if module.check_mode: |
| 1140 |
return True, {"msg": diff_msg} |
| 1141 |
else: |
| 1142 |
changed = True |
| 1143 |
bucketsrc = { |
| 1144 |
"Bucket": src_bucket, |
| 1145 |
"Key": src_obj, |
| 1146 |
} |
| 1147 |
if versionId: |
| 1148 |
bucketsrc.update({"VersionId": versionId}) |
| 1149 |
|
| 1150 |
extra_args = get_extra_params( |
| 1151 |
encrypt, |
| 1152 |
module.params.get("encryption_mode"), |
| 1153 |
module.params.get("encryption_kms_key_id"), |
| 1154 |
metadata, |
| 1155 |
) |
| 1156 |
|
| 1157 |
if metadata: |
| 1158 |
# 'MetadataDirective' Specifies whether the metadata is copied from the source object or replaced |
| 1159 |
# with metadata that's provided in the request. The default value is 'COPY', therefore when user |
| 1160 |
# specifies a metadata we should set it to 'REPLACE' |
| 1161 |
extra_args.update({"MetadataDirective": "REPLACE"}) |
| 1162 |
|
| 1163 |
# perform a "managed" copy rather simply using copy_object. This will automatically use |
| 1164 |
# multi-part uploads where necessary (https://github.com/boto/boto3/issues/1715) |
| 1165 |
copy_s3_object(s3, bucketsrc, bucket, obj, extra_args) |
| 1166 |
|
| 1167 |
# We can't set the ACLs & tags during the copy, update them afterwards |
| 1168 |
put_object_acl(module, s3, bucket, obj) |
| 1169 |
tags, tags_updated = ensure_s3_object_tags( |
| 1170 |
s3, bucket, obj, module.params.get("tags"), module.params.get("purge_tags") |
| 1171 |
) |
| 1172 |
|
| 1173 |
msg = f"Object copied from bucket {src_bucket} to bucket {bucket}." |
| 1174 |
return changed, {"msg": msg, "tags": tags} |
| 1175 |
|
| 1176 |
|
| 1177 |
def do_s3_object_copy(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None: |
| 1178 |
copy_src = module.params.get("copy_src") |
| 1179 |
if not copy_src.get("object") and s3_vars["object"]: |
| 1180 |
module.fail_json( |
| 1181 |
msg="A destination object was specified while trying to copy all the objects from the source bucket." |
| 1182 |
) |
| 1183 |
src_bucket = copy_src.get("bucket") |
| 1184 |
if not copy_src.get("object"): |
| 1185 |
# copy recursively object(s) from source bucket to destination bucket |
| 1186 |
# list all the objects from the source bucket |
| 1187 |
keys = list_bucket_object_keys(connection, src_bucket, prefix=copy_src.get("prefix")) |
| 1188 |
if len(keys) == 0: |
| 1189 |
module.exit_json(msg=f"No object found to be copied from source bucket {src_bucket}.") |
| 1190 |
|
| 1191 |
changed = False |
| 1192 |
number_keys_updated = 0 |
| 1193 |
for key in keys: |
| 1194 |
updated, result = copy_object_to_bucket( |
| 1195 |
module, |
| 1196 |
connection, |
| 1197 |
s3_vars["bucket"], |
| 1198 |
key, |
| 1199 |
s3_vars["encrypt"], |
| 1200 |
s3_vars["metadata"], |
| 1201 |
s3_vars["validate"], |
| 1202 |
src_bucket, |
| 1203 |
key, |
| 1204 |
versionId=copy_src.get("version_id"), |
| 1205 |
) |
| 1206 |
changed |= updated |
| 1207 |
number_keys_updated += 1 if updated else 0 |
| 1208 |
|
| 1209 |
msg = f"object(s) from buckets '{src_bucket}' and '{s3_vars['bucket']}' are the same." |
| 1210 |
if number_keys_updated: |
| 1211 |
msg = f"{number_keys_updated} copied into bucket '{s3_vars['bucket']}'" |
| 1212 |
module.exit_json(changed=changed, msg=msg) |
| 1213 |
else: |
| 1214 |
# copy single object from source bucket into destination bucket |
| 1215 |
changed, result = copy_object_to_bucket( |
| 1216 |
module, |
| 1217 |
connection, |
| 1218 |
s3_vars["bucket"], |
| 1219 |
s3_vars["object"], |
| 1220 |
s3_vars["encrypt"], |
| 1221 |
s3_vars["metadata"], |
| 1222 |
s3_vars["validate"], |
| 1223 |
src_bucket, |
| 1224 |
copy_src.get("object"), |
| 1225 |
versionId=copy_src.get("version_id"), |
| 1226 |
) |
| 1227 |
module.exit_json(changed=changed, **result) |
| 1228 |
|
| 1229 |
|
| 1230 |
def populate_params(module: AnsibleAWSModule) -> Dict: |
| 1231 |
# Copy the parameters dict, we shouldn't be directly modifying it. |
| 1232 |
variable_dict = copy.deepcopy(module.params) |
| 1233 |
|
| 1234 |
if variable_dict["validate_bucket_name"]: |
| 1235 |
validate_bucket_name(variable_dict["bucket"]) |
| 1236 |
|
| 1237 |
if variable_dict.get("overwrite") == "different" and not HAS_MD5: |
| 1238 |
module.fail_json(msg="overwrite=different is unavailable: ETag calculation requires MD5 support") |
| 1239 |
|
| 1240 |
if variable_dict.get("overwrite") not in [ |
| 1241 |
"always", |
| 1242 |
"never", |
| 1243 |
"different", |
| 1244 |
"latest", |
| 1245 |
]: |
| 1246 |
if module.boolean(variable_dict["overwrite"]): |
| 1247 |
variable_dict["overwrite"] = "always" |
| 1248 |
else: |
| 1249 |
variable_dict["overwrite"] = "never" |
| 1250 |
|
| 1251 |
# Bucket deletion does not require obj. Prevents ambiguity with delobj. |
| 1252 |
if variable_dict["object"]: |
| 1253 |
if variable_dict.get("mode") == "delete": |
| 1254 |
module.fail_json(msg="Parameter object cannot be used with mode=delete") |
| 1255 |
obj = variable_dict["object"] |
| 1256 |
if obj.startswith("/"): |
| 1257 |
module.fail_json( |
| 1258 |
msg="Parameter 'object' should not start with a leading '/'. See https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html" |
| 1259 |
) |
| 1260 |
|
| 1261 |
variable_dict["validate"] = not variable_dict["ignore_nonexistent_bucket"] |
| 1262 |
variable_dict["acl_disabled"] = False |
| 1263 |
|
| 1264 |
return variable_dict |
| 1265 |
|
| 1266 |
|
| 1267 |
def validate_bucket(module: AnsibleAWSModule, s3: ClientType, var_dict: Dict) -> Dict: |
| 1268 |
bucket_check(module, s3, var_dict["bucket"], validate=var_dict["validate"]) |
| 1269 |
|
| 1270 |
try: |
| 1271 |
ownership_controls = get_s3_bucket_ownership_controls(s3, var_dict["bucket"]) |
| 1272 |
if ownership_controls and ownership_controls.get("Rules"): |
| 1273 |
object_ownership = ownership_controls["Rules"][0]["ObjectOwnership"] |
| 1274 |
if object_ownership == "BucketOwnerEnforced": |
| 1275 |
var_dict["acl_disabled"] = True |
| 1276 |
except AnsibleS3Error: |
| 1277 |
# Bucket ownership controls not found or not accessible |
| 1278 |
pass |
| 1279 |
|
| 1280 |
if not var_dict["acl_disabled"]: |
| 1281 |
var_dict["object_acl"] = list(var_dict.get("permission")) |
| 1282 |
|
| 1283 |
return var_dict |
| 1284 |
|
| 1285 |
|
| 1286 |
def main(): |
| 1287 |
# Beware: this module uses an action plugin (plugins/action/s3_object.py) |
| 1288 |
# so that src parameter can be either in 'files/' lookup path on the |
| 1289 |
# controller, *or* on the remote host that the task is executed on. |
| 1290 |
|
| 1291 |
valid_modes = ["get", "put", "create", "geturl", "getstr", "delobj", "list", "copy"] |
| 1292 |
valid_acls = [ |
| 1293 |
"private", |
| 1294 |
"public-read", |
| 1295 |
"public-read-write", |
| 1296 |
"aws-exec-read", |
| 1297 |
"authenticated-read", |
| 1298 |
"bucket-owner-read", |
| 1299 |
"bucket-owner-full-control", |
| 1300 |
] |
| 1301 |
|
| 1302 |
argument_spec = dict( |
| 1303 |
bucket=dict(required=True), |
| 1304 |
dest=dict(default=None, type="path"), |
| 1305 |
encrypt=dict(default=True, type="bool"), |
| 1306 |
encryption_mode=dict(choices=["AES256", "aws:kms"], default="AES256"), |
| 1307 |
expiry=dict(default=600, type="int", aliases=["expiration"]), |
| 1308 |
headers=dict(type="dict"), |
| 1309 |
marker=dict(), |
| 1310 |
max_keys=dict(type="int", no_log=False), |
| 1311 |
metadata=dict(type="dict"), |
| 1312 |
mode=dict(choices=valid_modes, required=True), |
| 1313 |
sig_v4=dict(default=True, type="bool"), |
| 1314 |
object=dict(), |
| 1315 |
permission=dict(type="list", elements="str", default=["private"], choices=valid_acls), |
| 1316 |
version=dict(default=None), |
| 1317 |
overwrite=dict(aliases=["force"], default="different"), |
| 1318 |
prefix=dict(default=""), |
| 1319 |
retries=dict(aliases=["retry"], type="int", default=0), |
| 1320 |
dualstack=dict(default=False, type="bool"), |
| 1321 |
ceph=dict(default=False, type="bool", aliases=["rgw"]), |
| 1322 |
src=dict(type="path"), |
| 1323 |
content=dict(), |
| 1324 |
content_base64=dict(), |
| 1325 |
ignore_nonexistent_bucket=dict(default=False, type="bool"), |
| 1326 |
encryption_kms_key_id=dict(), |
| 1327 |
tags=dict(type="dict", aliases=["resource_tags"]), |
| 1328 |
purge_tags=dict(type="bool", default=True), |
| 1329 |
copy_src=dict( |
| 1330 |
type="dict", |
| 1331 |
options=dict( |
| 1332 |
bucket=dict(required=True), |
| 1333 |
object=dict(), |
| 1334 |
prefix=dict(default=""), |
| 1335 |
version_id=dict(), |
| 1336 |
), |
| 1337 |
), |
| 1338 |
validate_bucket_name=dict(type="bool", default=True), |
| 1339 |
expected_bucket_owner=dict(type="str"), |
| 1340 |
) |
| 1341 |
|
| 1342 |
required_if = [ |
| 1343 |
["ceph", True, ["endpoint_url"]], |
| 1344 |
["mode", "put", ["object"]], |
| 1345 |
["mode", "put", ["content", "content_base64", "src"], True], |
| 1346 |
["mode", "create", ["object"]], |
| 1347 |
["mode", "get", ["dest", "object"]], |
| 1348 |
["mode", "getstr", ["object"]], |
| 1349 |
["mode", "geturl", ["object"]], |
| 1350 |
["mode", "copy", ["copy_src"]], |
| 1351 |
["mode", "delobj", ["object"]], |
| 1352 |
] |
| 1353 |
|
| 1354 |
module = AnsibleAWSModule( |
| 1355 |
argument_spec=argument_spec, |
| 1356 |
supports_check_mode=True, |
| 1357 |
required_if=required_if, |
| 1358 |
mutually_exclusive=[["content", "content_base64", "src"]], |
| 1359 |
) |
| 1360 |
|
| 1361 |
if module.params.get("mode") == "list": |
| 1362 |
module.deprecate( |
| 1363 |
( |
| 1364 |
"Support for 'list' mode has been deprecated and will be removed in a release after " |
| 1365 |
"2026-11-01. Please use the amazon.aws.s3_object_info module instead." |
| 1366 |
), |
| 1367 |
date="2026-11-01", |
| 1368 |
collection_name="amazon.aws", |
| 1369 |
) |
| 1370 |
|
| 1371 |
endpoint_url = module.params.get("endpoint_url") |
| 1372 |
dualstack = module.params.get("dualstack") |
| 1373 |
|
| 1374 |
if dualstack and endpoint_url: |
| 1375 |
module.deprecate( |
| 1376 |
( |
| 1377 |
"Support for passing both the 'dualstack' and 'endpoint_url' parameters at the same " |
| 1378 |
"time has been deprecated." |
| 1379 |
), |
| 1380 |
date="2024-12-01", |
| 1381 |
collection_name="amazon.aws", |
| 1382 |
) |
| 1383 |
if "amazonaws.com" not in endpoint_url: |
| 1384 |
module.fail_json(msg="dualstack only applies to AWS S3") |
| 1385 |
|
| 1386 |
if module.params.get("overwrite") not in ("always", "never", "different", "latest"): |
| 1387 |
module.deprecate( |
| 1388 |
( |
| 1389 |
"Support for passing values of 'overwrite' other than 'always', 'never', " |
| 1390 |
"'different' or 'latest', has been deprecated." |
| 1391 |
), |
| 1392 |
date="2024-12-01", |
| 1393 |
collection_name="amazon.aws", |
| 1394 |
) |
| 1395 |
|
| 1396 |
extra_params = s3_extra_params(module.params, sigv4=False) |
| 1397 |
extra_params_v4 = s3_extra_params(module.params, sigv4=True) |
| 1398 |
retry_decorator = AWSRetry.jittered_backoff() |
| 1399 |
s3 = module.client("s3", retry_decorator=retry_decorator, **extra_params) |
| 1400 |
s3_v4 = module.client("s3", retry_decorator=retry_decorator, **extra_params_v4) |
| 1401 |
|
| 1402 |
s3_object_params = populate_params(module) |
| 1403 |
s3_object_params.update(validate_bucket(module, s3, s3_object_params)) |
| 1404 |
|
| 1405 |
# Conditions that force the use of Sig V4 |
| 1406 |
if module.params.get("sig_v4"): |
| 1407 |
s3 = s3_v4 |
| 1408 |
if module.params.get("encryption_mode") == "aws:kms": |
| 1409 |
s3 = s3_v4 |
| 1410 |
|
| 1411 |
func_mapping = { |
| 1412 |
"get": do_s3_object_get, |
| 1413 |
"put": do_s3_object_put, |
| 1414 |
"delobj": do_s3_object_delobj, |
| 1415 |
"list": do_s3_object_list, |
| 1416 |
"create": do_s3_object_create, |
| 1417 |
"geturl": do_s3_object_geturl, |
| 1418 |
"getstr": do_s3_object_getstr, |
| 1419 |
"copy": do_s3_object_copy, |
| 1420 |
} |
| 1421 |
func = func_mapping[s3_object_params["mode"]] |
| 1422 |
try: |
| 1423 |
try: |
| 1424 |
func(module, s3, s3_object_params) |
| 1425 |
except AnsibleS3Sigv4RequiredError: |
| 1426 |
# Opportunistically bump the connection up to SigV4 |
| 1427 |
func(module, s3_v4, s3_object_params) |
| 1428 |
except AnsibleS3Error as e: |
| 1429 |
module.fail_json_aws_error(e) |
| 1430 |
|
| 1431 |
module.exit_json(failed=False) |
| 1432 |
|
| 1433 |
|
| 1434 |
if __name__ == "__main__": |
| 1435 |
main() |