Foundry24 in Denver

Choosing an Infrastructure as Code Tool and Getting Started

Robbie infrastructure-as-code · cdk · terraform · aws · devops

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.

What it looks like

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.

Three tools for AWS

Here is the same bucket in each one, with encryption, versioning and a lifecycle rule.

AWS CDK (Cloud Development Kit)

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.

Terraform

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.

CloudFormation

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.

Which one I’d use

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.

Project structure

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

Start simple

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.

A basic web app stack

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.

Staging and production from one stack

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,
});

Keeping secrets out of the code

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"
);

Deploying

Local development

# See what will change
cdk diff --all

# Deploy to your account
cdk deploy --all

CI/CD integration

# .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

Migrating existing infrastructure

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

Where state lives

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.

Review infrastructure changes like code

A bad infrastructure change can take down production, so give it the same review as application code and run it in staging first.

Foundry24 builds and runs software for small businesses

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.

Send a message

It goes to hello@foundry24.io. Replies usually come within a day.