Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท SDKs and Local Development

Infrastructure as Code and IAM

Define DynamoDB tables as code with CloudFormation, CDK or Terraform, and secure them with least-privilege IAM policies, leading-key conditions and encryption.

Clicking a table into existence in the console is fine for learning, and a mistake for anything you will run twice. A table has keys, indexes, capacity settings, TTL, streams, backups, alarms and permissions, and all of them must match between development, testing and production. Infrastructure as Code (IaC) stores that definition in a file in your repository, so it is reviewed, versioned and repeatable. IAM then decides which code is allowed to touch it.

Everything in this lesson is configuration to read and adapt, not code that runs on this page. The runnable stand-in at the end checks an IAM-style policy against requests.

A table in CloudFormation

CloudFormation is AWS's native template language:

YAML
Resources:
  ShopTable:
    Type: AWS::DynamoDB::Table
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      TableName: Shop
      BillingMode: PAY_PER_REQUEST
      DeletionProtectionEnabled: true
      AttributeDefinitions:
        - { AttributeName: PK, AttributeType: S }
        - { AttributeName: SK, AttributeType: S }
        - { AttributeName: GSI1PK, AttributeType: S }
        - { AttributeName: GSI1SK, AttributeType: S }
      KeySchema:
        - { AttributeName: PK, KeyType: HASH }
        - { AttributeName: SK, KeyType: RANGE }
      GlobalSecondaryIndexes:
        - IndexName: GSI1
          KeySchema:
            - { AttributeName: GSI1PK, KeyType: HASH }
            - { AttributeName: GSI1SK, KeyType: RANGE }
          Projection: { ProjectionType: ALL }
      TimeToLiveSpecification: { AttributeName: expiresAt, Enabled: true }
      PointInTimeRecoverySpecification: { PointInTimeRecoveryEnabled: true }
      StreamSpecification: { StreamViewType: NEW_AND_OLD_IMAGES }
      SSESpecification: { SSEEnabled: true }

Only attributes used as keys (table or index) are declared in AttributeDefinitions; all other attributes are schemaless. DeletionPolicy: Retain and deletion protection stop a stack deletion from erasing production data (see backups). Adding or removing a global secondary index in CloudFormation is limited to one index change per update, and changing the key schema of a table forces a replacement, so changing keys is a migration, not an edit.

CDK and Terraform

The same table in the AWS CDK (TypeScript) and in Terraform:

TypeScript
import { Table, AttributeType, BillingMode } from "aws-cdk-lib/aws-dynamodb";

const table = new Table(this, "Shop", {
  partitionKey: { name: "PK", type: AttributeType.STRING },
  sortKey: { name: "SK", type: AttributeType.STRING },
  billingMode: BillingMode.PAY_PER_REQUEST,
  pointInTimeRecovery: true,
  deletionProtection: true,
  timeToLiveAttribute: "expiresAt",
});
table.addGlobalSecondaryIndex({
  indexName: "GSI1",
  partitionKey: { name: "GSI1PK", type: AttributeType.STRING },
  sortKey: { name: "GSI1SK", type: AttributeType.STRING },
});
table.grantReadWriteData(orderFunction);   // generates a least-privilege policy
HCL
resource "aws_dynamodb_table" "shop" {
  name         = "Shop"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "PK"
  range_key    = "SK"

  attribute { name = "PK"  type = "S" }
  attribute { name = "SK"  type = "S" }

  ttl { attribute_name = "expiresAt" enabled = true }
  point_in_time_recovery { enabled = true }
  deletion_protection_enabled = true
}

CDK's grant* methods create IAM policies for a Lambda or role automatically. Use the same definition in tests (local development) so indexes never drift.

Tables as code

CloudFormation Native AWS templates
CDK TypeScript, Python, Java
Terraform Multi-cloud HCL
Retain Protect production data

One definition for every environment.

1 / 2

IAM: least privilege

IAM policies allow actions on resources. Give each service only what it needs, on specific table and index ARNs:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:Query"],
    "Resource": [
      "arn:aws:dynamodb:eu-west-1:123456789012:table/Shop",
      "arn:aws:dynamodb:eu-west-1:123456789012:table/Shop/index/*"
    ]
  }]
}

Avoid dynamodb:* on *. A read-only service gets GetItem, BatchGetItem, Query, Scan only if needed (a Scan permission is rarely required). Index access needs the /index/* resource.

Fine-grained access with condition keys

IAM condition keys restrict which items and attributes a caller may touch:

  • dynamodb:LeadingKeys: the partition key values allowed. With Cognito or web identity, ${aws:userid} or ${cognito-identity.amazonaws.com:sub} limits users to their own partition.
  • dynamodb:Attributes plus dynamodb:Select: restrict readable or writable attributes.
  • dynamodb:ReturnValues and dynamodb:EnclosingOperation for transactions.
JSON
{
  "Effect": "Allow",
  "Action": ["dynamodb:GetItem", "dynamodb:Query", "dynamodb:PutItem"],
  "Resource": "arn:aws:dynamodb:eu-west-1:123456789012:table/Shop",
  "Condition": {
    "ForAllValues:StringLike": { "dynamodb:LeadingKeys": ["USER#${cognito-identity.amazonaws.com:sub}"] }
  }
}

This is why a design with the owner ID in the partition key pairs well with IAM: the policy can prove a user only reads their own item collection.

Try it: a tiny policy evaluator

The stand-in below mimics how an Allow statement with a LeadingKeys condition decides requests. It is a simplified teaching model of IAM, not the real evaluation engine.

Python Leading-key condition check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Anything not explicitly allowed is denied, and an explicit Deny always wins over an Allow.

Security checklist

  1. Roles, not keys. Lambda, ECS and EC2 use execution roles. People use IAM Identity Center. Never commit access keys.
  2. Encryption. All tables are encrypted at rest. Choose the AWS owned key (default), an AWS managed KMS key, or a customer managed KMS key if you need key policies and audit. Data in transit uses HTTPS.
  3. Network. Use a VPC gateway endpoint for DynamoDB so traffic from private subnets does not cross the internet, and restrict it with an endpoint policy.
  4. Audit. CloudTrail records control-plane events and can log data events for tables. Alarm on throttles and errors in CloudWatch.
  5. Guard rails. Deletion protection, Retain policies, separate accounts for production and tags for cost allocation.
  6. Resource-based policies can share a table or stream across accounts.

Never put a user's raw key inside a front-end app. Browser and mobile clients should use Cognito or a backend API with narrowly scoped credentials; the leading-key condition is a second line of defense, not the first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which attributes must be declared in AttributeDefinitions?

    DynamoDB is schemaless except for key attributes, which need a declared type for the table and index definitions.
  2. 2. What does the dynamodb:LeadingKeys condition restrict?

    It limits access to items whose partition key matches given values, for example only the caller's own USER# partition.
  3. 3. What is a safe way to protect a production table in CloudFormation?

    Retain keeps the table if the stack is deleted, and deletion protection blocks DeleteTable calls.
  4. 4. How does a Lambda function normally get permission to use DynamoDB?

    Services use IAM roles with temporary credentials; keys in code are a security risk.

Summary

  • Define tables, indexes, TTL, PITR, streams and protection in CloudFormation, CDK or Terraform.
  • Changing a table's key schema means replacement or migration, so design keys carefully.
  • Grant IAM actions only on the table and index ARNs a service needs.
  • Use dynamodb:LeadingKeys to confine users to their own item collection.
  • Prefer roles, VPC endpoints, KMS encryption, CloudTrail and deletion protection.

Next: Project: Order Management System