🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

AWS KMS and Secrets Manager for Data Engineers

AWS Data EngineeringKey Management & Secrets Management⭐ Premium
AWS Data Engineering ¡ Interview

The one-line mental model

KMS protects data by protecting keys, and Secrets Manager protects credentials by making rotation routine, together forming the control layer that lets a data platform prove who accessed what, when, and with which key.

You will be able to explain envelope encryption without stumbling, write a key policy that grants least privilege with a service condition, decide when Parameter Store is sufficient, and wire a rotation Lambda whose four steps leave no window of broken credentials.

Prerequisites

  • !AWS IAM: policies, roles and the evaluation logic
  • !Basic encryption vocabulary: plaintext, ciphertext and keys

What You'll Learn

  • 1Describe the CMK, data key and ciphertext relationship precisely
  • 2Write key policies with kms:ViaService conditions
  • 3Compare Secrets Manager and Parameter Store on cost and rotation
  • 4Implement the four-step credential rotation protocol safely

The key hierarchy, explained without hand-waving

AWS KMS is a managed service that keeps key material inside FIPS 140-2 validated hardware security modules and exposes a small API: encrypt, decrypt, generate data key, re-encrypt. Crucially, the service never returns the unencrypted key material of a customer managed key. What it returns is a data key: a fresh symmetric key generated on demand, returned once in plaintext alongside a copy encrypted under your key, which is why the pattern is called envelope encryption.

The reason this design exists is cost and safety in equal measure. Calling KMS for every kilobyte of a terabyte table would be slow and expensive, so your code encrypts the bulk data locally with the data key and only asks KMS to unwrap that key at read time. The data key lives in memory for the life of the operation and, if you must reuse one, it is stored alongside the ciphertext in its encrypted form. A stolen object without the wrapped key is useless, and a stolen wrapped key without KMS permission is equally useless.

Three key types appear in interviews. Symmetric keys handle the overwhelmingly common encrypt-and-decrypt case for S3, EBS and RDS. Asymmetric keys pair a public key for encryption with a private key for signing, useful when a partner must encrypt data they will never decrypt themselves. HMAC keys produce message authentication codes for integrity checks. For data engineering, memorise symmetric plus envelope encryption and you have covered ninety percent of real usage.

python
import boto3

kms = boto3.client("kms")
KEY_ID = "alias/acme-data-lake"

# Envelope encryption: one KMS call for many megabytes of data
data_key = kms.generate_data_key(KeyId=KEY_ID, KeySpec="AES_256")
plaintext_key = data_key["Plaintext"]
wrapped_key = data_key["CiphertextBlob"]

def encrypt_record(payload: bytes, key: bytes) -> bytes:
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    nonce = b"0123456789ab"          # 12-byte nonce, unique per record
    return AESGCM(key).encrypt(nonce, payload, None)

def decrypt_record(blob: bytes, wrapped: bytes) -> bytes:
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    unwrapped = kms.decrypt(CiphertextBlob=wrapped)["Plaintext"]
    nonce, body = blob[:12], blob[12:]
    return AESGCM(unwrapped).decrypt(nonce, body, None)

cipher = encrypt_record(b'{"order": 42}', plaintext_key)
print(decrypt_record(cipher, wrapped_key))

Notice that the wrapped key must travel with the ciphertext. Persist it as an object attribute or a sidecar file, never in your source tree, and keep the plaintext key out of logs entirely, because a single debug statement that prints key bytes defeats the whole design.

Key policies and IAM policies, and why both exist

A KMS key is governed by two policy documents that must both allow an action. The key policy lives on the key itself and is the root of trust: it can delegate permission to IAM policies in the same account or to another account outright. IAM policies live on the caller's role and can only grant what the key policy already permits. This double gate is why a team can have full KMS permissions in IAM and still get an access denied error, and it is the first thing to check when a Glue job fails at read time.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "EnableAccountAdministration",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::123456789012:root" },
      "Action": "kms:*",
      "Resource": "*"
    },
    {
      "Sid": "AllowGlueThroughS3Only",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::123456789012:role/GlueJobRole" },
      "Action": ["kms:Decrypt", "kms:GenerateDataKey"],
      "Resource": "*",
      "Condition": {
        "StringEquals": { "kms:ViaService": "s3.us-east-1.amazonaws.com" },
        "Bool": { "kms:EncryptedDataAccess": "true" }
      }
    }
  ]
}

The kms:ViaService condition is the line interviewers look for. It restricts a key so that the named role can only use it through S3, which means a stolen set of credentials cannot take the same permission and decrypt an unrelated ciphertext through the KMS API directly. Enable automatic annual rotation on every customer managed key: rotation swaps the backing material while keeping the key id and aliases stable, so no application change is required and no ciphertext becomes unreadable.

Secrets Manager, Parameter Store, and when each wins

Both services store configuration secrets encrypted with KMS, and the choice comes down to rotation, size and cost.

PropertySecrets ManagerParameter Store
Automatic rotationBuilt in, via a rotation LambdaNot provided
PricePer secret per month plus API callsFree tier, then small per-parameter charge
Maximum value size64 KB8 KB standard, 8 KB advanced with more
VersioningAutomatic with staging labelsManual versions
Cross-account sharingNativeVia resource policies, more setup
Best suited toDatabase credentials and API keysFeature flags and non-secret configuration

The economics are simple enough to reason about in an interview: a handful of rotating database credentials is a few dollars a month in Secrets Manager and worth every cent, while hundreds of static configuration values belong in Parameter Store where they cost nothing. The functional difference matters more. Secrets Manager tracks AWSCURRENT, AWSPENDING and AWSPREVIOUS stages on each version, which is what makes zero-downtime rotation possible at all; Parameter Store has no equivalent concept, so a credential swap there is an all-at-once edit that every consumer must tolerate.

python
import json
import boto3

sm = boto3.client("secretsmanager")

secret_value = {
    "host": "orders.cluster-123456.us-east-1.rds.amazonaws.com",
    "username": "app_writer",
    "password": "initial-sup3r-secret",
    "engine": "postgres",
    "port": 5432,
    "dbname": "orders",
}

created = sm.create_secret(
    Name="prod/orders/db-credentials",
    Description="Orders database writer credentials",
    SecretString=json.dumps(secret_value),
    Tags=[{"Key": "Environment", "Value": "production"}],
)

sm.rotate_secret(
    SecretId="prod/orders/db-credentials",
    RotationLambdaARN="arn:aws:lambda:us-east-1:123456789012:function:orders-rotation",
    RotationRules={"AutomaticallyAfterDays": 30},
)

current = json.loads(
    sm.get_secret_value(SecretId="prod/orders/db-credentials")["SecretString"]
)
print(f"connected as {current['username']} on port {current['port']}")

The four-step rotation protocol

Rotation is the part candidates most often describe vaguely, so it is worth knowing the sequence precisely. Secrets Manager invokes your Lambda with a step name, and the Lambda must be written to be re-entrant, because the service may retry any step.

createSecret generates a new password and stores it under the AWSPENDING staging label, leaving AWSCURRENT untouched. setSecret pushes that password into the database, using a second user or an alternate mechanism where the engine cannot change a password while connections are open. testSecret authenticates with the pending credentials to prove they work, which is the step that prevents a rotation from bricking your application at 3 a.m. finishSecret promotes the pending version to AWSCURRENT and demotes the old one to AWSPREVIOUS.

The order is what makes this safe: consumers keep reading AWSCURRENT throughout, the new credential is proven before promotion, and a failure at any step leaves the previous credential live. Applications should fetch credentials on a short cache interval rather than once at start-up, otherwise a rotated secret will not be picked up until the next deploy, which silently converts a working rotation into an outage the first time it runs.

Cost, limits and blast radius

Every security control has an operational footprint, and being concrete about it is what separates a prepared answer from a recited one. KMS charges roughly a dollar per customer managed key per month plus a small amount per request; a bucket key removes almost all per-object KMS calls for S3. Secrets Manager charges per secret per month, which is why mixing hundreds of non-rotating values into it is wasteful. Envelope encryption keeps both bills flat as data volume grows, because the number of KMS calls scales with keys and caches, not with bytes.

Blast radius is the other half. One key shared across every service means a single over-broad grant exposes everything, so separate keys by data domain: one for the raw lake, one for curated tables, one for database storage encryption. Deleting a key is irreversible after the waiting period, and every ciphertext written under it becomes permanently unreadable, so disable a key first and observe the impact rather than scheduling a deletion. Treat key administration and key usage as separate roles, because the person who may rotate a key should not automatically be the person who may decrypt customer data.

Audit, and proving it afterwards

Enabling CloudTrail on KMS is what converts encryption from a technical control into an auditable one: every encrypt, decrypt and generate data key call is logged with the caller identity, the key id, the source address and the timestamp. Ship those events to a separate account, set an alarm on decrypt volumes that deviate from baseline, and query them with Athena when an auditor asks who read a particular table last quarter. Secrets Manager inherits the same trail, and you should additionally alarm on secret deletions and on rotation failures, since those two events predict an outage. Finally, run an access review on both key policies and secret resource policies quarterly, removing roles whose jobs were eliminated, because credential sprawl in KMS is invisible in dashboards and obvious only to whoever reads the policy files.

Common Mistakes

Hardcoding a key id or secret string in application configuration

Fix: Reference key aliases and fetch secrets at runtime from Secrets Manager

Granting a role kms:Decrypt with no service condition

Fix: Add kms:ViaService so the permission only works through the intended AWS service

Fetching credentials once at process start

Fix: Cache with a short TTL and re-read so rotation is picked up without a redeploy

Sharing one KMS key across all services and environments

Fix: Split keys by data domain and environment to limit the blast radius of a grant error

Best Practices

  • Enable automatic rotation on every customer managed key and on every stored credential
  • Separate key administration roles from key usage roles
  • Use envelope encryption so KMS call volume scales with keys, not data size
  • Enable CloudTrail on KMS and alarm on anomalous decrypt volume and secret deletion
  • Keep the root key policy statement intact so account administration is never lost

Interview Questions

Q1: Explain envelope encryption in one paragraph.

KMS generates a plaintext data key plus a copy wrapped by your CMK; the data encrypts locally with the plaintext key, only the wrapped copy is stored, and decryption calls KMS once to unwrap it.

Q2: Why does an IAM-allowed role still get access denied on a key?

Because the key policy must also permit the action; both documents are evaluated and denial in either one wins.

Q3: Secrets Manager or Parameter Store for a rotating database password?

Secrets Manager, because it provides managed rotation, automatic version staging and a 64 KB payload, which are exactly what credential rotation requires.

Q4: What happens if you delete a KMS key?

After the waiting period the key becomes unrecoverable and every ciphertext under it is permanently unreadable, so disable first and treat deletion as a last resort.

Key Takeaways

  • Key policies are the root of trust; IAM policies only inherit what the key policy delegates
  • Envelope encryption keeps KMS calls cheap by encrypting bulk data with a local data key
  • kms:ViaService narrows a stolen credential to a single intended service
  • Secrets Manager exists for rotation: four steps, staging labels, no downtime
  • Separate keys by domain, enable CloudTrail, and never share a key across unrelated workloads
🔒

Premium Content

AWS KMS and Secrets Manager for Data Engineers

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement