A secrets manager lets an application fetch sensitive values, such as database credentials, at runtime instead of keeping them in source code. Pair it with a short-lived IAM role that can read only the required secret. section 11.5.1
Replace fragile hardcoded credentials with a runtime retrieval pattern:
- Hardcoded credentials can leak through source control, require redeployment when changed, and give attackers excessive access if they belong to an administrator account. section 11.5.1
- Fetch credentials at runtime using a server or container's short-lived IAM role, limited to reading the specific secret it needs. section 11.5.1
- Plan for rotation: handle an unauthorized response by refreshing credentials and retrying to avoid manual intervention and downtime. section 11.10
Listing 11.2 Secure Runtime Retrieval Refactor
import boto3
import json
from botocore.exceptions import ClientError
def get_database_credentials():
secret_name = "prod/BillingDatabase/Credentials"
region_name = "us-east-1"
# 1. Connect to the highly secure Secrets Manager
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
# 2. Request the credentials at runtime
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
raise e #A
# 3. Parse the secure response
secret_string = get_secret_value_response['SecretString']
secret_dict = json.loads(secret_string)
# 4. Return the credentials to be used by the ORM/Database connection
return secret_dict['username'], secret_dict['password']
db_user, db_pass = get_database_credentials() #B
connect_to_database(db_user, db_pass)
See a Python example using boto3 to request a named secret from AWS Secrets Manager and parse the returned credentials. section 11.5.1
For local development, environment variables can mimic runtime secret delivery; a source-control-excluded .env file is one suggested workflow. section 11.8
