7 min to read
AWS Secrets Manager - Secure Secret Management Service
A comprehensive guide to AWS Secrets Manager and its features

Overview
AWS Secrets Manager is a secrets management service that helps you protect access to your applications, services, and IT resources.
Without the upfront investment and ongoing maintenance costs of operating your own infrastructure, you can manage and retrieve database credentials, API keys, and other secrets throughout their lifecycle.
Key Features of AWS Secrets Manager
Secure Secret Storage and Management
- Securely store and retrieve secrets
- Encrypt secrets using AWS KMS
- Centralized secret management
Fine-grained Access Control
- Define granular permissions using IAM policies
- Control who can access or modify specific secrets
- Integrate with existing AWS services
Automated Secret Rotation
- Support for automatic secret rotation
- Custom rotation schedules
- Integration with AWS Lambda for custom rotation functions
Audit and Monitoring
- Integration with AWS CloudTrail
- Monitor and log secret access
- Maintain compliance and identify security risks
AWS Secrets Manager CLI Commands
# Available Commands
aws secretsmanager help
# Common Commands
aws secretsmanager create-secret
aws secretsmanager get-secret-value
aws secretsmanager list-secrets
aws secretsmanager rotate-secret
aws secretsmanager delete-secret
Secret Types and Examples
1. Database Credentials
{
"username": "myDatabaseUser",
"password": "mySecurePassword",
"host": "myDatabaseHost",
"port": 3306
}
2. API Keys
{
"api_key": "sk_test_1234567890abcdef",
"secret_key": "sh_test_1234567890abcdef"
}
3. OAuth Tokens
{
"access_token": "ya29.1234567890abcdef",
"refresh_token": "1/1234567890abcdef",
"client_id": "myClientID.apps.googleusercontent.com",
"client_secret": "myClientSecret"
}
4. SSH Keys
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAz0FzLw1bmK5OzYDhLTVlLQzPgh6T9T...
... (rest of the private key) ...
-----END RSA PRIVATE KEY-----
Rotation Configuration
Rotation Settings
- Configure rotation frequency (minimum 1 day)
- Set up Lambda function for rotation
- Automatic trigger on schedule
Required Permissions
- Secrets Manager permissions
- Lambda function permissions
- Application permissions
Understanding OAuth and SSO
- Access Token
- Short-term credentials
- Used for resource access
- Has expiration time
- Refresh Token
- Long-term credentials
- Used to obtain new access tokens
- Reduces need for frequent re-authentication
OAuth Token Flow
- User initiates login
- Application redirects to OAuth provider
- User grants permissions
- OAuth provider issues authentication code
- Application exchanges code for tokens
SSO Flow
Implementation Best Practices
1. Security: - Use customer managed KMS keys for additional control
- Implement least privilege IAM policies
- Enable automatic rotation for all secrets
- Consider multi-region replication for disaster recovery
2. Performance: - Cache secrets in application memory when appropriate
- Use VPC endpoints to access Secrets Manager within your VPC
- Implement proper error handling for retrieval failures
- Consider using Parameter Store for non-sensitive configuration
3. Cost Optimization: - Consolidate related credentials into a single secret when possible
- Clean up unused secrets to avoid unnecessary charges
- Use tagging for cost allocation and tracking
- Evaluate Parameter Store for less sensitive configs (free tier available)
Integration Examples
1. AWS CLI Example
2. AWS SDK (Python) Example
import boto3
import json
import base64
from botocore.exceptions import ClientError
def get_secret(secret_name, region_name="us-west-2"):
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
# Handle exceptions
if e.response['Error']['Code'] == 'DecryptionFailureException':
raise e
elif e.response['Error']['Code'] == 'InternalServiceErrorException':
raise e
elif e.response['Error']['Code'] == 'InvalidParameterException':
raise e
elif e.response['Error']['Code'] == 'InvalidRequestException':
raise e
elif e.response['Error']['Code'] == 'ResourceNotFoundException':
raise e
else:
# Decrypts secret using the associated KMS key
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
return json.loads(secret)
else:
decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
return decoded_binary_secret
# Example usage
def connect_to_database():
secret = get_secret("production/app/database")
# Connect to the database using the secret
connection = mysql.connector.connect(
host=secret['host'],
user=secret['username'],
password=secret['password'],
database=secret['dbname']
)
return connection
3. AWS CDK Example
Common Secrets Manager Use Cases
- Finance: API keys for payment gateways, banking credentials
- Healthcare: Credentials for accessing patient record systems
- E-commerce: Database credentials, payment processor API keys
- DevOps: CI/CD pipeline credentials, deployment tokens
- SaaS: Multi-tenant database credentials, third-party API tokens
Specific Implementation: Automatic RDS Credential Rotation
Troubleshooting
1. Access Denied Errors: - Check IAM permissions for both the user and resources
- Verify KMS key permissions if using a customer managed key
- Check for resource policies restricting access
- Ensure your VPC endpoint policy allows the action
2. Rotation Failures: - Review Lambda execution logs for detailed error messages
- Ensure Lambda has proper permissions to access the secret and database
- Check network connectivity if your database is in a VPC
- Verify that the rotation Lambda matches your database type
3. Performance Issues: - Implement caching to reduce frequent API calls
- Use VPC endpoints to avoid latency when accessing from a VPC
- Check for throttling or rate limiting issues
- Consider regional replicas for global applications
Comments