Lesson 258 of 296
Infrastructure as code: CDK and Terraform
What you will learn
- What infrastructure as code (IaC) is and why it matters
- Declarative vs imperative tools
- AWS CDK in TypeScript, with a real example
- Terraform: providers, resources, plan and apply, state
- CDK vs Terraform vs others
- IaC best practices
On this page
What is IaC?
Infrastructure as code means defining your servers, networks, databases, queues and permissions in code files instead of clicking in a web console.
| Clicking in the console ("ClickOps") | Infrastructure as code |
|---|---|
| Nobody remembers exactly what was changed | Every change is in Git history and reviewed in pull requests |
| Recreating staging like production is guesswork | Identical environments from the same code |
| Disaster recovery means rebuilding by hand | Rebuild everything with one command |
| Drift and undocumented settings | The code is the documentation |
Declarative vs imperative
Most IaC tools are declarative: you describe the desired end state ("a queue named X with a 4-day retention"), and the tool works out what to create, change or delete. Running it twice changes nothing the second time (it is idempotent).
AWS CDK
The AWS Cloud Development Kit (CDK) lets you define infrastructure in TypeScript (or Python, Java, C#, Go) using constructs: classes representing resources or whole patterns. CDK synthesises (generates) CloudFormation templates, and CloudFormation, AWS's own deployment engine, creates the resources.
import { App, Duration, RemovalPolicy, Stack, type StackProps } from "aws-cdk-lib";
import { Bucket, BlockPublicAccess, BucketEncryption } from "aws-cdk-lib/aws-s3";
import { Queue } from "aws-cdk-lib/aws-sqs";
import { Runtime, Code, Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
import { SqsEventSource } from "aws-cdk-lib/aws-lambda-event-sources";
import type { Construct } from "constructs";
export class UploadsStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const bucket = new Bucket(this, "Uploads", {
blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
encryption: BucketEncryption.S3_MANAGED,
enforceSSL: true,
versioned: true,
removalPolicy: RemovalPolicy.RETAIN
});
const deadLetters = new Queue(this, "ProcessingDLQ", { retentionPeriod: Duration.days(14) });
const queue = new Queue(this, "Processing", {
visibilityTimeout: Duration.seconds(180),
deadLetterQueue: { queue: deadLetters, maxReceiveCount: 5 }
});
const worker = new LambdaFunction(this, "Worker", {
runtime: Runtime.NODEJS_24_X,
handler: "index.handler",
code: Code.fromInline("exports.handler = async () => ({ batchItemFailures: [] });"),
timeout: Duration.seconds(30),
memorySize: 512
});
worker.addEventSource(new SqsEventSource(queue, { batchSize: 10, reportBatchItemFailures: true }));
bucket.grantRead(worker);
}
}
const app = new App();
new UploadsStack(app, "UploadsStack", { env: { region: "eu-west-2" } });Checked by synthesising this stack with aws-cdk-lib 2.278 and asserting on the generated template: the Lambda uses nodejs24.x, the queue has a 180-second visibility timeout and a dead-letter queue with maxReceiveCount 5, the event source mapping reports batch item failures, the bucket blocks all public access, is versioned and is retained on deletion, and the generated IAM policy contains only S3 read actions and the SQS actions the event source needs.
What makes CDK pleasant:
- Sensible defaults and high-level constructs:
bucket.grantRead(worker)writes a least-privilege IAM policy for you. - Real programming: loops, functions, types, IDE autocompletion, unit tests with assertions on the generated template.
visibilityTimeoutof 180 seconds is six times the function's 30-second timeout, matching AWS's guidance for SQS-triggered Lambdas (Lesson 255).RemovalPolicy.RETAINkeeps the bucket (and its data) if the stack is deleted.- In a real project the worker code comes from
NodejsFunction, which bundles a TypeScript file with esbuild; inline code keeps this example self-contained.
Commands: cdk bootstrap (once per account and region), cdk synth (generate the template), cdk diff (show what would change), cdk deploy, cdk destroy.
Terraform
Terraform (by HashiCorp, now part of IBM) is the most widely used multi-cloud IaC tool. You write HCL (HashiCorp Configuration Language):
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
backend "s3" {
bucket = "jobprep-terraform-state"
key = "prod/terraform.tfstate"
region = "eu-west-2"
use_lockfile = true
}
}
provider "aws" {
region = "eu-west-2"
}
resource "aws_sqs_queue" "dlq" {
name = "processing-dlq"
message_retention_seconds = 1209600
}
resource "aws_sqs_queue" "processing" {
name = "processing"
visibility_timeout_seconds = 180
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.dlq.arn
maxReceiveCount = 5
})
}
output "queue_url" {
value = aws_sqs_queue.processing.url
}| Concept | Meaning |
|---|---|
| Provider | A plugin for a platform: AWS, Azure, Google Cloud, Cloudflare, GitHub, Datadog... |
| Resource | Something to create (aws_sqs_queue) |
| Reference | aws_sqs_queue.dlq.arn uses another resource's attribute; Terraform orders creation automatically |
| Variables / outputs | Inputs and results |
| Module | A reusable group of resources |
| State | A file recording what Terraform created and their real IDs; stored remotely (an S3 backend) with locking so two people cannot apply at once. It can contain secrets, so protect it |
This configuration was checked with Terraform 1.17 (terraform init, validate and fmt -check all passed, with the AWS provider 6.x). use_lockfile = true uses S3's own locking for the state file (available since Terraform 1.10); older setups used a DynamoDB table for locking.
Workflow: terraform init (download providers), terraform plan (preview changes: always review it), terraform apply, terraform destroy. In teams, plans run in CI on pull requests and applies happen after approval.
OpenTofu is an open-source fork of Terraform under the Linux Foundation, created after HashiCorp changed Terraform's licence in 2023; it is largely compatible.
Choosing
| Tool | Strengths | Consider when |
|---|---|---|
| AWS CDK | TypeScript, high-level constructs, automatic IAM grants | AWS-only, TypeScript teams |
| Terraform / OpenTofu | Multi-cloud and SaaS providers, huge ecosystem, readable plans | Several clouds or services, platform teams, most job adverts |
| CloudFormation / SAM | Native AWS YAML; SAM simplifies serverless apps | Simple AWS stacks |
| Pulumi | General-purpose languages, multi-cloud | Like CDK but multi-cloud |
| SST, Serverless Framework | Opinionated serverless app frameworks | Serverless-first apps |
Best practices
- Everything in code, reviewed in pull requests; no manual console changes in production (they cause drift; detect it with
cdk diff,terraform plan, CloudFormation drift detection). - Separate environments (accounts, stacks or workspaces) from the same code with different parameters.
- Remote, locked, encrypted state for Terraform.
- No secrets in code: reference Secrets Manager or SSM.
- Protect important data: deletion protection, retain policies, backups.
- Small, composable stacks or modules; pin provider and library versions.
- Run
planordiffin CI and read it before applying: a resource replacement of a database deletes it.
How to say it in an interview
"Infrastructure as code keeps all infrastructure in version-controlled, reviewed code, so environments are reproducible, changes are auditable and disaster recovery is a deploy. Tools are declarative: I describe the desired state and the tool calculates the changes. With AWS CDK I write TypeScript constructs that synthesise CloudFormation, with helpers like grantRead generating least-privilege IAM. With Terraform I declare providers and resources in HCL, keep state remotely in S3 with locking, and always review terraform plan before apply, especially for replacements. I avoid console changes that cause drift, keep secrets out of code, pin versions and protect stateful resources from deletion."
Key words
| Word | Meaning |
|---|---|
| Infrastructure as code | Defining infrastructure in version-controlled code |
| Declarative | Describing the end state rather than steps |
| Drift | Real infrastructure differing from the code |
| AWS CDK / construct | IaC in programming languages / a reusable building block |
| CloudFormation | AWS's deployment engine for templates |
| Synthesise | Generate the CloudFormation template from CDK code |
| Terraform / HCL | Multi-cloud IaC tool / its configuration language |
| Provider / resource / module | Platform plugin / managed object / reusable group |
| State file | Terraform's record of what it manages |
| terraform plan | A preview of changes before applying |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.