Skip to main content

A Python library to manage S3 lifecycle policies

Project description

s3-lifecycle

PyPI TestPyPI

A small Python library to compute and apply policies on AWS S3 lifecycle policies—especially focused on safe, declarative storage class transitions—with dry-run, validation, and minimal disruption.


Problem

AWS S3 lifecycle policies are typically applied by overwriting the entire configuration. That makes automated changes brittle, error-prone, and risky when you only want to tweak transitions (e.g., change from STANDARDGLACIER after 90 days) without accidentally deleting other rules.

This library:

  • Introspects the current lifecycle policy
  • Compares it to the desired policy
  • Shows what would change (dry-run)
  • Validates rules
  • Applies only the intended change safely

Features

  • Declarative lifecycle policy definitions (via Python / JSON)
  • Diff engine: detects rule adds / updates / deletes
  • Safe apply with dry-run
  • Validation of transition semantics (e.g., non-decreasing days)
  • Idempotent behavior
  • Pluggable for custom validation or rule logic

Quickstart

1. Set Up AWS Environment

Before using s3-lifecycle, configure AWS credentials.

a) Using AWS CLI

aws configure

Provide:

AWS Access Key ID [None]: <YOUR_ACCESS_KEY>
AWS Secret Access Key [None]: <YOUR_SECRET_KEY>
Default region name [None]: <YOUR_DEFAULT_REGION>  # e.g., us-east-1
Default output format [None]: json

b) Using environment variables

Linux/macOS:

export AWS_ACCESS_KEY_ID=<YOUR_ACCESS_KEY>
export AWS_SECRET_ACCESS_KEY=<YOUR_SECRET_KEY>
export AWS_DEFAULT_REGION=us-east-1

Windows (PowerShell):

setx AWS_ACCESS_KEY_ID "<YOUR_ACCESS_KEY>"
setx AWS_SECRET_ACCESS_KEY "<YOUR_SECRET_KEY>"
setx AWS_DEFAULT_REGION "us-east-1"

⚠️ Ensure your IAM user has s3:GetLifecycleConfiguration and s3:PutLifecycleConfiguration permissions.


2. Install the Library

git clone https://github.com/FernandoOLI/s3-lifecycle.git
cd s3-lifecycle
pip install -e .

3. Basic Usage

from s3_lifecycle import LifecyclePolicy, LifecycleManager, validate_policy, ValidationError, ApplyError

# Example lifecycle policy dictionary
desired_policy_dict = {
    "Rules": [
        {
            "ID": "archive-log",
            "Filter": {"Prefix": "logs/"},
            "Status": "Enabled",
            "Transitions": [
                {"Days": 300, "StorageClass": "GLACIER"},
                {"Days": 390, "StorageClass": "DEEP_ARCHIVE"}
            ],
            "Expiration": {'Days': 500},
            "NoncurrentVersionTransitions": [
                {"NoncurrentDays": 30, "StorageClass": "GLACIER"},
                {"NoncurrentDays": 150, "StorageClass": "DEEP_ARCHIVE"}
            ],
            "NoncurrentVersionExpiration": {'NoncurrentDays': 700}
        }
    ]
}

def main():
    try:
        # Create and validate policy
        policy = LifecyclePolicy.from_dict(desired_policy_dict)
        validate_policy(policy)

        bucket = "lifecycle-management-bucket"

        # Initialize manager (will create boto3 client if not passed)
        manager = LifecycleManager()

        # Compute input vs current S3 bucket policy
        diff_result = manager.compute(bucket, policy)

        # Apply changes safely (dry_run=True prints summary only)
        manager.apply(bucket, diff_result, policy, dry_run=True)

    except ValidationError as ve:
        print(f"Policy validation error: {ve}, details: {ve.details}")
    except ApplyError as ae:
        print(f"Failed to apply lifecycle policy: {ae}")
    except Exception as e:
        print(f"Unexpected error: {e}")

if __name__ == "__main__":
    main()

4. Notes

  • dry_run=True only prints changes; no modifications are applied.
  • Always validate IAM permissions before running apply.
  • Supports declarative JSON/Python policy definitions for safe incremental updates.

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/my-feature)
  3. Make your changes
  4. Run tests and ensure coverage
  5. Submit a Pull Request

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

s3_lifecycle-0.1.2.tar.gz (7.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

s3_lifecycle-0.1.2-py3-none-any.whl (9.9 kB view details)

Uploaded Python 3

File details

Details for the file s3_lifecycle-0.1.2.tar.gz.

File metadata

  • Download URL: s3_lifecycle-0.1.2.tar.gz
  • Upload date:
  • Size: 7.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for s3_lifecycle-0.1.2.tar.gz
Algorithm Hash digest
SHA256 3bcaebc78a558215623ead2c97ee1a46470df4db1db0081ac5554700c9ebdaf4
MD5 2a506f7f0f5f9ce514ec699d7c59425c
BLAKE2b-256 c338ed2c1ca85663fd24ca2cc9c71522ed786f908d07c09e730e4ebcf1f632dd

See more details on using hashes here.

File details

Details for the file s3_lifecycle-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: s3_lifecycle-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 9.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for s3_lifecycle-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 87471dab15d5153264f6184887e549e2ecf4f0303659226ec96c51b73f4a0f04
MD5 bbd9f96a3a202630b43e9de48e87be0e
BLAKE2b-256 2f2e56f617b10501bd204a6b2b5c5d86fdf2eb0aace36f6217e1faf2ce0209c4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page