Infrastructure built by clicking through the AWS console works until the person who clicked leaves, or the account has to be rebuilt. There’s no record of who changed what or why, and changes go live without review. Production slowly diverges from staging.
Infrastructure as Code (IaC) means defining your infrastructure in version-controlled files.
const database = new rds.DatabaseInstance(this, "Database", {
engine: rds.DatabaseInstanceEngine.postgres({ version: rds.PostgresEngineVersion.VER_15 }),
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T4G, ec2.InstanceSize.SMALL),
vpc,
allocatedStorage: 20,
backupRetention: Duration.days(7),
});
This lives in Git with its history, gets reviewed before merging, and deploys the same way every time. It can also recreate the entire environment.
Here is the same bucket in each one, with encryption, versioning and a lifecycle rule.
const bucket = new s3.Bucket(this, "DataBucket", {
encryption: s3.BucketEncryption.S3_MANAGED,
versioned: true,
lifecycleRules: [{
expiration: Duration.days(365),
transitions: [{
storageClass: s3.StorageClass.GLACIER,
transitionAfter: Duration.days(30),
}],
}],
});
CDK fits a team comfortable with TypeScript or Python, working only in AWS, especially on complex infrastructure. It’s a full programming language with strong typing that catches errors early, and its high-level constructs cut boilerplate.
resource "aws_s3_bucket" "data" {
bucket_prefix = "data-"
}
resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
bucket = aws_s3_bucket.data.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
resource "aws_s3_bucket_versioning" "data" {
bucket = aws_s3_bucket.data.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_lifecycle_configuration" "data" {
bucket = aws_s3_bucket.data.id
rule {
id = "archive"
status = "Enabled"
filter {}
transition {
days = 30
storage_class = "GLACIER"
}
expiration {
days = 365
}
}
}
Terraform is cloud-agnostic, which makes it the one for multi-cloud environments. It also makes sense for a team with existing Terraform experience, and it has a mature ecosystem and a large community.
Resources:
DataBucket:
Type: AWS::S3::Bucket
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
VersioningConfiguration:
Status: Enabled
LifecycleConfiguration:
Rules:
- Status: Enabled
Transitions:
- StorageClass: GLACIER
TransitionInDays: 30
ExpirationInDays: 365
CloudFormation is native to AWS and needs no additional tooling, which fits simple setups and teams already invested in it.
CDK for most projects. A real programming language is worth the learning curve because a stack becomes an ordinary class you can version and publish. My cdk-app-patterns package ships compute, domain and bastion stacks that way, and this site and another product of mine both depend on it.
infrastructure/
├── bin/
│ └── app.ts # Entry point
├── lib/
│ └── stacks/
│ ├── network-stack.ts # VPC, subnets
│ └── app-stack.ts # Database, Fargate service
├── cdk.json
├── package.json
└── tsconfig.json
Don’t try to codify everything at once. Start with one environment and its core infrastructure (database, compute, networking). Use it for new resources only, and don’t migrate existing manual resources immediately, because migrating is harder than starting fresh.
The network lives in its own stack because it changes rarely and other stacks depend on it.
// lib/stacks/network-stack.ts
import { Stack, StackProps } from "aws-cdk-lib";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import { Construct } from "constructs";
export class NetworkStack extends Stack {
public readonly vpc: ec2.Vpc;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
this.vpc = new ec2.Vpc(this, "Vpc", {
maxAzs: 2,
natGateways: 1,
});
}
}
The app stack takes that VPC as a prop, then creates the database and the service.
// lib/stacks/app-stack.ts
import { Stack, StackProps } from "aws-cdk-lib";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import * as ecr from "aws-cdk-lib/aws-ecr";
import * as ecs from "aws-cdk-lib/aws-ecs";
import * as ecs_patterns from "aws-cdk-lib/aws-ecs-patterns";
import * as rds from "aws-cdk-lib/aws-rds";
import { Construct } from "constructs";
export interface AppStackProps extends StackProps {
vpc: ec2.IVpc;
repositoryName: string;
imageTag: string;
instanceSize: ec2.InstanceSize;
}
export class AppStack extends Stack {
constructor(scope: Construct, id: string, props: AppStackProps) {
super(scope, id, props);
const database = new rds.DatabaseInstance(this, "Database", {
engine: rds.DatabaseInstanceEngine.postgres({
version: rds.PostgresEngineVersion.VER_15,
}),
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T4G, props.instanceSize),
vpc: props.vpc,
vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS },
databaseName: "app",
credentials: rds.Credentials.fromGeneratedSecret("postgres"),
});
const secret = database.secret!;
const cluster = new ecs.Cluster(this, "Cluster", { vpc: props.vpc });
const repository = ecr.Repository.fromRepositoryName(this, "Repository", props.repositoryName);
const service = new ecs_patterns.ApplicationLoadBalancedFargateService(this, "Service", {
cluster,
memoryLimitMiB: 512,
cpu: 256,
taskImageOptions: {
image: ecs.ContainerImage.fromEcrRepository(repository, props.imageTag),
environment: {
DB_HOST: database.dbInstanceEndpointAddress,
DB_PORT: database.dbInstanceEndpointPort,
DB_NAME: "app",
},
secrets: {
DB_USER: ecs.Secret.fromSecretsManager(secret, "username"),
DB_PASSWORD: ecs.Secret.fromSecretsManager(secret, "password"),
},
},
});
database.connections.allowDefaultPortFrom(service.service);
}
}
The generated secret is a JSON document, so the service reads the username and password fields one at a time and the app builds its connection string from them. The last line opens the database’s security group to the service. Without it, the app can’t reach Postgres.
The entry point creates one network and one app stack per environment. Both environments share the code and differ only in these values.
// bin/app.ts
import * as cdk from "aws-cdk-lib";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import { AppStack } from "../lib/stacks/app-stack";
import { NetworkStack } from "../lib/stacks/network-stack";
const app = new cdk.App();
const staging = { account: "111111111111", region: "us-east-1" };
const stagingNetwork = new NetworkStack(app, "NetworkStaging", { env: staging });
new AppStack(app, "AppStaging", {
env: staging,
vpc: stagingNetwork.vpc,
repositoryName: "my-app",
imageTag: "1.4.2",
instanceSize: ec2.InstanceSize.MICRO,
});
const production = { account: "222222222222", region: "us-east-1" };
const productionNetwork = new NetworkStack(app, "NetworkProduction", { env: production });
new AppStack(app, "AppProduction", {
env: production,
vpc: productionNetwork.vpc,
repositoryName: "my-app",
imageTag: "1.4.2",
instanceSize: ec2.InstanceSize.SMALL,
});
Read them from Secrets Manager rather than hardcoding them.
// Bad
const apiKey = "sk-1234567890";
// Good
const apiKey = secretsmanager.Secret.fromSecretNameV2(
this, "ApiKey", "/myapp/api-key"
);
# See what will change
cdk diff --all
# Deploy to your account
cdk deploy --all
# .github/workflows/infrastructure.yml
name: Infrastructure
on:
push:
branches: [main]
paths: ['infrastructure/**']
permissions:
id-token: write # role-to-assume authenticates with OIDC
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: us-east-1
- name: Install dependencies
run: cd infrastructure && npm ci
- name: CDK diff
run: cd infrastructure && npx cdk diff --all
- name: CDK deploy
run: cd infrastructure && npx cdk deploy --all --require-approval never
Existing manual infrastructure moves over in three phases. First, use cdk import to bring existing resources under IaC management.
cdk import AppStack
# Follow prompts to import existing resources
Then make sure the IaC definition matches reality.
cdk diff
# Should show no changes if import was successful
From here, all changes go through code.
# Make change in code
git commit -m "Increase database instance size"
git push
# CI/CD deploys the change
Terraform keeps a state file that you have to store and lock yourself. CDK has no state file of its own, because the state is the CloudFormation stack. That has its own failure modes, like a rollback that gets stuck or resources that drift after someone edits them in the console.
A bad infrastructure change can take down production, so give it the same review as application code and run it in staging first.
AI agents, automation, and websites, built in a few weeks and then maintained for a monthly fee. If something in your week should be software by now, book a call.