| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
--- |
| 9 |
module: s3_lifecycle |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: Manage S3 bucket lifecycle rules in AWS |
| 12 |
description: |
| 13 |
- Manage S3 bucket lifecycle rules in AWS. |
| 14 |
author: |
| 15 |
- "Rob White (@wimnat)" |
| 16 |
notes: |
| 17 |
- If specifying expiration time as days then transition time must also be specified in days. |
| 18 |
- If specifying expiration time as a date then transition time must also be specified as a date. |
| 19 |
options: |
| 20 |
name: |
| 21 |
description: |
| 22 |
- Name of the S3 bucket. |
| 23 |
required: true |
| 24 |
type: str |
| 25 |
abort_incomplete_multipart_upload_days: |
| 26 |
description: |
| 27 |
- Specifies the days since the initiation of an incomplete multipart upload that Amazon S3 will wait before permanently removing all parts of the upload. |
| 28 |
type: int |
| 29 |
version_added: 2.2.0 |
| 30 |
expiration_date: |
| 31 |
description: |
| 32 |
- Indicates the lifetime of the objects that are subject to the rule by the date they will expire. |
| 33 |
- The value must be ISO-8601 format, the time must be midnight and a GMT timezone must be specified. |
| 34 |
- This cannot be specified with I(expire_object_delete_marker) |
| 35 |
type: str |
| 36 |
expiration_days: |
| 37 |
description: |
| 38 |
- Indicates the lifetime, in days, of the objects that are subject to the rule. |
| 39 |
- The value must be a non-zero positive integer. |
| 40 |
- This cannot be specified with I(expire_object_delete_marker) |
| 41 |
type: int |
| 42 |
expire_object_delete_marker: |
| 43 |
description: |
| 44 |
- Indicates whether Amazon S3 will remove a delete marker with no noncurrent versions. |
| 45 |
- If set to C(true), the delete marker will be expired; if set to C(false) the policy takes no action. |
| 46 |
- This cannot be specified with I(expiration_days) or I(expiration_date). |
| 47 |
type: bool |
| 48 |
version_added: 2.2.0 |
| 49 |
prefix: |
| 50 |
description: |
| 51 |
- Prefix identifying one or more objects to which the rule applies. |
| 52 |
- If no prefix is specified, the rule will apply to the whole bucket. |
| 53 |
type: str |
| 54 |
purge_transitions: |
| 55 |
description: |
| 56 |
- Whether to replace all the current transition(s) with the new transition(s). |
| 57 |
- When C(false), the provided transition(s) will be added, replacing transitions |
| 58 |
with the same storage_class. When true, existing transitions will be removed |
| 59 |
and replaced with the new transition(s) |
| 60 |
default: true |
| 61 |
type: bool |
| 62 |
maximum_object_size: |
| 63 |
description: |
| 64 |
- The maximum object size to which the rule applies. |
| 65 |
required: false |
| 66 |
type: int |
| 67 |
version_added: 9.1.0 |
| 68 |
minimum_object_size: |
| 69 |
description: |
| 70 |
- The minimum object size to which the rule applies. |
| 71 |
required: false |
| 72 |
version_added: 9.1.0 |
| 73 |
type: int |
| 74 |
noncurrent_version_expiration_days: |
| 75 |
description: |
| 76 |
- The number of days after which non-current versions should be deleted. |
| 77 |
- Must be set if I(noncurrent_version_keep_newer) is set. |
| 78 |
required: false |
| 79 |
type: int |
| 80 |
noncurrent_version_keep_newer: |
| 81 |
description: |
| 82 |
- The minimum number of non-current versions to retain. |
| 83 |
- Requres I(noncurrent_version_expiration_days). |
| 84 |
required: false |
| 85 |
type: int |
| 86 |
version_added: 5.3.0 |
| 87 |
noncurrent_version_storage_class: |
| 88 |
description: |
| 89 |
- The storage class to which non-current versions are transitioned. |
| 90 |
default: glacier |
| 91 |
choices: ['glacier', 'onezone_ia', 'standard_ia', 'intelligent_tiering', 'deep_archive'] |
| 92 |
required: false |
| 93 |
type: str |
| 94 |
noncurrent_version_transition_days: |
| 95 |
description: |
| 96 |
- The number of days after which non-current versions will be transitioned |
| 97 |
to the storage class specified in I(noncurrent_version_storage_class). |
| 98 |
required: false |
| 99 |
type: int |
| 100 |
noncurrent_version_transitions: |
| 101 |
description: |
| 102 |
- A list of transition behaviors to be applied to noncurrent versions for the rule. |
| 103 |
- Each storage class may be used only once. Each transition behavior contains these elements |
| 104 |
I(transition_days) |
| 105 |
I(storage_class) |
| 106 |
type: list |
| 107 |
elements: dict |
| 108 |
rule_id: |
| 109 |
description: |
| 110 |
- Unique identifier for the rule. |
| 111 |
- The value cannot be longer than 255 characters. |
| 112 |
- A unique value for the rule will be generated if no value is provided. |
| 113 |
type: str |
| 114 |
state: |
| 115 |
description: |
| 116 |
- Create or remove the lifecycle rule. |
| 117 |
default: present |
| 118 |
choices: [ 'present', 'absent' ] |
| 119 |
type: str |
| 120 |
status: |
| 121 |
description: |
| 122 |
- If C(enabled), the rule is currently being applied. |
| 123 |
- If C(disabled), the rule is not currently being applied. |
| 124 |
default: enabled |
| 125 |
choices: [ 'enabled', 'disabled' ] |
| 126 |
type: str |
| 127 |
storage_class: |
| 128 |
description: |
| 129 |
- The storage class to transition to. |
| 130 |
default: glacier |
| 131 |
choices: [ 'glacier', 'onezone_ia', 'standard_ia', 'intelligent_tiering', 'deep_archive'] |
| 132 |
type: str |
| 133 |
transition_date: |
| 134 |
description: |
| 135 |
- Indicates the lifetime of the objects that are subject to the rule by the date they |
| 136 |
will transition to a different storage class. |
| 137 |
- The value must be ISO-8601 format, the time must be midnight and a GMT timezone must |
| 138 |
be specified. |
| 139 |
- If (transition_days) is not specified, this parameter is required. |
| 140 |
type: str |
| 141 |
transition_days: |
| 142 |
description: |
| 143 |
- Indicates when, in days, an object transitions to a different storage class. |
| 144 |
- If I(transition_date) is not specified, this parameter is required. |
| 145 |
type: int |
| 146 |
transitions: |
| 147 |
description: |
| 148 |
- A list of transition behaviors to be applied to the rule. |
| 149 |
- Each storage class may be used only once. Each transition behavior may contain these elements |
| 150 |
I(transition_days) |
| 151 |
I(transition_date) |
| 152 |
I(storage_class) |
| 153 |
type: list |
| 154 |
elements: dict |
| 155 |
wait: |
| 156 |
description: |
| 157 |
- Wait for the configuration to complete before returning. |
| 158 |
version_added: 1.5.0 |
| 159 |
type: bool |
| 160 |
default: false |
| 161 |
extends_documentation_fragment: |
| 162 |
- amazon.aws.common.modules |
| 163 |
- amazon.aws.region.modules |
| 164 |
- amazon.aws.boto3 |
| 165 |
""" |
| 166 |
|
| 167 |
RETURN = r""" # """ |
| 168 |
|
| 169 |
EXAMPLES = r""" |
| 170 |
# Note: These examples do not set authentication details, see the AWS Guide for details. |
| 171 |
|
| 172 |
- name: Configure a lifecycle rule on a bucket to expire (delete) items with a prefix of /logs/ after 30 days |
| 173 |
community.aws.s3_lifecycle: |
| 174 |
name: mybucket |
| 175 |
expiration_days: 30 |
| 176 |
prefix: logs/ |
| 177 |
status: enabled |
| 178 |
state: present |
| 179 |
|
| 180 |
- name: Configure a lifecycle rule to transition all items with a prefix of /logs/ to glacier after 7 days and then delete after 90 days |
| 181 |
community.aws.s3_lifecycle: |
| 182 |
name: mybucket |
| 183 |
transition_days: 7 |
| 184 |
expiration_days: 90 |
| 185 |
prefix: logs/ |
| 186 |
status: enabled |
| 187 |
state: present |
| 188 |
|
| 189 |
# Note that midnight GMT must be specified. |
| 190 |
# Be sure to quote your date strings |
| 191 |
- name: Configure a lifecycle rule to transition all items with a prefix of /logs/ to glacier on 31 Dec 2020 and then delete on 31 Dec 2030. |
| 192 |
community.aws.s3_lifecycle: |
| 193 |
name: mybucket |
| 194 |
transition_date: "2020-12-30T00:00:00.000Z" |
| 195 |
expiration_date: "2030-12-30T00:00:00.000Z" |
| 196 |
prefix: logs/ |
| 197 |
status: enabled |
| 198 |
state: present |
| 199 |
|
| 200 |
- name: Disable the rule created above |
| 201 |
community.aws.s3_lifecycle: |
| 202 |
name: mybucket |
| 203 |
prefix: logs/ |
| 204 |
status: disabled |
| 205 |
state: present |
| 206 |
|
| 207 |
- name: Delete the lifecycle rule created above |
| 208 |
community.aws.s3_lifecycle: |
| 209 |
name: mybucket |
| 210 |
prefix: logs/ |
| 211 |
state: absent |
| 212 |
|
| 213 |
- name: Configure a lifecycle rule to transition all backup files older than 31 days in /backups/ to standard infrequent access class. |
| 214 |
community.aws.s3_lifecycle: |
| 215 |
name: mybucket |
| 216 |
prefix: backups/ |
| 217 |
storage_class: standard_ia |
| 218 |
transition_days: 31 |
| 219 |
state: present |
| 220 |
status: enabled |
| 221 |
|
| 222 |
- name: Configure a lifecycle rule to transition files to infrequent access after 30 days and glacier after 90 |
| 223 |
community.aws.s3_lifecycle: |
| 224 |
name: mybucket |
| 225 |
prefix: logs/ |
| 226 |
state: present |
| 227 |
status: enabled |
| 228 |
transitions: |
| 229 |
- transition_days: 30 |
| 230 |
storage_class: standard_ia |
| 231 |
- transition_days: 90 |
| 232 |
storage_class: glacier |
| 233 |
""" |
| 234 |
|
| 235 |
import datetime |
| 236 |
import time |
| 237 |
from copy import deepcopy |
| 238 |
|
| 239 |
try: |
| 240 |
from dateutil import parser as date_parser |
| 241 |
|
| 242 |
HAS_DATEUTIL = True |
| 243 |
except ImportError: |
| 244 |
HAS_DATEUTIL = False |
| 245 |
|
| 246 |
try: |
| 247 |
import botocore |
| 248 |
except ImportError: |
| 249 |
pass # handled by AnsibleAwsModule |
| 250 |
|
| 251 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 252 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_message |
| 253 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import normalize_boto3_result |
| 254 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 255 |
|
| 256 |
from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule |
| 257 |
|
| 258 |
|
| 259 |
def parse_date(date): |
| 260 |
if date is None: |
| 261 |
return None |
| 262 |
try: |
| 263 |
if HAS_DATEUTIL: |
| 264 |
return date_parser.parse(date) |
| 265 |
else: |
| 266 |
# Very simplistic |
| 267 |
return datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.000Z") |
| 268 |
except ValueError: |
| 269 |
return None |
| 270 |
|
| 271 |
|
| 272 |
def fetch_rules(client, module, name): |
| 273 |
# Get the bucket's current lifecycle rules |
| 274 |
try: |
| 275 |
current_lifecycle = client.get_bucket_lifecycle_configuration(aws_retry=True, Bucket=name) |
| 276 |
current_lifecycle_rules = normalize_boto3_result(current_lifecycle["Rules"]) |
| 277 |
except is_boto3_error_code("NoSuchLifecycleConfiguration"): |
| 278 |
current_lifecycle_rules = [] |
| 279 |
except ( |
| 280 |
botocore.exceptions.ClientError, |
| 281 |
botocore.exceptions.BotoCoreError, |
| 282 |
) as e: # pylint: disable=duplicate-except |
| 283 |
module.fail_json_aws(e) |
| 284 |
return current_lifecycle_rules |
| 285 |
|
| 286 |
|
| 287 |
# Helper function to deeply compare filters |
| 288 |
def filters_are_equal(filter1, filter2): |
| 289 |
if filter1 == filter2: |
| 290 |
return True |
| 291 |
if not filter1 or not filter2: |
| 292 |
return False |
| 293 |
# Treat empty string as equal to a filter not being set |
| 294 |
return ( |
| 295 |
filter1.get("Prefix", "") == filter2.get("Prefix", "") |
| 296 |
and filter1.get("ObjectSizeGreaterThan") == filter2.get("ObjectSizeGreaterThan") |
| 297 |
and filter1.get("ObjectSizeLessThan") == filter2.get("ObjectSizeLessThan") |
| 298 |
and filter1.get("And", {}).get("Prefix", "") == filter2.get("And", {}).get("Prefix", "") |
| 299 |
and filter1.get("And", {}).get("ObjectSizeGreaterThan") == filter2.get("And", {}).get("ObjectSizeGreaterThan") |
| 300 |
and filter1.get("And", {}).get("ObjectSizeLessThan") == filter2.get("And", {}).get("ObjectSizeLessThan") |
| 301 |
) |
| 302 |
|
| 303 |
|
| 304 |
def build_rule(client, module): |
| 305 |
abort_incomplete_multipart_upload_days = module.params.get("abort_incomplete_multipart_upload_days") |
| 306 |
expiration_date = parse_date(module.params.get("expiration_date")) |
| 307 |
expiration_days = module.params.get("expiration_days") |
| 308 |
expire_object_delete_marker = module.params.get("expire_object_delete_marker") |
| 309 |
maximum_object_size = module.params.get("maximum_object_size") |
| 310 |
minimum_object_size = module.params.get("minimum_object_size") |
| 311 |
noncurrent_version_expiration_days = module.params.get("noncurrent_version_expiration_days") |
| 312 |
noncurrent_version_transition_days = module.params.get("noncurrent_version_transition_days") |
| 313 |
noncurrent_version_transitions = module.params.get("noncurrent_version_transitions") |
| 314 |
noncurrent_version_storage_class = module.params.get("noncurrent_version_storage_class") |
| 315 |
noncurrent_version_keep_newer = module.params.get("noncurrent_version_keep_newer") |
| 316 |
prefix = module.params.get("prefix") or "" |
| 317 |
rule_id = module.params.get("rule_id") |
| 318 |
status = module.params.get("status") |
| 319 |
storage_class = module.params.get("storage_class") |
| 320 |
transition_date = parse_date(module.params.get("transition_date")) |
| 321 |
transition_days = module.params.get("transition_days") |
| 322 |
transitions = module.params.get("transitions") |
| 323 |
|
| 324 |
if maximum_object_size is not None or minimum_object_size is not None: |
| 325 |
and_dict = dict(Prefix=prefix) |
| 326 |
if minimum_object_size is not None: |
| 327 |
and_dict["ObjectSizeGreaterThan"] = minimum_object_size |
| 328 |
if maximum_object_size is not None: |
| 329 |
and_dict["ObjectSizeLessThan"] = maximum_object_size |
| 330 |
rule = dict(Filter=dict(And=and_dict), Status=status.title()) |
| 331 |
else: |
| 332 |
rule = dict(Filter=dict(Prefix=prefix), Status=status.title()) |
| 333 |
if rule_id is not None: |
| 334 |
rule["ID"] = rule_id |
| 335 |
|
| 336 |
if abort_incomplete_multipart_upload_days: |
| 337 |
rule["AbortIncompleteMultipartUpload"] = {"DaysAfterInitiation": abort_incomplete_multipart_upload_days} |
| 338 |
|
| 339 |
# Create expiration |
| 340 |
if expiration_days is not None: |
| 341 |
rule["Expiration"] = dict(Days=expiration_days) |
| 342 |
elif expiration_date is not None: |
| 343 |
rule["Expiration"] = dict(Date=expiration_date.isoformat()) |
| 344 |
elif expire_object_delete_marker is not None: |
| 345 |
rule["Expiration"] = dict(ExpiredObjectDeleteMarker=expire_object_delete_marker) |
| 346 |
if noncurrent_version_expiration_days or noncurrent_version_keep_newer: |
| 347 |
rule["NoncurrentVersionExpiration"] = dict() |
| 348 |
if noncurrent_version_expiration_days is not None: |
| 349 |
rule["NoncurrentVersionExpiration"]["NoncurrentDays"] = noncurrent_version_expiration_days |
| 350 |
if noncurrent_version_keep_newer is not None: |
| 351 |
rule["NoncurrentVersionExpiration"]["NewerNoncurrentVersions"] = noncurrent_version_keep_newer |
| 352 |
if transition_days is not None: |
| 353 |
rule["Transitions"] = [ |
| 354 |
dict(Days=transition_days, StorageClass=storage_class.upper()), |
| 355 |
] |
| 356 |
|
| 357 |
elif transition_date is not None: |
| 358 |
rule["Transitions"] = [ |
| 359 |
dict(Date=transition_date.isoformat(), StorageClass=storage_class.upper()), |
| 360 |
] |
| 361 |
|
| 362 |
if transitions is not None: |
| 363 |
if not rule.get("Transitions"): |
| 364 |
rule["Transitions"] = [] |
| 365 |
for transition in transitions: |
| 366 |
t_out = dict() |
| 367 |
if transition.get("transition_date"): |
| 368 |
t_out["Date"] = transition["transition_date"] |
| 369 |
elif transition.get("transition_days") is not None: |
| 370 |
t_out["Days"] = int(transition["transition_days"]) |
| 371 |
if transition.get("storage_class"): |
| 372 |
t_out["StorageClass"] = transition["storage_class"].upper() |
| 373 |
rule["Transitions"].append(t_out) |
| 374 |
|
| 375 |
if noncurrent_version_transition_days is not None: |
| 376 |
rule["NoncurrentVersionTransitions"] = [ |
| 377 |
dict( |
| 378 |
NoncurrentDays=noncurrent_version_transition_days, StorageClass=noncurrent_version_storage_class.upper() |
| 379 |
), |
| 380 |
] |
| 381 |
|
| 382 |
if noncurrent_version_transitions is not None: |
| 383 |
if not rule.get("NoncurrentVersionTransitions"): |
| 384 |
rule["NoncurrentVersionTransitions"] = [] |
| 385 |
for noncurrent_version_transition in noncurrent_version_transitions: |
| 386 |
t_out = dict() |
| 387 |
t_out["NoncurrentDays"] = noncurrent_version_transition["transition_days"] |
| 388 |
if noncurrent_version_transition.get("storage_class"): |
| 389 |
t_out["StorageClass"] = noncurrent_version_transition["storage_class"].upper() |
| 390 |
rule["NoncurrentVersionTransitions"].append(t_out) |
| 391 |
|
| 392 |
return rule |
| 393 |
|
| 394 |
|
| 395 |
def compare_and_update_configuration(client, module, current_lifecycle_rules, rule): |
| 396 |
purge_transitions = module.params.get("purge_transitions") |
| 397 |
rule_id = module.params.get("rule_id") |
| 398 |
|
| 399 |
lifecycle_configuration = dict(Rules=[]) |
| 400 |
changed = False |
| 401 |
appended = False |
| 402 |
# If current_lifecycle_obj is not None then we have rules to compare, otherwise just add the rule |
| 403 |
if current_lifecycle_rules: |
| 404 |
# If rule ID exists, use that for comparison otherwise compare based on prefix |
| 405 |
for existing_rule in current_lifecycle_rules: |
| 406 |
if rule.get("ID") == existing_rule.get("ID") and not filters_are_equal( |
| 407 |
rule.get("Filter"), existing_rule.get("Filter") |
| 408 |
): |
| 409 |
existing_rule.pop("ID") |
| 410 |
elif rule_id is None and filters_are_equal(rule.get("Filter"), existing_rule.get("Filter")): |
| 411 |
existing_rule.pop("ID") |
| 412 |
if rule.get("ID") == existing_rule.get("ID"): |
| 413 |
changed_, appended_ = update_or_append_rule( |
| 414 |
rule, existing_rule, purge_transitions, lifecycle_configuration |
| 415 |
) |
| 416 |
changed = changed_ or changed |
| 417 |
appended = appended_ or appended |
| 418 |
else: |
| 419 |
lifecycle_configuration["Rules"].append(existing_rule) |
| 420 |
|
| 421 |
# If nothing appended then append now as the rule must not exist |
| 422 |
if not appended: |
| 423 |
lifecycle_configuration["Rules"].append(rule) |
| 424 |
changed = True |
| 425 |
else: |
| 426 |
lifecycle_configuration["Rules"].append(rule) |
| 427 |
changed = True |
| 428 |
|
| 429 |
return changed, lifecycle_configuration |
| 430 |
|
| 431 |
|
| 432 |
def update_or_append_rule(new_rule, existing_rule, purge_transitions, lifecycle_obj): |
| 433 |
changed = False |
| 434 |
if existing_rule["Status"] != new_rule["Status"]: |
| 435 |
if not new_rule.get("Transitions") and existing_rule.get("Transitions"): |
| 436 |
new_rule["Transitions"] = existing_rule["Transitions"] |
| 437 |
if not new_rule.get("Expiration") and existing_rule.get("Expiration"): |
| 438 |
new_rule["Expiration"] = existing_rule["Expiration"] |
| 439 |
if not new_rule.get("NoncurrentVersionExpiration") and existing_rule.get("NoncurrentVersionExpiration"): |
| 440 |
new_rule["NoncurrentVersionExpiration"] = existing_rule["NoncurrentVersionExpiration"] |
| 441 |
lifecycle_obj["Rules"].append(new_rule) |
| 442 |
changed = True |
| 443 |
appended = True |
| 444 |
else: |
| 445 |
if not purge_transitions: |
| 446 |
merge_transitions(new_rule, existing_rule) |
| 447 |
if compare_rule(new_rule, existing_rule, purge_transitions): |
| 448 |
lifecycle_obj["Rules"].append(new_rule) |
| 449 |
appended = True |
| 450 |
else: |
| 451 |
lifecycle_obj["Rules"].append(new_rule) |
| 452 |
changed = True |
| 453 |
appended = True |
| 454 |
return changed, appended |
| 455 |
|
| 456 |
|
| 457 |
def compare_and_remove_rule(current_lifecycle_rules, rule_id=None, prefix=None): |
| 458 |
changed = False |
| 459 |
lifecycle_configuration = dict(Rules=[]) |
| 460 |
|
| 461 |
# Check if rule exists |
| 462 |
# If an ID exists, use that otherwise compare based on prefix |
| 463 |
if rule_id is not None: |
| 464 |
for existing_rule in current_lifecycle_rules: |
| 465 |
if rule_id == existing_rule["ID"]: |
| 466 |
# We're not keeping the rule (i.e. deleting) so mark as changed |
| 467 |
changed = True |
| 468 |
else: |
| 469 |
lifecycle_configuration["Rules"].append(existing_rule) |
| 470 |
else: |
| 471 |
for existing_rule in current_lifecycle_rules: |
| 472 |
if prefix == existing_rule["Filter"].get("Prefix", ""): |
| 473 |
# We're not keeping the rule (i.e. deleting) so mark as changed |
| 474 |
changed = True |
| 475 |
else: |
| 476 |
lifecycle_configuration["Rules"].append(existing_rule) |
| 477 |
|
| 478 |
return changed, lifecycle_configuration |
| 479 |
|
| 480 |
|
| 481 |
def compare_rule(new_rule, old_rule, purge_transitions): |
| 482 |
# Copy objects |
| 483 |
rule1 = deepcopy(new_rule) |
| 484 |
rule2 = deepcopy(old_rule) |
| 485 |
|
| 486 |
if purge_transitions: |
| 487 |
return rule1 == rule2 |
| 488 |
else: |
| 489 |
transitions1 = rule1.pop("Transitions", []) |
| 490 |
transitions2 = rule2.pop("Transitions", []) |
| 491 |
noncurrent_transtions1 = rule1.pop("NoncurrentVersionTransitions", []) |
| 492 |
noncurrent_transtions2 = rule2.pop("NoncurrentVersionTransitions", []) |
| 493 |
if rule1 != rule2: |
| 494 |
return False |
| 495 |
for transition in transitions1: |
| 496 |
if transition not in transitions2: |
| 497 |
return False |
| 498 |
for transition in noncurrent_transtions1: |
| 499 |
if transition not in noncurrent_transtions2: |
| 500 |
return False |
| 501 |
return True |
| 502 |
|
| 503 |
|
| 504 |
def merge_transitions(updated_rule, updating_rule): |
| 505 |
# because of the legal S3 transitions, we know only one can exist for each storage class. |
| 506 |
# So, our strategy is build some dicts, keyed on storage class and add the storage class transitions that are only |
| 507 |
# in updating_rule to updated_rule |
| 508 |
updated_transitions = {} |
| 509 |
updating_transitions = {} |
| 510 |
for transition in updated_rule.get("Transitions", []): |
| 511 |
updated_transitions[transition["StorageClass"]] = transition |
| 512 |
for transition in updating_rule.get("Transitions", []): |
| 513 |
updating_transitions[transition["StorageClass"]] = transition |
| 514 |
for storage_class, transition in updating_transitions.items(): |
| 515 |
if updated_transitions.get(storage_class) is None: |
| 516 |
updated_rule["Transitions"].append(transition) |
| 517 |
|
| 518 |
|
| 519 |
def create_lifecycle_rule(client, module): |
| 520 |
name = module.params.get("name") |
| 521 |
wait = module.params.get("wait") |
| 522 |
changed = False |
| 523 |
|
| 524 |
old_lifecycle_rules = fetch_rules(client, module, name) |
| 525 |
new_rule = build_rule(client, module) |
| 526 |
(changed, lifecycle_configuration) = compare_and_update_configuration(client, module, old_lifecycle_rules, new_rule) |
| 527 |
if changed: |
| 528 |
# Write lifecycle to bucket |
| 529 |
try: |
| 530 |
client.put_bucket_lifecycle_configuration( |
| 531 |
aws_retry=True, Bucket=name, LifecycleConfiguration=lifecycle_configuration |
| 532 |
) |
| 533 |
except is_boto3_error_message("At least one action needs to be specified in a rule"): |
| 534 |
# Amazon interpreted this as not changing anything |
| 535 |
changed = False |
| 536 |
except ( |
| 537 |
botocore.exceptions.ClientError, |
| 538 |
botocore.exceptions.BotoCoreError, |
| 539 |
) as e: # pylint: disable=duplicate-except |
| 540 |
module.fail_json_aws( |
| 541 |
e, lifecycle_configuration=lifecycle_configuration, name=name, old_lifecycle_rules=old_lifecycle_rules |
| 542 |
) |
| 543 |
|
| 544 |
_changed = changed |
| 545 |
_retries = 10 |
| 546 |
_not_changed_cnt = 6 |
| 547 |
while wait and _changed and _retries and _not_changed_cnt: |
| 548 |
# We've seen examples where get_bucket_lifecycle_configuration returns |
| 549 |
# the updated rules, then the old rules, then the updated rules again and |
| 550 |
# again couple of times. |
| 551 |
# Thus try to read the rule few times in a row to check if it has changed. |
| 552 |
time.sleep(5) |
| 553 |
_retries -= 1 |
| 554 |
new_rules = fetch_rules(client, module, name) |
| 555 |
(_changed, lifecycle_configuration) = compare_and_update_configuration(client, module, new_rules, new_rule) |
| 556 |
if not _changed: |
| 557 |
_not_changed_cnt -= 1 |
| 558 |
_changed = True |
| 559 |
else: |
| 560 |
_not_changed_cnt = 6 |
| 561 |
else: |
| 562 |
_retries = 0 |
| 563 |
|
| 564 |
new_rules = fetch_rules(client, module, name) |
| 565 |
|
| 566 |
module.exit_json( |
| 567 |
changed=changed, |
| 568 |
new_rule=new_rule, |
| 569 |
rules=new_rules, |
| 570 |
old_rules=old_lifecycle_rules, |
| 571 |
_retries=_retries, |
| 572 |
_config=lifecycle_configuration, |
| 573 |
) |
| 574 |
|
| 575 |
|
| 576 |
def destroy_lifecycle_rule(client, module): |
| 577 |
name = module.params.get("name") |
| 578 |
prefix = module.params.get("prefix") |
| 579 |
rule_id = module.params.get("rule_id") |
| 580 |
wait = module.params.get("wait") |
| 581 |
changed = False |
| 582 |
|
| 583 |
if prefix is None: |
| 584 |
prefix = "" |
| 585 |
|
| 586 |
current_lifecycle_rules = fetch_rules(client, module, name) |
| 587 |
changed, lifecycle_obj = compare_and_remove_rule(current_lifecycle_rules, rule_id, prefix) |
| 588 |
|
| 589 |
if changed: |
| 590 |
# Write lifecycle to bucket or, if there no rules left, delete lifecycle configuration |
| 591 |
try: |
| 592 |
if lifecycle_obj["Rules"]: |
| 593 |
client.put_bucket_lifecycle_configuration( |
| 594 |
aws_retry=True, Bucket=name, LifecycleConfiguration=lifecycle_obj |
| 595 |
) |
| 596 |
elif current_lifecycle_rules: |
| 597 |
changed = True |
| 598 |
client.delete_bucket_lifecycle(aws_retry=True, Bucket=name) |
| 599 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 600 |
module.fail_json_aws(e) |
| 601 |
|
| 602 |
_changed = changed |
| 603 |
_retries = 10 |
| 604 |
_not_changed_cnt = 6 |
| 605 |
while wait and _changed and _retries and _not_changed_cnt: |
| 606 |
# We've seen examples where get_bucket_lifecycle_configuration returns |
| 607 |
# the updated rules, then the old rules, then the updated rules again and |
| 608 |
# again couple of times. |
| 609 |
# Thus try to read the rule few times in a row to check if it has changed. |
| 610 |
time.sleep(5) |
| 611 |
_retries -= 1 |
| 612 |
new_rules = fetch_rules(client, module, name) |
| 613 |
(_changed, lifecycle_configuration) = compare_and_remove_rule(new_rules, rule_id, prefix) |
| 614 |
if not _changed: |
| 615 |
_not_changed_cnt -= 1 |
| 616 |
_changed = True |
| 617 |
else: |
| 618 |
_not_changed_cnt = 6 |
| 619 |
else: |
| 620 |
_retries = 0 |
| 621 |
|
| 622 |
new_rules = fetch_rules(client, module, name) |
| 623 |
|
| 624 |
module.exit_json(changed=changed, rules=new_rules, old_rules=current_lifecycle_rules, _retries=_retries) |
| 625 |
|
| 626 |
|
| 627 |
def main(): |
| 628 |
s3_storage_class = ["glacier", "onezone_ia", "standard_ia", "intelligent_tiering", "deep_archive"] |
| 629 |
argument_spec = dict( |
| 630 |
name=dict(required=True, type="str"), |
| 631 |
abort_incomplete_multipart_upload_days=dict(type="int"), |
| 632 |
expiration_days=dict(type="int"), |
| 633 |
expiration_date=dict(), |
| 634 |
expire_object_delete_marker=dict(type="bool"), |
| 635 |
maximum_object_size=dict(type="int"), |
| 636 |
minimum_object_size=dict(type="int"), |
| 637 |
noncurrent_version_expiration_days=dict(type="int"), |
| 638 |
noncurrent_version_keep_newer=dict(type="int"), |
| 639 |
noncurrent_version_storage_class=dict(default="glacier", type="str", choices=s3_storage_class), |
| 640 |
noncurrent_version_transition_days=dict(type="int"), |
| 641 |
noncurrent_version_transitions=dict(type="list", elements="dict"), |
| 642 |
prefix=dict(), |
| 643 |
rule_id=dict(), |
| 644 |
state=dict(default="present", choices=["present", "absent"]), |
| 645 |
status=dict(default="enabled", choices=["enabled", "disabled"]), |
| 646 |
storage_class=dict(default="glacier", type="str", choices=s3_storage_class), |
| 647 |
transition_days=dict(type="int"), |
| 648 |
transition_date=dict(), |
| 649 |
transitions=dict(type="list", elements="dict"), |
| 650 |
purge_transitions=dict(default=True, type="bool"), |
| 651 |
wait=dict(type="bool", default=False), |
| 652 |
) |
| 653 |
|
| 654 |
module = AnsibleAWSModule( |
| 655 |
argument_spec=argument_spec, |
| 656 |
mutually_exclusive=[ |
| 657 |
["expiration_days", "expiration_date", "expire_object_delete_marker"], |
| 658 |
["expiration_days", "transition_date"], |
| 659 |
["transition_days", "transition_date"], |
| 660 |
["transition_days", "expiration_date"], |
| 661 |
["transition_days", "transitions"], |
| 662 |
["transition_date", "transitions"], |
| 663 |
["noncurrent_version_transition_days", "noncurrent_version_transitions"], |
| 664 |
], |
| 665 |
required_by={ |
| 666 |
"noncurrent_version_keep_newer": ["noncurrent_version_expiration_days"], |
| 667 |
}, |
| 668 |
) |
| 669 |
|
| 670 |
client = module.client("s3", retry_decorator=AWSRetry.jittered_backoff()) |
| 671 |
|
| 672 |
expiration_date = module.params.get("expiration_date") |
| 673 |
transition_date = module.params.get("transition_date") |
| 674 |
state = module.params.get("state") |
| 675 |
|
| 676 |
if state == "present" and module.params["status"] == "enabled": # allow deleting/disabling a rule by id/prefix |
| 677 |
required_when_present = ( |
| 678 |
"abort_incomplete_multipart_upload_days", |
| 679 |
"expiration_date", |
| 680 |
"expiration_days", |
| 681 |
"expire_object_delete_marker", |
| 682 |
"transition_date", |
| 683 |
"transition_days", |
| 684 |
"transitions", |
| 685 |
"noncurrent_version_expiration_days", |
| 686 |
"noncurrent_version_keep_newer", |
| 687 |
"noncurrent_version_transition_days", |
| 688 |
"noncurrent_version_transitions", |
| 689 |
) |
| 690 |
for param in required_when_present: |
| 691 |
if module.params.get(param) is None: |
| 692 |
break |
| 693 |
else: |
| 694 |
msg = f"one of the following is required when 'state' is 'present': {', '.join(required_when_present)}" |
| 695 |
module.fail_json(msg=msg) |
| 696 |
|
| 697 |
# If dates have been set, make sure they're in a valid format |
| 698 |
if expiration_date: |
| 699 |
expiration_date = parse_date(expiration_date) |
| 700 |
if expiration_date is None: |
| 701 |
module.fail_json( |
| 702 |
msg="expiration_date is not a valid ISO-8601 format." |
| 703 |
" The time must be midnight and a timezone of GMT must be included" |
| 704 |
) |
| 705 |
if transition_date: |
| 706 |
transition_date = parse_date(transition_date) |
| 707 |
if transition_date is None: |
| 708 |
module.fail_json( |
| 709 |
msg="transition_date is not a valid ISO-8601 format." |
| 710 |
" The time must be midnight and a timezone of GMT must be included" |
| 711 |
) |
| 712 |
|
| 713 |
if state == "present": |
| 714 |
create_lifecycle_rule(client, module) |
| 715 |
elif state == "absent": |
| 716 |
destroy_lifecycle_rule(client, module) |
| 717 |
|
| 718 |
|
| 719 |
if __name__ == "__main__": |
| 720 |
main() |