Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to use Boto3 to create a secret key as plain text in AWS Secret Manager
AWS Secrets Manager is a service that helps you securely store, retrieve, and manage sensitive information like API keys, database credentials, and other secrets. Using boto3, Python's AWS SDK, you can programmatically create and manage secrets as plain text.
Prerequisites
Before creating secrets, ensure you have ?
- AWS credentials configured (via AWS CLI, IAM roles, or environment variables)
- Proper IAM permissions for Secrets Manager operations
- boto3 library installed:
pip install boto3
Creating a Secret in AWS Secrets Manager
The process involves establishing an AWS session, creating a Secrets Manager client, and calling the create_secret method with the required parameters ?
import boto3
from botocore.exceptions import ClientError
def create_secret_details(secret_stored_location, secret_key_pair: str):
"""
Create a secret in AWS Secrets Manager
Args:
secret_stored_location (str): The name/path where secret will be stored
secret_key_pair (str): The secret value as a JSON string
Returns:
dict: Response metadata from AWS Secrets Manager
"""
session = boto3.session.Session()
secrets_client = session.client('secretsmanager')
try:
response = secrets_client.create_secret(
Name=secret_stored_location,
SecretString=secret_key_pair
)
return response
except ClientError as e:
raise Exception("boto3 client error in create_secret_details: " + str(e))
except Exception as e:
raise Exception("Unexpected error in create_secret_details: " + str(e))
# Example usage
secret_details = '{"username": "admin", "password": "mypassword123"}'
response = create_secret_details('/myapp/database/credentials', secret_details)
print("Secret created successfully!")
print(f"ARN: {response['ARN']}")
print(f"Version ID: {response['VersionId']}")
Key Parameters
| Parameter | Type | Description |
|---|---|---|
Name |
string | Unique identifier for the secret (e.g., "/myapp/database") |
SecretString |
string | The secret value as plain text (often JSON format) |
Description |
string (optional) | Human-readable description of the secret |
Complete Example with Error Handling
import boto3
from botocore.exceptions import ClientError
import json
def create_database_secret():
"""Create a database credential secret"""
# Secret data as dictionary, then convert to JSON string
secret_data = {
"username": "dbuser",
"password": "secure_password_123",
"host": "mydb.example.com",
"port": 5432,
"database": "production"
}
secret_string = json.dumps(secret_data)
secret_name = "/myapp/database/credentials"
try:
session = boto3.session.Session(region_name='us-east-1')
secrets_client = session.client('secretsmanager')
response = secrets_client.create_secret(
Name=secret_name,
Description="Database credentials for production environment",
SecretString=secret_string
)
print("? Secret created successfully!")
print(f"Secret ARN: {response['ARN']}")
print(f"Version ID: {response['VersionId']}")
return response
except ClientError as e:
error_code = e.response['Error']['Code']
if error_code == 'ResourceExistsException':
print("? Secret already exists with this name")
elif error_code == 'AccessDeniedException':
print("? Insufficient permissions to create secret")
else:
print(f"? AWS error: {e}")
except Exception as e:
print(f"? Unexpected error: {e}")
# Run the function
create_database_secret()
Important Notes
-
Service Name: Use
'secretsmanager'not'secretmanager'when creating the client - Secret Format: Store secrets as JSON strings for structured data
-
Naming Convention: Use hierarchical names like
/app/environment/service - Region: Secrets are region-specific; specify the correct region
-
Permissions: Ensure your IAM role has
secretsmanager:CreateSecretpermission
Conclusion
Creating secrets in AWS Secrets Manager with boto3 involves using the create_secret method with proper error handling. Always store sensitive data as JSON strings and use descriptive, hierarchical naming conventions for better organization.
Advertisements
