Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

AWS Secrets Manager and KMS: Protect Keys and Secrets Explained

Juniors still put database passwords in Lambda environment variables in plaintext. That is a gift to anyone who can read the config. AWS Secrets Manager stores the secret encrypted; AWS KMS holds the keys that encrypt. Together they are the lock and the key factory.

In this chapter

  • Why plaintext secrets fail audits
  • Secrets Manager vs Parameter Store
  • KMS CMK concepts: key policy, grants
  • Rotation and RDS integration basics
  • Lab, errors, FAQ, interview

1. Everyday example first

A hospital app connects to RDS. Password rotates every 30 days. Secrets Manager can rotate with a Lambda; apps call GetSecretValue at runtime (or cache briefly). KMS CMK encrypts the secret string. If a laptop is stolen, the thief still needs IAM + KMS permission.

2. Why both services?

A database password and an encryption key serve different roles. Put the password in Secrets Manager so an approved app can fetch the current secret value. A KMS key can protect the data key used to encrypt that value at rest. The app calls GetSecretValue and Secrets Manager performs the service’s cryptographic work. If a customer managed key protects the secret, check the secret-reading permission and the key permission separately. A permission to use the database is also separate from permission to obtain its password.

KMS is about keys and cryptographic operations. Secrets Manager is about storing rotating application secrets. Parameter Store (SSM) can store SecureStrings with KMS too — pick Secrets Manager when you need managed rotation and fine secret lifecycle.

ServiceUse for
KMSCreate/control CMKs, encrypt data keys
Secrets ManagerDB creds, API tokens, rotation
SSM Parameter StoreConfig and simpler secrets
Read a secret without embedding it in codeApplication identity: Uses its assigned role; GetSecretValue: Requests the named secret; Service permissions: Checks secret access and applicable key policy; Decryption: Secrets Manager uses AWS KMS; Application: Uses the value without logging itApplication identityUses its assigned roleGetSecretValueRequests the named secretService permissionsChecks secret access and applicablekey policyDecryptionSecrets Manager uses AWS KMSApplicationUses the value without logging it
IAM + KMS gated fetch

3. How to wire it

Rotation means replacing the old credential with a new one and coordinating the change with the service that uses it. For a practice example, imagine the secret changes from one dummy value to another. A program with the old cached value can fail after the database expects the new one. Test how the lab app notices a refresh by recording only whether access works. Keep the returned secret out of logs. If the request is denied, read the policy evidence and key condition rather than printing the secret to diagnose access.

  1. Create a CMK (or use aws/secretsmanager carefully). Prefer customer CMK for audit.
  2. Create a secret; choose RDS rotation if supported.
  3. Grant the app role secretsmanager:GetSecretValue on the secret ARN. If the secret uses a customer managed KMS key, also allow kms:Decrypt for that key. Check that its key policy allows the access either directly or through IAM.
  4. Never log the secret string.
  5. Alert on unusual GetSecretValue spikes.
  6. Document break-glass procedure.
{
  "Effect": "Allow",
  "Action": ["secretsmanager:GetSecretValue"],
  "Resource": "arn:aws:secretsmanager:ap-south-1:111122223333:secret:prod/db-*"
}

4. Industries

  • BFSI: mandatory rotation + CMK where required
  • SaaS multi-tenant: per-tenant API tokens
  • Healthcare: audit who decrypted
  • Startups: stop Slack-shared passwords

5. Lab: create a dummy secret and read it

Use a dummy value unrelated to real logins. Verify the authorized lab identity can retrieve it without displaying or recording the value. Compare with a test identity without access, which should receive a denial. If you test a customer managed key, document which permission controls decryption. Afterward schedule deletion according to the lab’s cleanup steps and check the secret’s pending state.

Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.

  1. KMS → create symmetric CMK alias alias/lab-secrets.
  2. Secrets Manager → store new secret lab/demo string not-a-real-password.
  3. Encrypt with your CMK.
  4. From CloudShell get-secret-value in ap-south-1 with a lab role.
  5. Note CloudTrail shows the API call.

Cleanup (stop billing)

  1. Delete the secret schedule and schedule CMK deletion (7–30 days).
  2. Remove lab IAM policies.

6. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
Secret in Lambda env plaintextMove to Secrets Manager; inject at runtime.
Resource star on GetSecretValuePin secret ARN.
Disabled CMK broke prodMonitor CMK state; staged disable.
Rotation Lambda fails silentlyAlarm on rotation errors.
Cached secret forever in memoryShort TTL cache; refresh on auth errors.
Shared secret across 40 appsSplit secrets; least blast radius.
Put secret in AMIBake no secrets; fetch at boot.
Forgot replica for multi-regionReplicate secret + key strategy.
Developers all AdminSeparate read roles; break-glass only.
Printed secret in CI logsMask; use OIDC roles.

7. Troubleshooting checklist

  1. AccessDeniedException → IAM + key policy both.
  2. Secret pending deletion — restore if needed.
  3. Rotation: check Lambda VPC/SG to DB.
  4. Decrypt failures after key policy edit — rollback policy.
  5. Wrong region secret id.
  6. CloudTrail not showing? Include management events.

8. FAQ

Q. Secrets Manager vs SSM SecureString?

Secrets Manager shines at rotation and secret lifecycle.

Q. Who can decrypt?

In the same account, a KMS key policy can allow a principal directly or let an IAM policy grant access. Check for applicable explicit denies.

Q. Envelope encryption?

KMS encrypts data keys; data keys encrypt bulk data.

Q. Cost worry?

Secrets and API calls cost; delete unused.

Q. Can I use CMK with S3/EBS too?

Yes — same CMK discipline.

9. Interview Q&A

Q. Why not env vars for DB passwords?

Visible in console/config; hard to rotate; often logged.

Q. What does KMS do?

Manages keys and encrypt/decrypt/generate data keys.

Q. CMK vs AWS managed key?

CMK: you control policy and rotation options.

Q. How rotation works?

Lambda updates DB and secret versions in stages.

Q. Least privilege for secrets?

GetSecretValue on exact ARN + kms:Decrypt on that CMK.

Q. Detect misuse?

CloudTrail + metric alarms on GetSecretValue.

10. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

Treat every secret like a house key: know who has a copy and change the locks on a schedule.

Ravindra Bagale's Tip (MR)

Secret = घरची चावी: copy कोणाकडे, schedule वर locks बदला.

Tip (HI)

हर secret घर की चाबी है — किसके पास copy है जानो और समय पर ताले बदलो।

Try at home

  1. Scan one personal project for hardcoded passwords.
  2. Write IAM policy for one secret ARN only.
  3. Explain envelope encryption to a friend in 60 seconds.

In short

  1. Secrets Manager stores rotating secrets.
  2. KMS holds and controls encryption keys.
  3. IAM + key policy together gate decrypt.
  4. No plaintext secrets in env, AMI, or Git.

Revision, interview and comparison cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: Secrets Manager + KMS. Passwords in git or Lambda env plaintext leak and rarely rotate. Secrets Manager stores secrets; KMS encrypts them. Apps retrieve at runtime with IAM. Create secret → encrypt with CMK → grant app role secretsmanager:GetSecretValue + kms:Decrypt → rotate. RDS password lives in Secrets Manager; Lambda reads it each cold start or caches briefly.
Revision card: Secrets Manager + KMS · Download PNG · Open card page
Revision card: Automatic rotation. Static DB passwords for years are a breach waiting to happen. Rotation uses a Lambda that creates a new password, updates DB and secret versions (AWSPENDING → AWSCURRENT). Enable rotation schedule; test in staging; monitor rotation failures in CloudWatch. Every 30 days the clinic DB password changes without redeploying the app.
Revision card: Automatic rotation · Download PNG · Open card page
Revision card: CMK vs AWS managed. Compliance may require key policies, rotation evidence, and cross-account control. AWS managed keys are easy; customer managed keys (CMK) give key policies, grants, and clearer ownership. Use CMK for production secrets; separate keys per env; least-privilege key policy. Finance account decrypts only with finance CMK; marketing role is denied by key policy.
Revision card: CMK vs AWS managed · Download PNG · Open card page
Revision card: Least privilege for secrets. Resource * on GetSecretValue lets one breach read every secret. Grant GetSecretValue on specific secret ARNs; separate read from put/rotate roles. App role: get one secret. Admin role: create/rotate. Deny decrypt of other envs’ CMKs. Staging role cannot GetSecretValue on prod/db-password ARN.
Revision card: Least privilege for secrets · Download PNG · Open card page
Revision card: Secrets Manager vs SSM. Teams mix Parameter Store and Secrets Manager without a rule. SSM Parameter Store (SecureString) is fine for config; Secrets Manager adds rotation and richer secret lifecycle. Use Secrets Manager for DB/API credentials that must rotate; SSM for non-rotating app config. Stripe API key with rotation → Secrets Manager; FEATURE_X=true → SSM String.
Revision card: Secrets Manager vs SSM · Download PNG · Open card page
Comparison: Secrets Manager vs SSM Parameter Store. Secrets Manager: Secret lifecycle + managed rotation. SSM Parameter Store: Hierarchical config; SecureString optional.
Comparison: Secrets Manager vs SSM Parameter Store · Download PNG · Open card page
Comparison: Customer managed key (CMK) vs AWS managed key. Customer managed key (CMK): You set key policy, rotation, grants, aliases. AWS managed key: AWS manages the key; simpler, less control.
Comparison: Customer managed key (CMK) vs AWS managed key · Download PNG · Open card page
Interview card: Why Secrets Manager + KMS?. Central secret storage with encryption, IAM retrieval, and optional rotation — not git or plaintext env. KMS CMKs add key-policy control for compliance. Lambda gets DB password at runtime from Secrets Manager.
Interview card: Why Secrets Manager + KMS? · Download PNG · Open card page
Interview card: How does rotation work?. Rotation Lambda sets AWSPENDING password, updates DB, then AWSCURRENT. Monitor failures; test in staging first. 30-day schedule for clinic RDS secret.
Interview card: How does rotation work? · Download PNG · Open card page
Interview card: Secrets Manager vs SSM?. Secrets Manager for rotating credentials; SSM Parameter Store for general config (SecureString OK). Do not invent two homes for the same DB password. Stripe key→Secrets; FEATURE flag→SSM.
Interview card: Secrets Manager vs SSM? · Download PNG · Open card page
Interview card: Cross-account secret access?. Resource policy on the secret plus KMS key policy grants to the consumer account/role. Prefer pulling into the app role over copying plaintext across accounts. Analytics role in account B GetSecretValue on account A reporting-api secret.
Interview card: Cross-account secret access? · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practise this chapter

Interview questions and answers

An app is allowed to call GetSecretValue but gets a denial for a customer-managed-encrypted secret. What is your next check?

Confirm the ARN it asks for and inspect the KMS key policy and permission to decrypt with the relevant customer managed key. Secret access and cryptographic key access are evaluated separately. Reproduce with a dummy secret and log the success or denial while keeping the value private.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. Which service stores the app’s current database credential for retrieval?

Answer and explanation

B. Secrets Manager

Secrets Manager manages secret values and their versions. KMS can protect encryption keys used to encrypt those values.

2. What can fail after credential rotation if the app caches the secret?

Answer and explanation

C. It can try the old credential after the service accepts only the new one

The application needs a suitable refresh plan. Check the authentication result without recording the secret.

3. What evidence should a dummy-secret test record?

Answer and explanation

A. Allow or deny outcome and which identity attempted the operation

Use non-sensitive evidence and test both intended success and denial.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Amravati Agro Market is a agriculture business in Amravati. Anjali Thakre looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy List secrets

Inventory secrets.

List secrets.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Describe secret

Metadata without value.

Describe secret amravatiagro/db.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy List keys

See CMKs.

List KMS keys.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy List aliases

Human names for keys.

List aliases.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Min recovery window days

Delete schedule.

Minimum recovery window days often used in labs (enter 7)?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Plaintext env bad — enter 0 for allowed?

Never plaintext.

Is plaintext DB password in Lambda env OK? Enter 0 for no.

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Get secret value

Runtime fetch.

Get secret value amravatiagro/db.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Describe key

Check state/policy.

Describe key alias/lab-secrets.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Decrypt on one key

Apps need decrypt.

Allow kms:Decrypt on arn:aws:kms:ap-south-1:120348739971:key/abcd-efgh.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Secret string JSON

Structured secrets.

JSON username app password changeme.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Medium Apply the lesson: scenario 11

A role in account A needs to use a KMS key in account B. Account A already grants IAM permission. Which policy on the key must also permit the cross-account use?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Short TTL minutes classroom

Do not cache forever.

A short classroom secret cache TTL in minutes (enter 5)?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Rotate secret

Trigger rotation.

Rotate secret amravatiagro/db.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Delete secret schedule

Cleanup labs safely.

Delete secret amravatiagro/lab with recovery window 7.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard GetSecretValue pinned

No star resources.

Allow secretsmanager:GetSecretValue on arn:aws:secretsmanager:ap-south-1:120348739971:secret:amravatiagro/db-*.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Hard Rotation days JSON

Schedule rotation.

JSON RotationDays 30.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.