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.
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.
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),!Ifwith conditions,!ImportValuefrom 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/Snapshotprotects 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.
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) });
}
}from aws_cdk import Stack, Duration, RemovalPolicy
from aws_cdk import aws_dynamodb as dynamodb, aws_sqs as sqs, aws_lambda as _lambda
from aws_cdk.aws_apigatewayv2 import HttpApi, HttpMethod
from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration
from constructs import Construct
class OrdersStack(Stack):
def __init__(self, scope: Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
table = dynamodb.TableV2(self, "Orders",
partition_key=dynamodb.Attribute(name="PK", type=dynamodb.AttributeType.STRING),
sort_key=dynamodb.Attribute(name="SK", type=dynamodb.AttributeType.STRING),
removal_policy=RemovalPolicy.RETAIN)
dlq = sqs.Queue(self, "OrdersDlq", retention_period=Duration.days(14))
queue = sqs.Queue(self, "OrdersQueue", visibility_timeout=Duration.seconds(180),
dead_letter_queue=sqs.DeadLetterQueue(queue=dlq, max_receive_count=5))
fn = _lambda.Function(self, "CreateOrder",
runtime=_lambda.Runtime.PYTHON_3_13, architecture=_lambda.Architecture.ARM_64,
handler="handler.lambda_handler", code=_lambda.Code.from_asset("src"),
memory_size=512, timeout=Duration.seconds(10),
environment={"TABLE": table.table_name, "QUEUE_URL": queue.queue_url})
table.grant_write_data(fn)
queue.grant_send_messages(fn)
api = HttpApi(self, "Api")
api.add_routes(path="/orders", methods=[HttpMethod.POST],
integration=HttpLambdaIntegration("CreateOrderInt", fn))About 40 lines generate several hundred lines of CloudFormation — including IAM policies scoped to exactly this table and queue.
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 OrdersStackWhy teams like CDK:
- Abstraction and reuse: publish your organisation's
SecureBucketorStandardServiceconstruct 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
| Tool | Approach | Choose when |
|---|---|---|
| CloudFormation | Declarative YAML/JSON, AWS-native | Simple stacks, StackSets, no build step wanted |
| CDK | Code → CloudFormation | AWS-focused teams wanting abstraction and type safety |
| SAM | CloudFormation shorthand for serverless + sam local testing | Lambda-centric apps, quick serverless projects |
| Terraform / OpenTofu | HCL, own state file, providers for every cloud and SaaS | Multi-cloud or multi-vendor infrastructure, existing Terraform skills |
| Pulumi | General-purpose languages, own engine | Code-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
- Every change is a pull request; CI runs
synth/validate, linting (cfn-lint, cdk-nag, Checkov) and shows the diff or change set. - Deploy automatically to dev, then staging; promote the same artefact to production (CI/CD).
- Pipelines assume deploy roles via OIDC — no long-lived keys (IAM).
- Production changes review the change set, especially replacements.
- Detect drift regularly and block console changes in production with SCPs or permission sets.
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.
- 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.