Automating AWS ECR Tagging with Python and Boto3

Proper tagging of AWS resources is critical for efficient resource management, cost allocation, and auditing. If you have numerous AWS Elastic Container Registry (ECR) repositories, manual tagging can be tedious and error-prone. This article provides a simple and effective solution: automating the tagging of ECR repositories using Python and the AWS SDK for Python (Boto3).
Why Automate Tagging?
Automating tagging saves time, ensures consistency, and prevents costly mistakes. Tags help track resources related to specific projects, environments, or cost centers.
Prerequisites
- Python 3 installed
- AWS CLI installed and configured
- Boto3 library installed (
pip install boto3) - IAM permissions:
ecr:DescribeRepositoriesecr:ListTagsForResourceecr:TagResource
Tagging AWS ECR Repositories with Python
Here's a straightforward Python script using Boto3 to add predefined tags to all your ECR repositories that currently have no tags.
Python Script
import boto3
AWS_REGION = ’eu-central-1’ # Replace with your region
Define your tags
TAGS_TO_APPLY = [
{‘Key’: ‘provisioned’, ‘Value’: ‘manual’},
{‘Key’: ’environment’, ‘Value’: ‘dev’},
{‘Key’: ‘project’, ‘Value’: ‘Project_Name’},
]
def tag_ecr_repositories():
ecr_client = boto3.client(’ecr’, region_name=AWS_REGION)
paginator = ecr_client.get_paginator('describe_repositories')
for page in paginator.paginate():
for repo in page['repositories']:
repo_arn = repo['repositoryArn']
repo_name = repo['repositoryName']
existing_tags = ecr_client.list_tags_for_resource(resourceArn=repo_arn).get('tags', [])
if not existing_tags:
print(f"Adding tags to repository '{repo_name}'")
ecr_client.tag_resource(resourceArn=repo_arn, tags=TAGS_TO_APPLY)
else:
print(f"Repository '{repo_name}' already has tags. Skipping.")
if name == ‘main’:
tag_ecr_repositories()
The script will automatically scan through your ECR repositories and add tags only to those repositories that currently have no tags.
Benefits
- Saves valuable administrative time.
- Ensures consistency across your AWS environment.
- Reduces the risk of human error.
Conclusion
Automating the tagging of AWS resources is an essential practice for effective cloud management. Using Python with Boto3 simplifies this task significantly, ensuring your AWS resources remain organized and easily manageable.
More from Ercan
Two more sites, same author, different ground.
AI, LLMs, agents, applied ML.
Field notes on AI workloads. Bedrock cost analysis, agent patterns, vector storage trade-offs, production failure modes.
Visit ercan.ai →The hub. About, consulting, contact.
Personal hub for both writing tracks. Who I am, how the consulting works, how to reach me.
Visit ercanermis.com →