CloudFormation & CDK

Infrastructure as code on AWS — CloudFormation templates, stacks, change sets, drift detection, nested stacks and StackSets, rollback behaviour, the AWS CDK with constructs and synthesis, a complete CDK example, CDK vs Terraform vs SAM, and safe deployment pipelines.

Intermediate 4 min readLesson 15 of 19 Interview Q&A

Clicking resources together in the console doesn't scale: it isn't reviewable, repeatable or recoverable. Infrastructure as code (IaC) describes infrastructure in files that live in Git, go through code review and deploy through pipelines (Infrastructure as code). AWS's native engine is CloudFormation; the Cloud Development Kit (CDK) lets you write it in a real programming language.

CloudFormation

You write a template (YAML or JSON) declaring resources; CloudFormation creates a stack — the set of real resources — working out dependencies and creating, updating or deleting them in the right order.

YAML
AWSTemplateFormatVersion: "2010-09-09"
Parameters:
  Env:
    Type: String
    AllowedValues: [dev, prod]
Resources:
  OrdersTable:
    Type: AWS::DynamoDB::Table
    DeletionPolicy: Retain                 # keep data if the stack is deleted
    UpdateReplacePolicy: Retain
    Properties:
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - { AttributeName: PK, AttributeType: S }
        - { AttributeName: SK, AttributeType: S }
      KeySchema:
        - { AttributeName: PK, KeyType: HASH }
        - { AttributeName: SK, KeyType: RANGE }
      PointInTimeRecoverySpecification: { PointInTimeRecoveryEnabled: true }
  OrdersQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub "orders-${Env}"
      VisibilityTimeout: 180
Outputs:
  TableName:
    Value: !Ref OrdersTable
    Export: { Name: !Sub "${Env}-orders-table" }

Key ideas:

  • Intrinsic functions: !Ref (a resource's ID or a parameter), !GetAtt (an attribute like an ARN), !Sub (string interpolation), !If with conditions, !ImportValue from another stack's exports.
  • Change sets preview exactly what an update will add, modify or replace — always review them in production, because some property changes (a DynamoDB key schema, an RDS identifier) replace the resource, which can mean data loss.
  • Rollback: if any resource fails during an update, CloudFormation rolls the whole stack back to the last good state. You can attach CloudWatch alarms as rollback triggers.
  • DeletionPolicy: Retain / Snapshot protects stateful resources; stack termination protection prevents accidental deletion.
  • Drift detection finds resources changed outside CloudFormation (someone clicked in the console).
  • Nested stacks compose templates; StackSets deploy one template across many accounts and regions (guardrails, baseline roles).
  • Custom resources (backed by Lambda) and the CloudFormation registry extend it to anything.

The downsides of raw templates: verbose, little abstraction, logic squeezed into YAML. That's what CDK fixes.

The AWS CDK

CDK lets you define infrastructure in TypeScript, Python, Java, C# or Go. Your program builds a tree of constructs; cdk synth turns it into CloudFormation templates, and cdk deploy deploys them.

L3 — patternsApplicationLoadBalancedFargateService: VPC + cluster + ALB + service in one constructL2 — curated resourcess3.Bucket, lambda.Function — sensible defaults and helper methods like grantRead()L1 — Cfn resourcesCfnBucket — one-to-one with CloudFormation, generated from the specCloudFormationthe deployment engine underneath

A complete example

An API that writes orders to DynamoDB and publishes them to a queue:

import { Stack, StackProps, Duration, RemovalPolicy } from "aws-cdk-lib";
import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
import * as sqs from "aws-cdk-lib/aws-sqs";
import * as lambda from "aws-cdk-lib/aws-lambda";
import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs";
import { HttpApi, HttpMethod } from "aws-cdk-lib/aws-apigatewayv2";
import { HttpLambdaIntegration } from "aws-cdk-lib/aws-apigatewayv2-integrations";
import { Construct } from "constructs";

export class OrdersStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const table = new dynamodb.TableV2(this, "Orders", {
      partitionKey: { name: "PK", type: dynamodb.AttributeType.STRING },
      sortKey: { name: "SK", type: dynamodb.AttributeType.STRING },
      pointInTimeRecoverySpecification: { pointInTimeRecoveryEnabled: true },
      removalPolicy: RemovalPolicy.RETAIN,
    });

    const dlq = new sqs.Queue(this, "OrdersDlq", { retentionPeriod: Duration.days(14) });
    const queue = new sqs.Queue(this, "OrdersQueue", {
      visibilityTimeout: Duration.seconds(180),
      deadLetterQueue: { queue: dlq, maxReceiveCount: 5 },
    });

    const createOrder = new NodejsFunction(this, "CreateOrder", {
      entry: "src/create-order.ts",
      runtime: lambda.Runtime.NODEJS_22_X,
      architecture: lambda.Architecture.ARM_64,
      memorySize: 512,
      timeout: Duration.seconds(10),
      environment: { TABLE: table.tableName, QUEUE_URL: queue.queueUrl },
    });

    table.grantWriteData(createOrder);      // least-privilege IAM generated for you
    queue.grantSendMessages(createOrder);

    const api = new HttpApi(this, "Api");
    api.addRoutes({ path: "/orders", methods: [HttpMethod.POST],
      integration: new HttpLambdaIntegration("CreateOrderInt", createOrder) });
  }
}

About 40 lines generate several hundred lines of CloudFormation — including IAM policies scoped to exactly this table and queue.

Shell
npx cdk bootstrap aws://123456789012/ap-south-1   # once per account/region: assets bucket + deploy roles
npx cdk synth                                       # generate templates (review in PRs)
npx cdk diff                                        # what will change?
npx cdk deploy OrdersStack

Why teams like CDK:

  • Abstraction and reuse: publish your organisation's SecureBucket or StandardService construct as a library.
  • grant* methods produce least-privilege IAM automatically.
  • Loops, conditionals, types and IDE autocomplete instead of YAML gymnastics.
  • Unit tests with assertions on the synthesised template; cdk-nag checks for security best practices.
  • CDK Pipelines for self-updating, multi-account deployment pipelines.

Pitfalls: changing a construct's logical ID (renaming it or moving it in the tree) makes CloudFormation replace the resource — protect stateful resources with RemovalPolicy.RETAIN and review cdk diff. Keep stateful and stateless resources in separate stacks.

SAM, Terraform and others

ToolApproachChoose when
CloudFormationDeclarative YAML/JSON, AWS-nativeSimple stacks, StackSets, no build step wanted
CDKCode → CloudFormationAWS-focused teams wanting abstraction and type safety
SAMCloudFormation shorthand for serverless + sam local testingLambda-centric apps, quick serverless projects
Terraform / OpenTofuHCL, own state file, providers for every cloud and SaaSMulti-cloud or multi-vendor infrastructure, existing Terraform skills
PulumiGeneral-purpose languages, own engineCode-first teams outside the CDK ecosystem

All are good; what matters is that production infrastructure is only changed through code and pipelines.

Safe infrastructure delivery

  1. Every change is a pull request; CI runs synth/validate, linting (cfn-lint, cdk-nag, Checkov) and shows the diff or change set.
  2. Deploy automatically to dev, then staging; promote the same artefact to production (CI/CD).
  3. Pipelines assume deploy roles via OIDC — no long-lived keys (IAM).
  4. Production changes review the change set, especially replacements.
  5. Detect drift regularly and block console changes in production with SCPs or permission sets.
Interview questions
QWhat's the difference between CloudFormation and CDK?easy

CloudFormation is AWS's deployment engine: it takes declarative YAML or JSON templates and creates, updates and rolls back stacks of resources. CDK is a framework for writing infrastructure in programming languages like TypeScript or Python; it synthesises CloudFormation templates and deploys them through CloudFormation. CDK adds abstraction (constructs), reuse, type checking and helpers like grant methods, while CloudFormation still provides the state management and rollback.

QHow do you avoid losing data when updating infrastructure as code?medium

Review change sets or cdk diff for resources marked as replacement; set DeletionPolicy and UpdateReplacePolicy to Retain or Snapshot (RemovalPolicy.RETAIN in CDK) on databases, buckets and tables; enable termination protection on stateful stacks; keep stateful resources in separate stacks that change rarely; avoid renaming logical IDs; and keep backups such as point-in-time recovery enabled independently of the IaC.

QWhat is drift and how do you handle it?easy

Drift is when the actual configuration of resources differs from what the template declares, usually because someone changed something manually in the console or CLI. CloudFormation drift detection reports it. Handle it by either updating the code to match a deliberate change or redeploying to revert it, and prevent it by restricting manual write access in production so all changes flow through pipelines.

Key takeaways
  • CloudFormation deploys templates as stacks, handling dependencies, updates and automatic rollback.
  • Review change sets for replacements; protect stateful resources with Retain/Snapshot policies and termination protection.
  • CDK synthesises CloudFormation from TypeScript, Python, Java and more, with L1/L2/L3 constructs and grant methods for least-privilege IAM.
  • Bootstrap, synth, diff and deploy; test templates and lint with cdk-nag.
  • SAM suits serverless apps; Terraform suits multi-cloud — the principle is the same: change production only through code and pipelines.