How to use Boto3 to update the secret keys from a specific location in AWS Secret Manager

AWS Secrets Manager allows you to securely store and manage sensitive information like API keys, database credentials, and other secrets. Using boto3, Python's AWS SDK, you can programmatically update secrets stored in AWS Secrets Manager.

Prerequisites

Before updating secrets, ensure you have ?

  • AWS credentials configured (via AWS CLI, IAM roles, or environment variables)
  • Appropriate IAM permissions for secretsmanager:UpdateSecret
  • The boto3 library installed: pip install boto3

Algorithm Steps

  • Step 1: Import boto3 and botocore exceptions to handle errors gracefully.

  • Step 2: Define the secret location (SecretId) and the new secret value as a JSON string.

  • Step 3: Create an AWS session using boto3. Specify region_name if not set in your default profile.

  • Step 4: Create a client for secretsmanager service.

  • Step 5: Call update_secret() with the SecretId and new SecretString.

  • Step 6: Handle exceptions and return the response metadata.

Complete Example

Here's how to update a secret in AWS Secrets Manager ?

import boto3
from botocore.exceptions import ClientError
import json

def update_secret_details(secret_stored_location, secret_key_pair):
    """
    Update secret in AWS Secrets Manager
    
    Args:
        secret_stored_location (str): Secret name or ARN
        secret_key_pair (str): JSON string containing the secret data
    
    Returns:
        dict: Response metadata from AWS
    """
    session = boto3.session.Session()
    secretsmanager_client = session.client('secretsmanager')
    
    try:
        response = secretsmanager_client.update_secret(
            SecretId=secret_stored_location,
            SecretString=secret_key_pair
        )
        return response
    except ClientError as e:
        raise Exception(f"AWS client error in update_secret_details: {e}")
    except Exception as e:
        raise Exception(f"Unexpected error in update_secret_details: {e}")

# Example usage
secret_location = '/secrets/aws'
secret_data = json.dumps({
    "username": "admin_user",
    "password": "new_secure_password_123",
    "api_key": "ak_test_12345"
})

try:
    response = update_secret_details(secret_location, secret_data)
    print("Secret updated successfully!")
    print(f"Version ID: {response['VersionId']}")
except Exception as e:
    print(f"Error updating secret: {e}")

Response Structure

When successful, the update_secret() method returns metadata including ?

  • ARN: The Amazon Resource Name of the secret
  • Name: The name of the secret
  • VersionId: Unique identifier for this version of the secret
  • ResponseMetadata: HTTP response details and request information

Best Practices

  • Always store secrets as properly formatted JSON strings
  • Use descriptive secret names with consistent naming conventions
  • Implement proper error handling for network issues and permission errors
  • Consider using IAM roles instead of hardcoded credentials
  • Validate secret data before updating to prevent corruption

Common Use Cases

  • Rotating database passwords automatically
  • Updating API keys when they expire
  • Managing application configuration secrets
  • Synchronizing secrets across multiple environments

Conclusion

Using boto3 to update AWS Secrets Manager is straightforward with the update_secret() method. Always ensure proper error handling and pass secrets as JSON strings for structured data storage.

Updated on: 2026-03-25T19:02:17+05:30

922 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements