• TechOps

    Need clarity?
    Chat with our experts now

    • Web Hosting SupportWeb Hosting Support
    • Helpdesk Support

      Skilled and professional 24/7 helpdesk support

    • Product Support

      Boost your product support with our expertise

    • Managed ServicesManaged Services
    • Server Management

      Don't let server issues slow you down. Let us manage them for you

    • Server Monitoring

      Safeguard your server health with our comprehensive monitoring solutions

    • Staff AugmentationStaff Augmentation
    • Hire an Admin

      Transform your business operations with our expert administrative support

    • Hire a Team

      Augment your workforce with highly skilled professional from our diverse talent pool

  • CloudOps

    Confused?
    Discuss with our sales team now.

    • Author ProfileAWS
      Well Architected Review
    • Author ProfileFinOps As a Service

      FinOps As a Service

    • Migrate

      Upgrade the journey: Migrate & Modernize seamlessly

    • Modernize

      Effortless CloudOps mastery for seamless cloud management

    • Optimize

      Efficient CloudOps: Boosting performance through optimization

    • Manage

      Simplify compliance complexities with our dedicated service

  • DevOps

    How Supportsages
    is creating an
    impact?

    View Casestudies
    • Author Profile24/7 DevOps As a Service

      Round-the-clock DevOps for uninterrupted efficiency

    • Author ProfileCI/CD Pipeline

      Automated CI/CD pipeline for seamless deployments

    • Author ProfileInfrastructure As a Code

      Crafting infrastructure with ingenious code

    • Author ProfileDevSecOps

      Integrated security in continuous DevOps practices

    • Author ProfileHire DevOps Engineers

      Level up your team with DevOps visionaries

    • Author ProfileConsulting Services

      Navigate success with expert DevOps consulting

  • SecOps

    Expert SecOps Services
    for any Scale

    • Author ProfileVAPT

      Vulnerability Assessment and Penetration Testing

    • Author ProfileSource Code Review

      Ensuring source code security and safe practices to reduce risks

    • Author ProfileSecurity Consultation

      On demand services for improving server security

    • Author ProfileSystem Hardening

      Reduced vulnerability and proactive protection

    • Author ProfileManaged SOC

      Monitors and maintains system security. Quick response on incidents

    • Author ProfileCompliance as a Service

      Regulatory compliance, reduced risk

  • Insights

    Explore our latest
    insights and resources

    Blog

    Explore our latest articles and insights

    Case Studies

    Read about our client success stories

  • Contact Us

  • About
  • Certifications
  • Life at Supportsages
  • Events
  • Contact
  • Careers
  • Blog

  • Dedicated Support Team
  • Quasi-dedicated Support Team
  • Hire a DevOps Engineer
  • Hire a Billing Support Staff
  • Per-ticket Support Plan
  • Managed Services

  • Microsoft Azure Expert
  • AWS Cloud Expert
  • Hire a developer
SS

SupportSages

Bites of wisdom @ work


Copyright © 2008 - 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy

Script to Gather Retention Details of S3 Buckets

Ashley Merrin Shaji

  • 6 min read
Script to Gather Retention Details of S3 Buckets

Generating audio, please wait...

Introduction 

This script is designed to retrieve and display retention details for all S3 buckets in your AWS account.  The script queries each bucket for life-cycle configurations and generates a comprehensive report in JSON format. Additionally, you can format the results into a tabular structure for easy viewing. 

Purpose 

  • Fetch, Identify and display retention policies for each bucket. 
  • Retrieve folder-specific lifecycle policies where applicable. 
  • Captures post-retention actions (e.g., expiration, transition). 
  • Save results in a JSON file for further processing. 

Prerequisites 

AWS CLI must be installed and configured with appropriate permissions to list S3 buckets and view life-cycle configurations. 

Script 

#!/bin/bash 
  
# Created by: Ashley Merrin Shaji
  
# Get the list of all S3 buckets in your account 
buckets=$(aws s3api list-buckets --query "Buckets[].Name" --output text) 
  
# Create a file to store the results 
output_file="s3_bucket_lifecycle_details.json" 
echo "[" > $output_file # Start the JSON array 
  
# Loop through each bucket 
for bucket in $buckets; do 
  echo "Fetching details for bucket: $bucket" 
    
  # Get the bucket's lifecycle configuration 
  lifecycle=$(aws s3api get-bucket-lifecycle-configuration --bucket "$bucket" 2>/dev/null) 
    
  # If lifecycle configuration exists, process it 
  if [ $? -eq 0 ]; then 
    echo "{\"Bucket\": \"$bucket\", \"LifecycleConfiguration\": $lifecycle," >> $output_file 
      
    # Fetch prefix-specific lifecycle rules with actions 
    prefixes=$(echo "$lifecycle" | jq -r '.Rules[]? | { 
      Prefix: .Filter.Prefix, 
      Expiration: .Expiration, 
      Transition: .Transitions[]? // null 
    }') 
      
    if [ -n "$prefixes" ]; then 
      echo "\"PrefixDetails\": [$prefixes]}" >> $output_file 
    else 
      echo "\"PrefixDetails\": []}" >> $output_file 
    fi 
  else 
    echo "{\"Bucket\": \"$bucket\", \"LifecycleConfiguration\": null, \"PrefixDetails\": []}," >> $output_file 
  fi 
done 
  
# Close the JSON array properly 
sed -i '$ s/,$//' $output_file # Remove the trailing comma from the last entry 
echo "]" >> $output_file 
  
echo "All bucket details with lifecycle configurations, prefix-specific rules, and post-retention actions saved to $output_file" 

Command to Format and Display Output 

Use the following command to parse and display the retention information in a tabular format: 

cat s3_bucket_lifecycle_details.json | jq -r ' 
[ 
.[] | 
{ 
  "Bucket": .Bucket, 
  "PostRetentionActions": ( 
    if .LifecycleConfiguration != null and .LifecycleConfiguration.Rules != null then 
      .LifecycleConfiguration.Rules[] | 
      ("Prefix: " + (.Filter.Prefix // "No Prefix") + ", Expiration Days: " + (.Expiration.Days | tostring // "No Expiration") + ", Transition Action: " + 
      ( 
        if .Transitions != null then 
          (.Transitions[] | ("After " + (.Days | tostring) + " Days -> " + .StorageClass)) 
        else 
          "No Transition" 
        end 
      )) 
    else 
      "No Retention Policy" 
    end 
  ) 
} 
] | 
(["Bucket Name", "Post-Retention Actions"] | @tsv), 
(.[] | [.Bucket, .PostRetentionActions] | @tsv) 
' | column -t -s$'\t' 
' 

Output 

The script generates a table with the following columns: 
Bucket Name: The name of the S3 bucket. 
Retention Policy: 
The jq command extracts and formats the following details for each bucket: 

  • "Prefix": Displays the prefix (folder) for which the lifecycle policy is applied. 
  • "Expiration Days": Displays the number of days after which objects expire. If no expiration policy is set, it shows "No Expiration". 
  • If no lifecycle configuration is present for the bucket, it displays "No Retention Policy". 

JSON Output: 

[ 
  { 
    "Bucket": "example-bucket-1", 
    "LifecycleConfiguration": { 
      "Rules": [ 
        { 
          "Filter": { "Prefix": "folder1/" }, 
          "Expiration": { "Days": 30 }, 
          "Transitions": [ 
            { "Days": 60, "StorageClass": "GLACIER" } 
          ] 
        } 
      ] 
    }, 
    "PrefixDetails": [ 
      { 
        "Prefix": "folder1/", 
        "Expiration": { "Days": 30 }, 
        "Transition": { "Days": 60, "StorageClass": "GLACIER" } 
      } 
    ] 
  }, 
  { 
    "Bucket": "example-bucket-2", 
    "LifecycleConfiguration": null, 
    "PrefixDetails": [] 
  } 
] 

Tabular Output: 

Bucket Name             Post-Retention Actions 
example-bucket-1 Prefix: folder1/, Expiration Days: 30, Transition Action: After 60 Days -> GLACIER
example-bucket-2No Retention Policy

Conclusion 

This script provides a comprehensive way to retrieve and display life-cycle policies for all S3 buckets in an AWS account, including folder-specific life-cycle rules and post-retention actions like expiration and transitions to different storage classes. It generates a detailed JSON report, helping users understand how long objects are retained or when they are transitioned or deleted. 

Additionally, the provided command formats the output into a clear, tabular view, making it easy for administrators to quickly identify which buckets or folders have specific retention policies and whether objects are set to expire or transition to another storage class. 

This solution ensures efficient data life-cycle management across all S3 buckets, aiding in compliance, cost optimization, and data governance. 

  • AWS
  • DevOps

Looking for AWS Experts?

We provide top-of-the-line custom AWS setup services tailored to your needs.

Automating SES Event Monitoring with AWS Lambda and CloudWatch Logs

Automating SES Event Monitoring with AWS Lambda and CloudWatch Logs
  • AWS
logo

Automating SES Event Monitoring with AWS Lambda and CloudWatch Logs

Automating SES Event Monitoring with AWS Lambda and CloudWatch Logs
  • AWS
  • DevOps
logo

Comparison of GCR (Google), ECR (Amazon), and ACR (Azure)

Comparison of GCR (Google), ECR (Amazon), and ACR (Azure)
  • DevOps
  • Azure
  • GCP
  • AWS
logo
Script to Gather Retention Details of S3 Buckets

Posts by Ashley Merrin Shaji