Protect keys and secrets with KMS and Secrets Manager
Retrieve and rotate a secret and explain which key policy, IAM policy and store each step depends on.
By Invicly Tech, , in AWS Cloud Engineering. About 12 minutes to read.
In short
AWS KMS holds encryption keys and decides who may use them, while Secrets Manager and Parameter Store hold the values your code needs, such as database passwords and API keys. Every read of an encrypted secret depends on three things: the store's own permission, the IAM policy of the caller and the KMS key policy. Rotation replaces a secret on a schedule so a leaked value stops working.
Think of it like this: KMS is the locksmith who keeps the master keys, and Secrets Manager is the locked cabinet whose lock the locksmith controls.
Explained simply
Your worker needs a database password. Writing it in code or Git means anyone who sees the code sees the password, and changing it means a new release. A secret store solves this: the password lives in one protected place, and the worker asks for it at run time, using its IAM role to prove who it is.
AWS has two stores. Secrets Manager is built for secrets: it keeps versions, can rotate a password on a schedule, and costs a small amount per secret each month. Parameter Store, part of Systems Manager, is built for configuration: standard parameters are free, and a SecureString parameter keeps a value encrypted.
Both stores encrypt values with AWS KMS, the Key Management Service. KMS holds keys that never leave it in plain form. Each key has a key policy, a document that says who may use or manage it. If the policy says no, nobody can decrypt, even an administrator with broad IAM permissions.
Rotation means replacing a secret regularly. If an old password leaks, it soon stops working. Secrets Manager rotates by calling a Lambda function that creates a new password, sets it in the database, tests it and then marks it as current. Clients that fetch the secret each time, or cache it briefly, never notice.
Press Play on a diagram to walk through it one step at a time.
- Worker role to Secrets Manager: GetSecretValue lab/db (IAM allows it)1GetSecretValue lab/db (IAM allows it)
- Secrets Manager to KMS: Decrypt the secret's data key for this caller2Decrypt the secret's data key for this caller
- KMS to Secrets Manager: Key policy and IAM allow kms:Decrypt: data key3Key policy and IAM allow kms:Decrypt: data key
- Secrets Manager to Worker role: AWSCURRENT secret value4AWSCURRENT secret value
- Per-secret monthly charge
- Values up to 64 KB
- Managed rotation with Lambda
- Versions with staging labels
- Cross-account and multi-Region
- Standard parameters free
- 4 KB standard, 8 KB advanced
- No built-in rotation
- Hierarchical paths
- SecureString uses KMS
In depth
KMS keys and key policies
There are three kinds of KMS key owners. AWS owned keys are used by services behind the scenes and you never see them. AWS managed keys, with aliases such as aws/secretsmanager or aws/ssm, are created for you in your account; you can see them but not change their policy. Customer managed keys are yours: you write the key policy, turn rotation on or off, and schedule deletion. They cost a monthly fee per key plus a small charge per request.
Every KMS key has exactly one key policy. The default policy contains a statement that trusts the account itself, which lets IAM policies grant use of the key. Remove that statement and IAM policies alone no longer work; only principals named in the key policy can use the key. Separate key administrators (who manage the key) from key users (who encrypt and decrypt).
- Key users: kms:Encrypt, kms:Decrypt, kms:GenerateDataKey
- Key admins: kms:Put*, kms:Enable*, kms:ScheduleKeyDeletion
- Automatic rotation keeps old material, so old data still decrypts
- Deletion waits 7 to 30 days; disable the key first to test impact
Envelope encryption in one picture
KMS can encrypt at most 4 KB directly, so services use envelope encryption. They ask KMS for a data key with GenerateDataKey. KMS returns the data key twice: once in plain form and once encrypted under your KMS key. The service encrypts the data locally with the plain data key, throws the plain copy away and stores the encrypted data key next to the data.
To read the data, the service sends the encrypted data key to KMS, which checks permissions and returns the plain data key. This is why reading a secret encrypted with a customer managed key needs kms:Decrypt: the permission check happens at that moment, for that caller. It also means disabling the key instantly blocks every future read, a useful emergency switch.
- 1GenerateDataKey
KMS returns plain and encrypted data key
- 2Encrypt locally
Service encrypts the secret with the plain key
- 3Discard plain key
Only the encrypted data key is stored
- 4Decrypt request
Encrypted key goes back to KMS with caller identity
- 5Permission check
Key policy and IAM decide; data key returned or denied
Secrets Manager or Parameter Store
Secrets Manager stores values up to 64 KB, keeps versions with staging labels, supports managed rotation, resource policies for cross-account access and replication to other Regions. It charges per secret per month and per API call. Services such as Amazon RDS can manage a database's master password in Secrets Manager for you.
Parameter Store has standard parameters (free, up to 4 KB, up to 10,000 per Region) and advanced parameters (paid, up to 8 KB, with policies such as expiry). It organises values in paths such as /prod/files/api-url, which makes IAM permissions by path easy. It has no built-in rotation. A common split is configuration and low-risk values in Parameter Store, and anything that must rotate in Secrets Manager.
In Lambda, the AWS Parameters and Secrets Lambda Extension caches values locally, which cuts both latency and API cost.
- Need rotation: Secrets Manager
- Plain config or feature flags: Parameter Store String
- Small encrypted value, no rotation: SecureString
- Cache values; do not call the store on every request
Rotation without downtime
A rotation Lambda runs four steps. createSecret makes a new value and stores it with the AWSPENDING label. setSecret applies it to the database or service. testSecret logs in with it. finishSecret moves AWSCURRENT to the new version, and the old one gets AWSPREVIOUS. If a step fails, AWSCURRENT stays on the old version and clients keep working.
The risky part is clients that hold the old password. The single-user strategy changes one user's password, so a long-lived connection pool may break when it reconnects with a stale cached value. The alternating-users strategy keeps two database users and switches between them, so the previous credentials still work until the next rotation. Either way, clients should re-fetch the secret when a login fails.
You set a schedule with rotation rules, such as every 30 days, and can trigger rotation at once with rotate-secret.
- AWSPENDING: being created and tested
- AWSCURRENT: what clients should use
- AWSPREVIOUS: the last good version, for rollback
- Retry with a fresh fetch on authentication errors
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Read a KMS key policy~35m
- 2Encrypt with a customer managed key~35m
- 3Store a secret in Secrets Manager~35m
- 4Compare with Parameter Store~35m
- 5Rotate a secret without downtime~35m
Key points
- Every KMS key has exactly one key policy; IAM policies only count if the key policy allows the account to use IAM.
- Customer managed keys give you control of the policy, rotation and deletion; AWS managed keys do not.
- Secrets Manager adds rotation, versioning and cross-account sharing; Parameter Store is cheaper and good for config.
- Rotation keeps old and new versions side by side through staging labels, so clients can switch without downtime.
- Deleting a KMS key is final after a 7 to 30 day waiting period, so disable it first and watch for errors.
Key terms
Tap a card to flip it. 0/5 known
Examples
aws secretsmanager create-secret --name lab/db \
--kms-key-id alias/lab-secrets \
--secret-string '{"username":"app","password":"example-only"}'
aws secretsmanager get-secret-value --secret-id lab/db \
--query SecretString --output text
aws ssm put-parameter --name /lab/api-url --type String \
--value https://api.example.comUse placeholder values only. A secret encrypted with a customer managed key also needs kms:Decrypt for the reader.
Debugging an AccessDenied on a secret
The worker logs AccessDeniedException when it calls GetSecretValue for lab/db. Step 1: read the message. If it names kms:Decrypt, the store allowed the call but KMS refused. Step 2: check the secret's key with describe-secret; it shows KmsKeyId alias/lab-secrets, a customer managed key. Step 3: read the key policy. The default account statement is there, so IAM can grant use. Step 4: add kms:Decrypt on that key ARN to the worker's role policy. Expected evidence: the next invocation reads the secret and CloudTrail shows a successful Decrypt by the worker role.
aws secretsmanager describe-secret --secret-id lab/db \
--query KmsKeyId
aws kms get-key-policy --key-id alias/lab-secrets \
--policy-name default --output text
# Add to the worker role policy:
# {"Effect":"Allow","Action":"kms:Decrypt",
# "Resource":"arn:aws:kms:eu-west-1:111122223333:key/<key-id>"}Reading a secret safely from Python
The worker reads the secret once per cold start and keeps it in memory, instead of on every message. If the database rejects the password, it fetches again, because rotation may have just changed it. This keeps API calls low and survives rotation. Prerequisites: boto3, a role with secretsmanager:GetSecretValue on the secret and kms:Decrypt on its key.
import json, boto3
sm = boto3.client("secretsmanager")
_cache = None
def db_credentials(refresh: bool = False) -> dict:
global _cache
if _cache is None or refresh:
value = sm.get_secret_value(SecretId="lab/db")["SecretString"]
_cache = json.loads(value)
return _cache
# On a login failure: creds = db_credentials(refresh=True)Quick reference
- Every KMS key has exactly one key policy; IAM only works if the key policy trusts the account
- Reading a secret under a customer managed key needs kms:Decrypt as well
- KMS key deletion waiting period: 7 to 30 days (default 30); disable first
- Staging labels: AWSPENDING, AWSCURRENT, AWSPREVIOUS
- Rotation steps: createSecret, setSecret, testSecret, finishSecret
- aws ssm get-parameter --name /lab/token --with-decryption
- Standard parameters: free, 4 KB; advanced: paid, 8 KB, policies
Common mistakes
- Granting secretsmanager:GetSecretValue but forgetting kms:Decrypt on the customer managed key.
- Rotating a single shared database user while long-lived connections still use the old password.
- Putting secrets in Lambda environment variables or in Git instead of reading them from a store.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Store a placeholder API URL in Parameter Store as a String and a placeholder token as a SecureString, then read both back.
- Exercise 2medium
Create a customer managed key with an alias, create a secret encrypted with it, and show that a role without kms:Decrypt cannot read the secret.
- Exercise 3hard
Design zero-downtime rotation for the worker's database password. Choose single-user or alternating users, and describe what the worker does when a login fails.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is it safe to put secrets in Lambda environment variables?
- They are encrypted at rest, but anyone who can view the function configuration can read them, and changing one means updating the function. A secret store with IAM access and rotation is safer.
- Does KMS key rotation re-encrypt my old data?
- No. Automatic rotation adds new key material for new encryptions and keeps the old material so existing data still decrypts. The key ID and ARN stay the same.
- Can I practise this without an AWS bill?
- Parameter Store standard parameters are free. For KMS and Secrets Manager, a local emulator such as LocalStack, or the moto library in Python tests, lets you rehearse the calls offline.