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:DescribeRepositories
ecr:ListTagsForResource
ecr: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.