Secrets Manager

Difficulty: Intermediate

Question

Why would you use AWS Secrets Manager instead of Systems Manager Parameter Store for database passwords and API keys?

Answer

Use Secrets Manager when a secret needs automatic rotation, cross-Region replication, cross-account access through resource policies, or larger values, and accept that it costs money per secret. Use Parameter Store (SecureString) for configuration and for secrets that rarely change, because its standard tier is free. Both encrypt with AWS KMS and are controlled by IAM, so the deciding factor is usually rotation: Secrets Manager can change an RDS password on a schedule and update the secret without application downtime.

Feature comparison

FeatureSecrets ManagerParameter Store
Primary purposeSecrets with a lifecycleConfiguration and simple secrets
EncryptionAlways KMS-encryptedSecureString uses KMS; String is plaintext
Automatic rotationBuilt in, Lambda-based, with managed rotation for RDS, Aurora, Redshift, DocumentDBNo native rotation
Max size64 KB4 KB standard, 8 KB advanced
Cross-Region replicationYesNo
Resource-based policy (cross-account)YesNo (advanced parameters can be shared via AWS RAM)
VersioningStaging labels AWSCURRENT, AWSPENDING, AWSPREVIOUSNumbered versions and labels
CostAbout $0.40 per secret per month plus API callsStandard tier free; advanced parameters and higher throughput are charged

How rotation works

Rotation uses a Lambda function with four steps, and the staging labels let applications keep working throughout:

  1. createSecret: generate a new password and store it as AWSPENDING.
  2. setSecret: change the password in the database.
  3. testSecret: log in with the new password to verify it.
  4. finishSecret: move AWSCURRENT to the new version; the old one becomes AWSPREVIOUS.

Applications always read AWSCURRENT. For RDS and Aurora you can go further and let RDS manage the master password in Secrets Manager (--manage-master-user-password), which handles rotation for you. For applications that cannot tolerate a brief window of mismatched credentials, the alternating users strategy rotates between two database users.

Using secrets safely in applications

  • Fetch at startup and cache in memory; do not call Secrets Manager on every request. The AWS Parameters and Secrets Lambda Extension and the client-side caching libraries handle this.
  • On authentication failures, refresh the cached secret once before failing, in case it was just rotated.
  • ECS task definitions and EKS (via the Secrets Store CSI driver) can inject secrets as environment variables or files, so they never appear in images or source code.
  • Grant secretsmanager:GetSecretValue on specific secret ARNs only, and use a customer-managed KMS key if you need tighter control or cross-account access.

A common combined pattern

Keep non-sensitive config (feature flags, URLs, timeouts) in Parameter Store hierarchies like /prod/payments/, and put credentials that should rotate (database passwords, a payment gateway API key) in Secrets Manager. Parameter Store can even reference a Secrets Manager secret through the /aws/reference/secretsmanager/ path, so code can read everything through one API.

Gotchas

  • Rotation for a database in a private subnet requires the rotation Lambda to reach both the database and the Secrets Manager endpoint (VPC endpoint or NAT).
  • Deleting a secret is scheduled with a recovery window (7 to 30 days) unless forced, which can surprise you when recreating a secret with the same name.
  • Secrets in plain environment variables are visible to anyone who can describe the function or task; prefer fetching at runtime.
Secrets Manager rotation lifecycle. Staging labels let the new password be created and tested before applications switch to it.
  1. createSecret: New password stored with the AWSPENDING label.
  2. setSecret: Rotation Lambda updates the password in the database.
  3. testSecret: Lambda logs in with the pending credentials.
  4. finishSecret: AWSCURRENT moves to the new version.
  5. Applications refresh: Cached clients pick up AWSCURRENT on next fetch.

Code examples

Reading a secret with caching in Python

import json
import boto3
from botocore.exceptions import ClientError

sm = boto3.client("secretsmanager")
_cache = {}

def get_db_credentials(secret_id="prod/payments/db", refresh=False):
    if refresh or secret_id not in _cache:
        try:
            resp = sm.get_secret_value(SecretId=secret_id)  # AWSCURRENT by default
        except ClientError as e:
            raise RuntimeError(f"Cannot read secret: {e.response['Error']['Code']}")
        _cache[secret_id] = json.loads(resp["SecretString"])
    return _cache[secret_id]

creds = get_db_credentials()
# On an auth failure, call get_db_credentials(refresh=True) once and retry

Caching avoids an API call per request, and refreshing on auth failure handles the moment just after a rotation.

Enable rotation every 30 days and compare with Parameter Store

aws secretsmanager rotate-secret \
  --secret-id prod/payments/db \
  --rotation-lambda-arn arn:aws:lambda:ap-south-1:111122223333:function:pg-rotation \
  --rotation-rules AutomaticallyAfterDays=30

# Parameter Store: free standard tier SecureString, no rotation
aws ssm put-parameter --name /prod/payments/gateway-url \
  --type String --value https://api.example-gateway.in
aws ssm get-parameter --name /prod/payments/api-key --with-decryption

Secrets Manager rotates on a schedule using the Lambda; Parameter Store simply stores and returns values, which is enough for config.

Key points

  • Secrets Manager: built-in rotation, replication, resource policies, 64 KB, paid per secret
  • Parameter Store: free standard tier, SecureString with KMS, no native rotation, 4 KB (8 KB advanced)
  • Rotation uses createSecret, setSecret, testSecret, finishSecret with AWSPENDING and AWSCURRENT labels
  • Cache secrets in the application and refresh on auth failure
  • Common pattern: config in Parameter Store, rotating credentials in Secrets Manager

Common follow-up questions

  • How does Secrets Manager rotate an RDS password without breaking running applications?
  • How would you give a Lambda function access to one secret only?
  • How do you avoid hitting Secrets Manager API costs and limits at high request rates?
  • When is Parameter Store perfectly fine for a secret?

Interview tips

  • Lead with rotation as the main differentiator, then mention cost, size, replication, and cross-account policies
  • Explain the staging labels during rotation; it shows you understand zero-downtime rotation
  • Do not claim Parameter Store is insecure; both use KMS, the difference is lifecycle features and cost

Concepts covered

AWS Secrets Manager, SSM Parameter Store, Secret Rotation, KMS Encryption, Cross-Region Replication

More AWS & Cloud Fundamentals questions