How to create S3 lifecycle rule using AWS CLI

This post explains how to set up S3 Lifecycle configuration on a S3 bucket using AWS CLI. Lifecycle rules are used to define action you want to take on S3 bucket object's lifetime.

To follow this tutorials you need to have AWS CLI installed and configured, if AWS CLI is not installed or not configured follow below articles to complete the setup.

AWS CLI configuration On Windows
1. How to install AWS CLI on windows
2. How to configure AWS CLI

AWS CLI configuration On Ubuntu
1. How to install AWS CLI on Ubuntu
2. How to configure AWS CLI

Create S3 Lifecycle configuration

Let's create a S3 lifecycle rule which performs following actions.
  • Create a lifecycle rule with name SampleRule.
  • Apply rule to the key name prefix text_documents/.
  • Transition objects to the S3 Glacier Flexible Retrieval storage class 365 days after creation.
  • Delete objects after two year of creation.

To create the rule write below configuration in file named lifecycle.json.

   
  {
    "Rules": [
      {
        "Filter": {
          "Prefix": "text_documents/"
        },
        "Status": "Enabled",
        "Transitions": [
          {
            "Days": 365,
            "StorageClass": "GLACIER"
          }
        ],
        "Expiration": {
          "Days": 730
        },
        "ID": "SampleRule"
      }
    ]
  }  
 

Set the Lifecycle configuration on S3 bucket

Run the below command to set the lifecycle configuration on your S3 bucket. Replace bucketname with the your bucket name.
   
aws s3api put-bucket-lifecycle-configuration --bucket bucketname --lifecycle-configuration file://lifecycle.json 

 

Verify Lifecycle configuration

After successful execution of command you should have below configuration applied to S3 bucket. s3rule

Follow US on Twitter:

Category: AWS

Similar Articles