AWS from zero · Part 6: Operating, securing and governing · Lesson 34 of 38 · about 45 minutes

KMS and Secrets Manager

Juniper & Rye gets an encryption key of its own, encrypts with it directly and through S3, and keeps the supplier password in Secrets Manager under it. Then the key is switched off: KMS and Secrets Manager stop at once, S3 only partly, and differently in two runs. CloudTrail shows every use of the key, including the ones AWS services made for you. All for under a cent.

By the end you'll know

  • The three kinds of KMS key, and when paying for your own is worth it
  • What a key policy is, and why the default one hands control to IAM
  • How encryption context works, and why KMS won't encrypt more than 4 KB
  • What envelope encryption is, and how S3 does it for you
  • How Secrets Manager stores, versions and hands out a secret
  • What happens to your data when a key is disabled, and what deleting one would do

Before you start

  • You need: the juniper-rye profile, signed in, and Lesson 20's virtual environment. Lesson 3 covers the policies a key policy works with, Lesson 15 the bucket, and Lesson 33 the event history the last step reads.
  • The script: lab.py from the practice folder's lesson-34. Everything it creates is named jr-lesson34-* and tagged lesson=34, and its delete step removes it.
  • Where you run things: your own machine, labeled (Your machine).
  • Every output below is from real runs on November 16, 2026, at about 2:20am in New York, which is 7:20am UTC. The lab was run twice; the section "Switch the key off" explains why both runs matter.

A deleted key takes your data with it

Anything encrypted under a KMS key can only be decrypted by that key. Delete the key and the data is gone for good, along with every backup encrypted the same way. That's why KMS never deletes a key straight away: you schedule it, and it waits 7 to 30 days, during which you can cancel. A customer managed key is $1.00 a month while it exists and costs nothing while it waits to be deleted.

The short version

  • KMS holds keys that never leave it. You send it data, or ask it for data keys; you never get the key itself.
  • Envelope encryption: KMS encrypts a small data key, and the data key encrypts the file. S3, Secrets Manager and EBS all work this way.
  • A key policy decides who can use a key. The default one lets IAM policies in the account decide.
  • Secrets Manager stores secrets encrypted with a KMS key, keeps versions, and can rotate them.
  • Disabling a key stops new decryption at once, except where a service still holds a data key it already decrypted.
  • CloudTrail records every use of a key, including uses AWS services made on your behalf.

What this lesson costs

PartPriceThis lab
A customer managed key$1.00 a month, by the hourTwo keys for a few minutes each
A key waiting to be deletedFree7 days, twice
KMS requests$0.03 per 10,000, after 20,000 free a monthAbout 120
A secret$0.40 a month, by the hourA few minutes, twice
Secrets Manager calls$0.05 per 10,000About 20
This lessonUnder a cent

Keys, and who holds them

Encryption is easy; keys are hard. A key in a config file, an environment variable or a laptop is a key someone can copy. KMS (Key Management Service) keeps keys inside hardware security modules that AWS runs, and the key material never leaves them: you send KMS data to encrypt, or ask it for a data key, and IAM and the key's own policy decide whether you may.

KMS is the bank's safe deposit room. Juniper & Rye never takes the master key home. When the bakery needs to lock away a recipe, it puts the recipe in a box with its own small padlock, and asks the bank to lock that padlock's key in the vault. Opening the recipe later means asking the bank for the padlock key back, and the bank checks ID first, every time, and writes it in the ledger.

There are three kinds of KMS key:

AWS ownedAWS managedCustomer managed
Looks likeInvisible to youaws/s3, aws/ebsYour own, with your alias
Made byA service, shared across accountsA service, in your account, on first useYou
Key policyNone you can seeFixed by AWSYours to write
Disable, delete, rotateNoNo; rotated yearly by AWSYes
CostFreeFree to own; requests are charged$1.00 a month, plus requests

Pay for your own key when you need control: to decide exactly who can decrypt, to share encrypted data with another account, or to be able to switch it off. Otherwise the AWS managed key is fine, and free.

(Your machine)

BASH
cd ~/Apps/aws-practice/lesson-34
source ../lesson-20/.venv/bin/activate
python lab.py fence
OUTPUT
== Keys already in this account, in us-east-2
  AWS managed:      alias/aws/backup
  AWS managed:      alias/aws/rds
  AWS managed:      alias/aws/lightsail
  AWS managed:      alias/aws/secretsmanager
  AWS managed:      alias/aws/lambda
  AWS managed:      alias/aws/ebs
  AWS managed:      alias/aws/ssm
  AWS managed:      alias/aws/elasticfilesystem
  customer managed: 1; AWS managed: 8
  secrets in Secrets Manager: 0
== Prices in us-east-2 (from the Price List API)
  us-east-2-KMS-Requests             $0.000003   $0.03 per 10000 KMS requests in US East (Ohio)
  us-east-2-KMS-Keys                 $1          $1 per customer managed KMS key version in US East (Ohio)
  USE2-AWSSecretsManager-Secrets     $0.4        $0.40 per Secret

Eight AWS managed keys already, made by earlier lessons. RDS, EBS, Backup, Lambda and the rest each created one the first time they encrypted something. The one customer managed key is from the first run of this lab, waiting to be deleted.

"Per customer managed KMS key version" matters for rotation: each time a key rotates, it keeps the old version so old data still decrypts. AWS charges $1.00 a month more for each of the first two rotations, and nothing for later ones.

A key of your own

BASH
python lab.py key
OUTPUT
== Creating a key for Juniper & Rye
== The key, by its alias alias/jr-lesson34-recipes
  KeyId        d63f8362-cc3a-48bc-ada0-55be0421e972
  KeyManager   CUSTOMER
  KeySpec      SYMMETRIC_DEFAULT
  KeyUsage     ENCRYPT_DECRYPT
  Origin       AWS_KMS
  KeyState     Enabled
  MultiRegion  False
  Created      07:23:38 UTC
== Its key policy, the one AWS gives a new key
  {
    "Version": "2012-10-17",
    "Id": "key-default-1",
    "Statement": [
      {
        "Sid": "Enable IAM User Permissions",
        "Effect": "Allow",
        "Principal": {
          "AWS": "(an ARN)"
        },
        "Action": "kms:*",
        "Resource": "*"
      }
    ]
  }
== Automatic rotation: on, every 365 days; next one 2027-11-16
  • SYMMETRIC_DEFAULT is a 256-bit AES key, the same key encrypting and decrypting. KMS also has asymmetric keys, for signing and for encrypting where the other side only has the public half.
  • An alias is a friendly name that points at a key, and can be moved to another key later. Code that uses alias/jr-lesson34-recipes never needs the key ID.
  • The key policy is the first thing KMS checks. Unlike almost everything else in AWS, a key isn't usable by anyone just because an IAM policy says so: the key policy has to allow it, or has to hand the decision to IAM. The default policy does that: its principal is the account itself (the ARN hidden here ends in :root), which means "IAM policies in this account decide". Without that statement, even the account's administrators can't use the key, and a key policy that locks everyone out can only be fixed by AWS Support.
  • Rotation every 365 days makes new key material for new encryption, and keeps the old versions so old ciphertext still decrypts. Nothing you encrypted has to be redone.

Encrypt and decrypt

KMS can encrypt small things itself, like a password or a short note. The encryption context is a set of names and values sent along with the data: it isn't secret, but it's bound into the ciphertext, has to match exactly to decrypt, and is written into CloudTrail, so the log says what was decrypted, not just that something was.

BASH
python lab.py encrypt
OUTPUT
== Encrypting 66 bytes with alias/jr-lesson34-recipes, and an encryption context {"app": "orders", "purpose": "supplier-login"}
  ciphertext: 222 bytes, starts AQICAHjaogKg1ToERTOZhB+Y…
== Decrypting it, without saying which key
  key used:   this one (the ciphertext says which key, so you don't have to)
  plaintext:  Supplier portal: Juniper & Rye account 4471, deliveries before 6am
== Decrypting with a different context
  InvalidCiphertextException: the context is part of what was encrypted, so it must match exactly
  without any context: InvalidCiphertextException
== Encrypting a 5,000-byte recipe file directly
  ValidationException: 1 validation error detected: Value at 'plaintext' failed to satisfy constraint: Member must have length less than or equal to 4096
  • 66 bytes became 222. The ciphertext carries which key and which key version made it, so decrypting needs no key ID. It starts with a short header, then bytes that name the key: jaogKg1ToERTOZhB+Y appears here and again in the data key below, because both came from the same key.
  • The wrong context and no context both fail, with the same error as a corrupted ciphertext. Someone who copies an encrypted value out of one place can't decrypt it in another place that sends a different context.
  • 4,096 bytes is the most KMS will encrypt. That isn't a limit you work around by sending pieces: it's KMS telling you to use envelope encryption.

Envelope encryption

For anything bigger than a note, KMS hands out a data key: a fresh 256-bit key, given to you twice, once in plain form and once encrypted under your KMS key. You encrypt the file with the plain one on your own machine, throw it away, and store the encrypted one next to the file. To read the file later, you send the encrypted data key to KMS, get the plain one back, and decrypt locally.

Envelope encryption with a KMS key and a data keyYour code asks KMS to generate a data key. KMS returns the data key twice: in plain form, and encrypted under the KMS key, which never leaves KMS. The plain data key encrypts the file on your side and is then discarded. The encrypted file and the encrypted data key are stored together. To read the file, the encrypted data key goes back to KMS to be decrypted, and the plain data key decrypts the file.KMS keynever leaves KMS$1.00 a monthGenerateDataKeyPlain data keyused once, then thrown awayEncrypted data keyonly KMS can open itencryptsThe fileany sizestored with the fileStoredfile + its key,both encryptedTo read it back, KMS decrypts the data key, and the data key decrypts the file.
Only a few hundred bytes ever go to KMS, however big the file is. S3, EBS and Secrets Manager all do this for you.
BASH
python lab.py envelope
OUTPUT
== By hand: ask KMS for a data key
  the data key:          32 bytes, used in memory and then thrown away (sha256 e1319d6242ec…)
  the encrypted copy:    184 bytes, AQIDAHjaogKg1ToERTOZhB+Y…, stored next to the data
  later, KMS decrypts the copy: sha256 e1319d6242ec…, the same key
  (the file itself is encrypted with the data key on your machine; KMS never sees it)
== S3 doing it for you: bucket jr-lesson34-recipes-6a53f20c, encrypted by default with alias/jr-lesson34-recipes
  uploaded 3 recipes with no encryption settings in the upload itself
  croissant.txt: ServerSideEncryption aws:kms, key this one, bucket key True
  reading it back: flour, butter, milk, sugar, yeast. Fold three times.

The script prints a fingerprint of the data key, never the key: the plain one and the one KMS gave back later match, which is the whole trick. It doesn't encrypt a file by hand, because that needs a cryptography library Lesson 20's environment doesn't have; S3 does it properly in the next lines.

S3 used the key without being asked in each upload. The bucket's default encryption names the key, so every new object is encrypted with it. The bucket key is an S3 setting worth turning on: instead of asking KMS for a data key for every object, S3 gets one bucket-level key from KMS and makes object keys from it for a while. CloudTrail, at the end, shows one GenerateDataKey call from S3 for three uploads. With thousands of uploads a minute, that's the difference between a KMS bill and none. It also matters in the next section but one.

Secrets Manager

The supplier portal's password has to live somewhere the order processor can read it, and that isn't the code, an environment variable, or a file in the repository. Secrets Manager stores it encrypted with a KMS key, controls who can read it with IAM, records every read in CloudTrail, and keeps versions so a password can be changed without a moment where the app has the wrong one.

BASH
python lab.py secret
OUTPUT
== Created secret jr-lesson34/supplier-api, encrypted with alias/jr-lesson34-recipes
  key: this lesson's key; rotation: off
== Reading it, as the order processor would
  username juniper-orders, password 32 characters (not shown), version e3fe3c97…, stages ['AWSCURRENT']
== A new password, as rotation would set it
  version e225c462…  AWSCURRENT
  version e3fe3c97…  AWSPREVIOUS
  AWSCURRENT and AWSPREVIOUS hold different passwords: True
  • The password came from Secrets Manager too: get_random_password makes a strong one, so nobody ever types or sees it.
  • Versions have staging labels. AWSCURRENT is what the app reads by default; the moment a new value is put, the old one becomes AWSPREVIOUS, still readable, so anything still using it can be rolled back.
  • Rotation is Secrets Manager running a Lambda function on a schedule that makes a new password, sets it at the supplier or database, tests it, and moves AWSCURRENT. For RDS and a few others, AWS provides the function. This lab only did the "put a new value" part by hand.
  • The first run of this step crashed reading AWSPREVIOUS a moment after setting it: Secrets Manager said that version didn't exist yet, while its own listing showed it. The script now waits and tries again; on the second run it worked first time.

Reading it in the order processor is three lines:

PYTHON
import boto3, json
value = boto3.client("secretsmanager").get_secret_value(SecretId="jr-lesson34/supplier-api")
login = json.loads(value["SecretString"])     # {"username": ..., "password": ...}

The function's role needs secretsmanager:GetSecretValue on that secret, and kms:Decrypt on the key if it's a customer managed one. Real apps cache the value for a few minutes rather than calling on every request; AWS has caching libraries for that.

Secrets Manager or Parameter Store? Lesson 11's Parameter Store can hold an encrypted SecureString for free. Secrets Manager costs $0.40 a month per secret, and earns it with rotation, versions with staging labels, and sharing across accounts. Configuration and rarely changed values go in Parameter Store; credentials that should rotate go in Secrets Manager.

Switch the key off

Disabling a key is the emergency brake: if a key's users might be compromised, turning it off stops all new decryption with it. Here's what that did, then what turning it back on did:

BASH
python lab.py off
OUTPUT
== 07:23:43 UTC: disabling the key
  key state: Disabled
  decrypt a note encrypted earlier             DisabledException
  read croissant.txt from S3                   KMS.DisabledException
  list the bucket's files                      works
  upload a new recipe                          works
  read the supplier password                   DecryptionFailure
  describe the secret (no decryption)          works
== 07:23:44 UTC: enabling it again
  key state: Enabled
  decrypt a note encrypted earlier             works
  read croissant.txt from S3                   works
  list the bucket's files                      works
  upload a new recipe                          works
  read the supplier password                   works
  describe the secret (no decryption)          works

KMS and Secrets Manager stopped at once. Anything that needed the key to decrypt failed; anything that only read names and settings, like listing files or describing the secret, carried on.

S3 was the surprise, and it was different each time. On the first run, with a different key, the same check gave:

With the key disabledFirst runSecond run
Decrypt the noteFailedFailed
Read croissant.txt from S3WorkedFailed
Upload a new recipeFailedWorked
Read the supplier passwordNot tested (that run's script crashed one step earlier)Failed

The bucket key explains both. S3 holds on to a bucket-level key it has already got from KMS and keeps using it for a while. Whatever S3 could do with what it already held worked; whatever needed a new call to KMS failed. CloudTrail agrees: in the first run, the failed call was S3's GenerateDataKey for the upload, and in the second, S3's Decrypt for the read. Which one S3 needed depended on what it had done in the seconds before. AWS documents that bucket keys are reused for a limited time, not exactly how long or for which operations, so treat the details as what we saw rather than a rule.

Disabling a key isn't instant everywhere

Services that keep data keys, like S3 with bucket keys, can keep working for a short time after a key is disabled. As an emergency brake it's still the right move; just don't assume every read stopped the same second.

Every use, recorded

Every KMS call is a management event, so it's in Lesson 33's free event history, including the calls AWS services make with your key on your behalf.

BASH
python lab.py audit
OUTPUT
== CloudTrail event history for KMS since 07:22:38 UTC (checking every 30 seconds, for up to 10 minutes)
  60 events, after 151 seconds
== Every call on KMS, by who made it
  action                 made by                        result                       count
  CreateAlias            you                            ok                           1
  CreateKey              you                            ok                           1
  Decrypt                fas.s3.amazonaws.com           DisabledException            1
  Decrypt                fas.s3.amazonaws.com           ok                           1
  Decrypt                secretsmanager.amazonaws.com   DisabledException            1
  Decrypt                secretsmanager.amazonaws.com   ok                           5
  Decrypt                you                            DisabledException            1
  Decrypt                you                            InvalidCiphertextException   2
  Decrypt                you                            ok                           3
  DescribeKey            you                            NotFoundException            2
  DescribeKey            you                            ok                           27
  DisableKey             you                            ok                           1
  EnableKey              you                            ok                           1
  EnableKeyRotation      you                            ok                           1
  Encrypt                you                            ok                           2
  GenerateDataKey        fas.s3.amazonaws.com           ok                           1
  GenerateDataKey        secretsmanager.amazonaws.com   ok                           3
  GenerateDataKey        you                            ok                           1
  GetKeyPolicy           you                            ok                           1
  GetKeyRotationStatus   you                            ok                           1
  ListAliases            you                            ok                           1
  ListKeys               you                            ok                           2
== One Decrypt made by secretsmanager.amazonaws.com (some fields left out)
  {
    "eventTime": "2026-11-16T07:23:44Z",
    "eventName": "Decrypt",
    "sourceIPAddress": "secretsmanager.amazonaws.com",
    "readOnly": true,
    "requestParameters": {
      "encryptionAlgorithm": "SYMMETRIC_DEFAULT",
      "encryptionContext": {
        "SecretARN": "(an ARN)",
        "SecretVersionId": "e225c462-e7c2-43e8-a8bc-aae415753236"
      }
    },
    "userIdentity": {
      "type": "AssumedRole",
      "invokedBy": "secretsmanager.amazonaws.com"
    }
  }
  • "Made by" a service still means you. invokedBy shows S3 or Secrets Manager made the call, but userIdentity is your role: the service used your permissions, so your role needed kms:Decrypt for the read to work. S3's calls show as fas.s3.amazonaws.com; FAS is AWS's name for these forward access sessions.
  • The encryption context says exactly which secret and which version were decrypted: Secrets Manager sets it for you. That's the encryption context earning its keep: the log says what was read, not just that something was.
  • Every failure is there: the disabled-key refusals from all three callers, and the two wrong-context attempts.
  • One GenerateDataKey from S3 for three uploads is the bucket key at work. Secrets Manager made three, for the secret's two versions. On the first run, one of its Decrypt calls was labeled RequestToValidateKeyAccess: a check, when the secret was created, that it could use the key.
  • 27 DescribeKey calls are the script itself, looking the key up by alias before almost every step.

Take it down

BASH
python lab.py delete
OUTPUT
== Deleted secret jr-lesson34/supplier-api, with no recovery window
== Deleted bucket jr-lesson34-recipes-6a53f20c and its 4 files
== Scheduled the key for deletion on 2026-11-23 02:26 UTC, the shortest wait KMS allows
  until then it can't be used, it costs nothing, and cancel_key_deletion would bring it back
== Anything left from Lesson 34
  nothing: all clear
  keys waiting to be deleted, at no charge: d63f8362… on 2026-11-23, e2c7f425… on 2026-11-23
  • Secrets also wait before they're deleted, 7 to 30 days, 30 if you don't say, so a deleted secret can be restored. The script skips that with ForceDeleteWithoutRecovery, which is fine for a lab and a bad habit anywhere else.
  • Keys always wait. 7 days is the minimum. A key waiting to be deleted can't be used and costs nothing; cancel the deletion and it's billed as if it had never been scheduled.
  • Both keys are listed, this run's and the first run's, waiting until November 23. There's nothing to do: they disappear on their own.
By hand: the same with the AWS CLI

(Your machine) A key and an alias, then encrypt and decrypt a note:

BASH
export AWS_PROFILE=juniper-rye AWS_REGION=us-east-2

KEY=$(aws kms create-key --description "lesson 34 by hand" --query KeyMetadata.KeyId --output text)
aws kms create-alias --alias-name alias/jr-lesson34-hand --target-key-id $KEY
aws kms enable-key-rotation --key-id $KEY

printf 'deliveries before 6am' > note.txt
aws kms encrypt --key-id alias/jr-lesson34-hand --plaintext fileb://note.txt   --encryption-context app=orders --query CiphertextBlob --output text | base64 --decode > note.enc
aws kms decrypt --ciphertext-blob fileb://note.enc --encryption-context app=orders   --query Plaintext --output text | base64 --decode

A secret encrypted with that key, read back:

BASH
aws secretsmanager create-secret --name jr-lesson34/by-hand --kms-key-id alias/jr-lesson34-hand   --secret-string '{"username":"juniper-orders","password":"change-me"}'
aws secretsmanager get-secret-value --secret-id jr-lesson34/by-hand --query SecretString --output text

Clean up:

BASH
aws secretsmanager delete-secret --secret-id jr-lesson34/by-hand --force-delete-without-recovery
aws kms delete-alias --alias-name alias/jr-lesson34-hand
aws kms schedule-key-deletion --key-id $KEY --pending-window-in-days 7
rm note.txt note.enc

In real systems

  • A key per application or kind of data, not one for everything, so one key's policy and one key's emergency brake affect one thing.
  • Key policies separate the people who manage a key from the ones who use it. Administrators can change and schedule deletion; the app's role can only encrypt and decrypt.
  • Deleting a key starts with disabling it, then watching CloudTrail for DisabledException errors for weeks before anything is scheduled, and the waiting period is 30 days, not 7.
  • EventBridge rules alert on DisableKey and ScheduleKeyDeletion, because either can take data offline.
  • Secrets are never in code, environment variables or images. Apps read them at startup or through a cache, with a role allowed to read only their own.
  • Database passwords rotate automatically, using the rotation functions AWS provides, and RDS can manage its own master password in Secrets Manager.
  • Encrypted data shared with another account needs a customer managed key, with that account named in the key policy.

Spot the problem

Work out what's wrong before you read the explanation.

"The cleanup script found an unused key." An account review flags a customer managed key with no alias and a $1.00-a-month charge, and someone schedules it for deletion with a 7-day wait, since nothing seems to use it. Eight days later, restoring last quarter's database backup fails. What's wrong? The backups were encrypted with that key, and with the key deleted they can never be decrypted again: "nothing uses it daily" isn't "nothing needs it". The fix: disable a key instead of deleting it, watch CloudTrail for refusals, and only schedule deletion, with the full 30 days, when you're sure nothing encrypted under it is still needed. Then check: look up the key's Decrypt events in event history before deciding, and remember that history only goes back 90 days, while backups go back further.

Keep this

RememberWhy
KMS keys never leave KMSYou send data or ask for data keys
The key policy is checked firstThe default one lets IAM decide
Use an encryption contextIt must match, and it's written to CloudTrail
4 KB is KMS's limitBigger data uses envelope encryption
Turn on S3 bucket keysOne KMS call for many objects
Secrets go in Secrets ManagerEncrypted, versioned, logged, rotatable
Disabling stops KMS at onceBut cached data keys can last a little longer
Deleting a key deletes the dataDisable first; wait 30 days, not 7

Where you are now

Juniper & Rye has a key of its own with a policy, an alias and yearly rotation; it has encrypted a note directly, a data key by hand, and recipe files through S3; and the supplier password lives in Secrets Manager, versioned and never printed. Switching the key off showed what an emergency brake really does, including what it doesn't stop straight away, and CloudTrail accounted for every use of the key, by you and by the services acting for you. Next, Lesson 35 lets AWS watch the account for you, with GuardDuty, Security Hub and Config.

Check yourself

  1. When is paying $1.00 a month for your own key worth it?

  2. What does the default key policy's one statement do?

  3. Decrypting with a different encryption context failed. Why?

  4. Why did KMS refuse to encrypt the 5,000-byte file?

  5. With the key disabled, which failed in both runs?

  6. CloudTrail shows a Decrypt invokedBy secretsmanager.amazonaws.com. Whose permissions were used?

  7. What happens if you cancel a key's scheduled deletion?

Key terms

  • KMS (Key Management Service): AWS's service for keys that never leave it.
  • Customer managed key: a KMS key you create and control, at $1.00 a month.
  • AWS managed key: a free key a service creates in your account, like aws/s3, with a policy you can't change.
  • Key policy: the resource policy on a key, checked before IAM.
  • Alias: a friendly name pointing at a key.
  • Key rotation: new key material on a schedule, keeping old versions so old data still decrypts.
  • Encryption context: names and values bound into a ciphertext, which must match to decrypt and are logged.
  • Data key: a key KMS generates for encrypting data outside KMS, returned plain and encrypted.
  • Envelope encryption: encrypting data with a data key, and the data key with a KMS key.
  • S3 bucket key: a bucket-level key S3 gets from KMS and reuses, to make far fewer KMS calls.
  • Secret: a value in Secrets Manager, encrypted with a KMS key and versioned.
  • Staging label: a name on a secret version, like AWSCURRENT or AWSPREVIOUS.

Go deeper