Skip to content
Ercan Ermis
Ercan Ermis

notes for everyone about cloud technology

  • Cloud
    • AWS
    • GCP
  • Container
    • Kubernetes
    • Docker
  • Linux
  • DevOps
  • Privacy Policy
  • Contact
Ercan Ermis

notes for everyone about cloud technology

Streamline Your AWS ECR Management with This Powerful Bash Script

Ercan, March 27, 2025March 27, 2025

Managing container repositories in AWS ECR (Elastic Container Registry) can quickly become a daunting task, especially as your infrastructure grows. In this article, we’ll take an in-depth look at a handy bash script designed to automate the application of lifecycle policies to your ECR repositories. This script not only simplifies repository management but also ensures that only the most recent images are retained, helping you save on storage costs and keep your registry tidy.

What Does This Script Do?

The primary purpose of this bash script is to automate the process of applying a lifecycle policy that keeps only the latest three images in each AWS ECR repository in a specified region. Here’s a quick overview of its functionality:

  • Error Handling: The script is configured to exit immediately if any command returns a non-zero status, which minimizes the risk of unintended behavior.
  • Color-Coded Output: It uses ANSI color codes to highlight messages (such as warnings in red), making the output easier to parse.
  • Dry-Run Mode: For a safe, non-destructive test, the script includes a --dry-run option that simulates actions without actually applying the policy.
  • AWS CLI Integration: It retrieves repository names using the AWS CLI and then iterates over each repository to check for an existing lifecycle policy before applying a new one.

Breaking Down the Script

1. Setting Up the Environment

The script starts by enforcing strict error handling with set -e and defines ANSI color codes for enhanced terminal output. This ensures that any error stops the script immediately, preventing unintended operations.

#!/bin/bash
set -e
RED='\033[0;31m'
NC='\033[0m' # No Color

2. Parsing Command-Line Arguments

A simple loop processes command-line arguments to detect if the script should run in dry-run mode. This allows administrators to test the script without making any real changes.

DRY_RUN=false
while [[ "$#" -gt 0 ]]; do
    case $1 in
        --dry-run) DRY_RUN=true ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

3. Specifying the AWS Region and Retrieving Repositories

The script is configured to work in a specified region (eu-central-1 by default). It retrieves the list of repository names from AWS ECR using the AWS CLI. If no repositories are found, it exits with an appropriate message.

REGION="eu-central-1"
repos=$(aws ecr describe-repositories --region "$REGION" --query 'repositories[].repositoryName' --output text)
if [ -z "$repos" ]; then
    echo "No repositories found in region $REGION."
    exit 1
fi

4. Defining the Lifecycle Policy

A JSON object is defined within the script to specify the lifecycle policy. This policy is set to keep only the last three images, which is ideal for many use cases where maintaining the most recent images is sufficient.

lifecycle_policy='{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Keep last 3 images",
      "selection": {
        "tagStatus": "any",
        "countType": "imageCountMoreThan",
        "countNumber": 3
      },
      "action": {
        "type": "expire"
      }
    }
  ]
}'

5. Applying the Lifecycle Policy to Each Repository

The script then loops through each repository. It checks if a lifecycle policy already exists. If it does, the repository is skipped, and a warning is shown in red. If not, the lifecycle policy is applied, or a dry-run message is printed if that mode is enabled.

for repo in $repos; do
    echo "Processing repository: $repo"
    if aws ecr get-lifecycle-policy --repository-name "$repo" --region "$REGION" > /dev/null 2>&1; then
        echo -e "${RED}Lifecycle policy already exists for repository $repo. Skipping...${NC}"
    else
        if [ "$DRY_RUN" = true ]; then
            echo "DRY RUN: Would apply lifecycle policy to repository: $repo"
            echo "DRY RUN: aws ecr put-lifecycle-policy --repository-name \"$repo\" --lifecycle-policy-text '$lifecycle_policy' --region \"$REGION\""
        else
            echo "Applying lifecycle policy to repository: $repo"
            aws ecr put-lifecycle-policy \
                --repository-name "$repo" \
                --lifecycle-policy-text "$lifecycle_policy" \
                --region "$REGION" | tee
        fi
    fi
done
echo "Processing complete."

Benefits of Using This Script

Automation and Efficiency

Manually applying lifecycle policies across multiple repositories can be tedious and error-prone. This script automates the process, ensuring consistent application of policies and freeing up valuable time for your team.

Cost Management

By keeping only the most recent images, the script helps in managing storage costs. Old, unused images are automatically removed, reducing unnecessary storage expenditure.

Safe Testing with Dry-Run Mode

Before making any permanent changes, you can run the script in dry-run mode. This feature provides a clear preview of what actions will be performed, minimizing the risk of mistakes.

Customizable and Extendable

The script can easily be modified to suit your specific needs, such as changing the retention policy or targeting different regions. Its modular design allows for quick adaptations as your AWS environment evolves.

Conclusion

Automating routine tasks is a key strategy for efficient DevOps and system administration. This bash script for applying lifecycle policies to AWS ECR repositories is an excellent example of how simple automation can drive significant operational benefits. Whether you’re looking to reduce costs, streamline your workflow, or enforce a consistent policy across your repositories, this script offers a reliable and customizable solution.

Implement this script in your AWS environment and experience the ease of automated repository management today!

Share on Social Media
x facebook linkedin reddit
Serverless

Post navigation

Previous post
Next post
  • AWS (45)
    • Serverless (4)
  • Best (9)
  • DevOps (16)
  • Docker (10)
  • GCP (3)
  • Kubernetes (3)
  • Linux (13)
  • Uncategorized (6)

Recent Posts

  • Automating AWS CloudWatch Log Group Tagging with Python and Boto3
  • Automating AWS ECR Tagging with Python and Boto3
  • Automating ECR Image Cleanup with Bash
  • Update ECR Repositories with Bash Script
  • Why Automated Tests Are Essential in Your CI/CD Pipeline and Development Flow
  • Streamline Your AWS ECR Management with This Powerful Bash Script
  • Setting up DKIM for Google Workspace (Gmail) using Terraform and AWS Route 53
  • Automate AWS Site-to-Site VPN Monitoring
  • Optimizing Docker Images: Tips for Reducing Image Size and Build Time
  • Monitoring EC2 Disk Space with a Simple Bash Script and Slack Alerts
  • Securing Docker Containers: Best Practices for Container Security
  • Mastering Dockerfile: Writing Efficient, Scalable Container Builds
  • Migrating a Git Repository from GitLab to GitHub with GPG-Signed Commits
  • Accessing AWS Services in Private Subnets Without 0.0.0.0/0
  • Understanding AWS Regions, Availability Zones, and VPCs: A Comprehensive Guide
©2025 Ercan Ermis | WordPress Theme by SuperbThemes