How to manage secrets with AWS Secrets Manager
Store, retrieve, cache, and rotate application secrets with AWS Secrets Manager and least-privilege IAM. Includes CloudTrail auditing and rotation.
Hardcoded secrets in code or environment variables leak. AWS Secrets Manager stores credentials encrypted with KMS, controls access with IAM, and can rotate them automatically. Applications fetch secrets at runtime rather than embedding them.
Prerequisites
- An AWS account, Node.js, and Terraform.
- The
@aws-sdk/client-secrets-managerpackage.
Steps
1. Create a secret
aws secretsmanager create-secret --name prod/db --secret-string '{"username":"app","password":"s3cr3t"}'
Store structured JSON so one secret can hold related fields.
2. Restrict access with IAM
Grant only the workload's role permission to read the specific secret ARN:
{ "Effect": "Allow", "Action": "secretsmanager:GetSecretValue", "Resource": "<secret-arn>" }
Never grant secretsmanager:* on *.
3. Retrieve at runtime
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
const sm = new SecretsManagerClient({});
const { SecretString } = await sm.send(new GetSecretValueCommand({ SecretId: "prod/db" }));
const creds = JSON.parse(SecretString);
4. Cache the secret
Fetching on every request adds latency and cost. Cache the value in memory for a few minutes and refresh on expiry or on an authentication failure.
5. Enable rotation
Attach a rotation Lambda and a schedule so the password changes automatically:
aws secretsmanager rotate-secret --secret-id prod/db --rotation-lambda-arn <arn> --rotation-rules AutomaticallyAfterDays=30
Rotation updates both the secret and the backing database user.
6. Audit access
Every GetSecretValue call is logged in CloudTrail. Review it to spot unexpected access.
Verification
Run the app and confirm it reads the secret without it appearing in code or env vars. Trigger a rotation and confirm the application picks up the new value after its cache expires. Check CloudTrail for the retrieval events.
Next Steps
Use resource policies for cross-account access, replicate secrets to other regions for disaster recovery, and compare with SSM Parameter Store for non-rotating config.
Prerequisites
- AWS account
- Node.js installed
- Terraform installed
Steps
- 1Create a secret
- 2Restrict access with IAM
- 3Retrieve at runtime
- 4Cache the secret
- 5Enable rotation
- 6Audit access