How to use Boto3 to add tags in specified AWS secrets

AWS Secrets Manager allows you to store and manage sensitive information like database passwords and API keys. You can organize and categorize secrets using tags, which are key-value pairs that help with resource management and billing. The boto3 library provides a simple way to add tags to AWS secrets programmatically.

Prerequisites

Before adding tags to AWS secrets, ensure you have ?

  • AWS credentials configured (via AWS CLI, environment variables, or IAM roles)

  • The boto3 library installed: pip install boto3

  • Proper IAM permissions for Secrets Manager operations

Understanding the Tag Format

AWS Secrets Manager expects tags in a specific format. Each tag is a dictionary with Key and Value fields ?

# Correct format for AWS Secrets Manager tags
tags = [
    {"Key": "Environment", "Value": "Production"},
    {"Key": "Team", "Value": "DevOps"}
]

Adding Tags to AWS Secrets

Here's a complete function to add tags to an AWS secret using boto3 ?

import boto3
from botocore.exceptions import ClientError

def add_tags_to_secret(secret_name, tags_list):
    """
    Add tags to an AWS secret
    
    Args:
        secret_name (str): Name or ARN of the secret
        tags_list (list): List of tag dictionaries with 'Key' and 'Value'
    
    Returns:
        dict: Response from AWS
    """
    try:
        # Create AWS session and client
        session = boto3.session.Session()
        client = session.client('secretsmanager')
        
        # Add tags to the secret
        response = client.tag_resource(
            SecretId=secret_name,
            Tags=tags_list
        )
        
        return response
        
    except ClientError as e:
        raise Exception(f"AWS ClientError in add_tags_to_secret: {e}")
    except Exception as e:
        raise Exception(f"Unexpected error in add_tags_to_secret: {e}")

# Example usage
tags_to_add = [
    {"Key": "Environment", "Value": "Development"},
    {"Key": "Project", "Value": "WebApp"},
    {"Key": "Owner", "Value": "DataTeam"}
]

# Add tags to a secret
secret_name = "my-database-secret"
result = add_tags_to_secret(secret_name, tags_to_add)
print("Tags added successfully!")
print(f"Request ID: {result['ResponseMetadata']['RequestId']}")
Tags added successfully!
Request ID: c9f418b0-1234-5678-9abc-def012345678

Retrieving Secret Tags

You can also retrieve existing tags from a secret to verify the operation ?

def get_secret_tags(secret_name):
    """
    Retrieve tags for an AWS secret
    
    Args:
        secret_name (str): Name or ARN of the secret
    
    Returns:
        list: List of tag dictionaries
    """
    try:
        session = boto3.session.Session()
        client = session.client('secretsmanager')
        
        response = client.describe_secret(SecretId=secret_name)
        return response.get('Tags', [])
        
    except ClientError as e:
        raise Exception(f"Error retrieving tags: {e}")

# Get current tags
current_tags = get_secret_tags("my-database-secret")
print("Current tags:")
for tag in current_tags:
    print(f"  {tag['Key']}: {tag['Value']}")
Current tags:
  Environment: Development
  Project: WebApp
  Owner: DataTeam

Best Practices

  • Use descriptive tag keys: Choose meaningful names like "Environment", "Project", "Owner"

  • Standardize tag values: Use consistent values like "Production", "Staging", "Development"

  • Handle exceptions: Always wrap AWS operations in try-except blocks

  • Validate tag format: Ensure tags follow the required dictionary structure

Conclusion

Adding tags to AWS secrets using boto3 is straightforward with the tag_resource() method. Tags help organize resources, track costs, and implement access controls. Always handle exceptions properly and follow AWS tagging best practices for effective resource management.

Updated on: 2026-03-25T19:04:09+05:30

887 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements