Pulumi: Infrastructure as Real Code
Write your infrastructure in TypeScript, Python, or Go โ not a custom DSL.
What you'll learn in this chapter
- Why Pulumi exists and what problem it solves that Terraform doesn't
- The critical difference between a DSL and a general-purpose programming language for infrastructure
- Pulumi's core concepts: stacks, projects, resources, outputs, and config
- A complete AWS infrastructure deployment written in TypeScript
- The same infrastructure written in Python
- How to write unit tests for your infrastructure code
- The Pulumi CLI workflow and daily commands
- When to choose Pulumi over Terraform, and when to stick with Terraform
The Programming Language Superpower
In the previous chapter we built infrastructure with Terraform's HCL โ a domain-specific language designed specifically for describing infrastructure. HCL is clean and readable for simple cases. But spend a few months with it on a complex project and the cracks begin to show.
Imagine trying to write a recipe book, but the format requires you to list every ingredient and every step in a rigid, bureaucratic template. You can't write a helper function. You can't say "if this ingredient is unavailable, substitute that one." You can't write a loop that says "repeat this step for each of the ten wedding cakes." You have to write each cake out individually, ten times. You can't write unit tests to check that your recipe is correct. And when something goes wrong, the error messages read like they were written by a committee in 1987.
That's the experience many engineers have with Terraform HCL at scale.
Pulumi takes a completely different approach: write infrastructure in the programming language you already know. TypeScript. Python. Go. Java. C#. Real loops, real conditionals, real functions, real classes. Real IDE autocomplete and type checking. Real unit tests. If you know how to write TypeScript, you can write Pulumi infrastructure code on day one, without learning a new language.
Terraform HCL is like writing recipes in a very rigid cookbook format โ every recipe must follow the same template, there are no shortcuts, no abbreviations, no "see page 42 for the base sauce." It works, and for simple recipes it's fine.
Pulumi is like writing those recipes in Python. You can write a make_sauce() function
that ten recipes call. You can write a loop that generates 10 similar recipes. You can write a
test that verifies the recipe is healthy before you cook it. You can import libraries from PyPI
to help you. All the power of a real programming language, applied to infrastructure.
Pulumi vs Terraform โ Choosing Your Weapon
This isn't a battle โ both tools are excellent. Understanding their strengths helps you choose the right one for your project:
- Terraform: Custom HCL syntax, declarative, the most widely used IaC tool in the world. Massive community, thousands of Registry modules, excellent documentation, battle-tested at enormous scale. Best choice for most teams starting with IaC, teams that prefer simplicity, and when strong community support is valued.
- Pulumi: Real programming languages (TypeScript, Python, Go, Java, C#), imperative with declarative intent, same underlying providers as Terraform (uses the Terraform provider bridge), excellent testability, better for complex conditional logic and dynamic resource generation. Best choice for teams frustrated by HCL's limitations, teams that want to test infrastructure code, and when the infrastructure is genuinely complex.
- OpenTofu: 100% Terraform-compatible open-source fork, fully MPL-licensed. Use it if you're concerned about HashiCorp's BSL license, or if you're building tooling on top of Terraform's internals.
Key insight: Pulumi uses Terraform's provider ecosystem under the hood. Almost every AWS, GCP, and Azure resource available in Terraform is also available in Pulumi. You're not giving up ecosystem breadth when you choose Pulumi.
When to Choose Pulumi Over Terraform
There are specific scenarios where Pulumi's general-purpose language support genuinely shines over Terraform HCL. Here are the most common ones you'll encounter:
- Dynamic resource creation: When the number or names of resources are determined at runtime โ e.g., "create one subnet per availability zone" or "create one worker node group per environment tier." In HCL this requires awkward
countandfor_eachworkarounds. In Pulumi it's a for loop. - Complex conditional logic: "If this environment is production and the region is us-east-1 and it's Monday, provision this. Otherwise provision that." HCL's conditionals are limited ternary operators. TypeScript is TypeScript.
- Infrastructure unit tests: Pulumi programs are regular code. You can mock the providers and write proper unit tests that verify your security group rules, naming conventions, or tagging policies before deploying.
- Generating infrastructure from data: Reading a YAML config file and creating infrastructure based on its contents. In Pulumi: read the file with Node.js's
fs, parse it, loop over the entries, create resources. In HCL: significant pain. - TypeScript/Python teams: Engineers who write TypeScript or Python daily can be productive in Pulumi on day one. There is zero new syntax to learn.
Pulumi Core Concepts
Pulumi's vocabulary maps closely to Terraform's with a few name changes:
- Project: the directory containing your Pulumi program (your code). Defined by a
Pulumi.yamlfile. Like a Terraform root module. - Stack: an isolated instance of your infrastructure. Production, staging, and development are separate stacks with separate state. Like a Terraform workspace. Each stack has its own configuration and outputs.
- Resource: a cloud resource โ same concept as Terraform.
new aws.ec2.Instance(...) - Config: stack-specific configuration values. Like environment variables, but for your Pulumi stack. Set with
pulumi config set key value. Secrets are encrypted with--secret. - Output: a value exported from your stack โ the IP of a server, the URL of a load balancer. Other stacks can reference these.
- Provider: same as Terraform โ the plugin that communicates with a cloud platform.
Setting Up Pulumi
# Install the Pulumi CLI
curl -fsSL https://get.pulumi.com | sh
# Create a new TypeScript project for AWS
pulumi new aws-typescript
# Create a new Python project for AWS
pulumi new aws-python
# Log into Pulumi's free state backend
pulumi login
# Or use a local state file (no account needed)
pulumi login --local
Pulumi in TypeScript โ A Complete AWS Example
Let's build the same AWS infrastructure we built in Chapter 12 โ VPC, subnets, security group,
EC2 instances โ but this time in TypeScript. Notice how natural it feels, and how the dynamic
subnet creation across multiple availability zones is trivial with a regular .map() call:
// index.ts โ Pulumi TypeScript program
import * as aws from "@pulumi/aws";
import * as pulumi from "@pulumi/pulumi";
// Read configuration for this stack
const config = new pulumi.Config();
const environment = config.require("environment");
const instanceCount = config.getNumber("instanceCount") || 2;
// VPC โ our private network
const vpc = new aws.ec2.Vpc("main-vpc", {
cidrBlock: "10.0.0.0/16",
enableDnsHostnames: true,
tags: {
Name: `${environment}-vpc`,
Environment: environment,
},
});
// Internet Gateway
const igw = new aws.ec2.InternetGateway("main-igw", {
vpcId: vpc.id,
tags: { Name: `${environment}-igw` },
});
// Create subnets dynamically across availability zones โ real loop!
const azs = ["us-east-1a", "us-east-1b", "us-east-1c"];
const subnets = azs.map((az, index) =>
new aws.ec2.Subnet(`public-subnet-${index}`, {
vpcId: vpc.id,
cidrBlock: `10.0.${index + 1}.0/24`,
availabilityZone: az,
mapPublicIpOnLaunch: true,
tags: { Name: `${environment}-public-${az}` },
})
);
// Security Group โ allow web traffic
const sg = new aws.ec2.SecurityGroup("web-sg", {
vpcId: vpc.id,
ingress: [
{ fromPort: 80, toPort: 80, protocol: "tcp", cidrBlocks: ["0.0.0.0/0"] },
{ fromPort: 443, toPort: 443, protocol: "tcp", cidrBlocks: ["0.0.0.0/0"] },
{ fromPort: 22, toPort: 22, protocol: "tcp", cidrBlocks: ["YOUR_IP/32"] },
],
egress: [
{ fromPort: 0, toPort: 0, protocol: "-1", cidrBlocks: ["0.0.0.0/0"] },
],
tags: { Environment: environment },
});
// Get latest Ubuntu 22.04 AMI
const ami = pulumi.output(aws.ec2.getAmi({
mostRecent: true,
owners: ["099720109477"],
filters: [{ name: "name", values: ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"] }],
}));
// Launch EC2 instances โ a real loop, not Terraform's count workaround
const instances = Array.from({ length: instanceCount }, (_, i) =>
new aws.ec2.Instance(`web-server-${i}`, {
ami: ami.id,
instanceType: environment === "production" ? "t3.medium" : "t3.micro",
subnetId: subnets[i % subnets.length].id,
vpcSecurityGroupIds: [sg.id],
tags: {
Name: `${environment}-web-${i}`,
Environment: environment,
},
})
);
// Export useful values as stack outputs
export const vpcId = vpc.id;
export const subnetIds = subnets.map(s => s.id);
export const instanceIds = instances.map(i => i.id);
export const publicIps = instances.map(i => i.publicIp);
Look at the instance type line: environment === "production" ? "t3.medium" : "t3.micro"
โ a native TypeScript ternary. In Terraform you'd write
instance_type = var.environment == "production" ? "t3.medium" : "t3.micro"
which looks similar in this case, but try doing something more complex โ multiple conditions,
a lookup table, a function call โ and the gap widens quickly. In TypeScript you have the entire
language at your disposal.
Pulumi in Python โ Same Infrastructure, Different Language
If your team writes Python, you don't have to learn TypeScript. The exact same infrastructure, expressed in Python:
# __main__.py โ Pulumi Python program
import pulumi
import pulumi_aws as aws
config = pulumi.Config()
environment = config.require("environment")
instance_count = config.get_int("instanceCount") or 2
# VPC
vpc = aws.ec2.Vpc("main-vpc",
cidr_block="10.0.0.0/16",
enable_dns_hostnames=True,
tags={"Name": f"{environment}-vpc", "Environment": environment}
)
# Create subnets dynamically โ Python list comprehension
azs = ["us-east-1a", "us-east-1b", "us-east-1c"]
subnets = [
aws.ec2.Subnet(f"public-subnet-{i}",
vpc_id=vpc.id,
cidr_block=f"10.0.{i+1}.0/24",
availability_zone=az,
map_public_ip_on_launch=True,
tags={"Name": f"{environment}-subnet-{az}"}
)
for i, az in enumerate(azs)
]
# Security Group
sg = aws.ec2.SecurityGroup("web-sg",
vpc_id=vpc.id,
ingress=[
aws.ec2.SecurityGroupIngressArgs(from_port=80, to_port=80, protocol="tcp", cidr_blocks=["0.0.0.0/0"]),
aws.ec2.SecurityGroupIngressArgs(from_port=443, to_port=443, protocol="tcp", cidr_blocks=["0.0.0.0/0"]),
],
egress=[
aws.ec2.SecurityGroupEgressArgs(from_port=0, to_port=0, protocol="-1", cidr_blocks=["0.0.0.0/0"]),
]
)
# Launch multiple instances โ a real Python loop
instance_type = "t3.medium" if environment == "production" else "t3.micro"
instances = [
aws.ec2.Instance(f"web-server-{i}",
instance_type=instance_type,
subnet_id=subnets[i % len(subnets)].id,
vpc_security_group_ids=[sg.id],
tags={"Name": f"{environment}-web-{i}"}
)
for i in range(instance_count)
]
# Export outputs
pulumi.export("vpc_id", vpc.id)
pulumi.export("subnet_ids", [s.id for s in subnets])
pulumi.export("instance_ids", [i.id for i in instances])
pulumi.export("public_ips", [i.public_ip for i in instances])
The Pulumi CLI Workflow
Pulumi's command structure mirrors Terraform's. If you know Terraform, you already know Pulumi's CLI. The main difference is that "workspaces" are called "stacks."
# Install Pulumi CLI
curl -fsSL https://get.pulumi.com | sh
# Create a new TypeScript project in the current directory
pulumi new aws-typescript
# Configure the current stack
pulumi config set environment production
pulumi config set instanceCount 3
pulumi config set --secret DB_PASSWORD my-secret-password
# Preview what will change (like terraform plan)
pulumi preview
# Deploy (like terraform apply โ prompts for confirmation)
pulumi up
# View exported stack outputs
pulumi stack output
pulumi stack output vpcId # specific output
# Destroy all infrastructure in this stack
pulumi destroy
# List all stacks in this project
pulumi stack ls
# Create a new stack (e.g., for staging)
pulumi stack init staging
# Switch to a different stack
pulumi stack select staging
Stacks โ Managing Multiple Environments
Each environment (production, staging, development) is a separate Pulumi stack. Same code, different configuration. This maps directly to a real workflow:
# Set up the production stack
pulumi stack init production
pulumi config set environment production
pulumi config set instanceCount 5
pulumi config set aws:region us-east-1
# Set up the staging stack
pulumi stack init staging
pulumi config set environment staging
pulumi config set instanceCount 1
pulumi config set aws:region us-east-1
# Deploy staging
pulumi stack select staging
pulumi up
# Deploy production (separate state, separate resources)
pulumi stack select production
pulumi up
Each stack's configuration lives in a file like Pulumi.production.yaml and
Pulumi.staging.yaml, which are safe to commit to Git (secrets are encrypted).
Testing Infrastructure Code โ Pulumi's Killer Feature
This is where Pulumi genuinely changes the game. With Terraform, you can run terraform validate
for basic syntax checks, and tools like checkov or tfsec for security
linting. But you cannot write unit tests for Terraform logic the way you'd write unit tests for
application code.
With Pulumi, your infrastructure is application code. You can use Mocha, Jest, Pytest, or Go's testing package to write real unit tests that verify your infrastructure before deploying it. Pulumi's testing SDK lets you mock cloud providers so tests run instantly without touching AWS.
// infra.test.ts โ Pulumi unit tests with Mocha
import * as pulumi from "@pulumi/pulumi";
import { describe, it, before } from "mocha";
import * as assert from "assert";
// Mock the cloud provider โ tests run instantly, no real AWS calls
pulumi.runtime.setMocks({
newResource: (args) => ({
id: `${args.name}-id`,
state: args.inputs,
}),
call: (args) => ({ outputs: {} }),
});
describe("Infrastructure security tests", () => {
let infra: typeof import("./index");
before(async () => {
infra = await import("./index");
});
it("instances should use correct type for production", async () => {
// Verify production uses t3.medium, not t3.micro
const type = await new Promise
infra.instances[0].instanceType.apply(resolve)
);
assert.strictEqual(type, "t3.medium");
});
it("security group should not allow unrestricted SSH", async () => {
// Verify SSH is not open to the world (0.0.0.0/0)
const ingress = await new Promise((resolve) =>
infra.sg.ingress.apply(resolve)
);
const sshRule = ingress.find((r: any) => r.fromPort === 22);
assert.ok(sshRule, "SSH rule should exist");
assert.notStrictEqual(
sshRule.cidrBlocks[0], "0.0.0.0/0",
"SSH must not be open to the world"
);
});
it("all resources should have an Environment tag", async () => {
const tags = await new Promise((resolve) =>
infra.vpc.tags.apply(resolve)
);
assert.ok(tags && tags["Environment"], "VPC must have Environment tag");
});
});
// Run tests: npx mocha --require ts-node/register infra.test.ts
Imagine a junior engineer accidentally removes the CIDR restriction on the SSH security group rule โ now port 22 is open to the entire internet. With Terraform, this passes validation and applies without warning. With Pulumi, the unit test catches this in CI before it ever touches a real environment. Infrastructure tests are your last line of defense against security misconfigurations and naming convention violations.
Pulumi Secrets โ Built-In Encryption
Pulumi handles secrets better than Terraform out of the box. Any config value marked with
--secret is encrypted in the state file and in your Pulumi.stack.yaml file.
Pulumi uses its own encryption service or a key you provide (AWS KMS, Azure Key Vault, etc.).
# Store a secret โ encrypted in state and config file
pulumi config set --secret DB_PASSWORD my-database-password
pulumi config set --secret API_KEY my-api-key
# In your code, read secrets just like regular config
// TypeScript
const config = new pulumi.Config();
const dbPassword = config.requireSecret("DB_PASSWORD");
// dbPassword is a pulumi.Output<string> โ never logged, never exposed
Cross-Stack References
In large projects, it's common to split infrastructure into multiple stacks โ a "network" stack that creates the VPC, a "database" stack that creates RDS, an "app" stack that deploys the application. Pulumi lets stacks reference each other's outputs:
// In the app stack, reference outputs from the network stack
const networkStack = new pulumi.StackReference("myorg/network/production");
const vpcId = networkStack.getOutput("vpcId");
const subnetIds = networkStack.getOutput("subnetIds");
// Now use those values to deploy into the existing VPC
const sg = new aws.ec2.SecurityGroup("app-sg", {
vpcId: vpcId, // comes from the network stack
// ...
});
Pulumi in a CI/CD Pipeline
Like Terraform, Pulumi runs best inside a CI/CD pipeline for team environments. Pull requests
run pulumi preview and post the diff as a comment. Merges to main
trigger pulumi up automatically.
# .github/workflows/pulumi.yml
name: Pulumi Preview and Deploy
on:
pull_request:
branches: [main]
jobs:
preview:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install dependencies
run: npm install
- name: Run infrastructure unit tests
run: npm test
- name: Pulumi Preview
uses: pulumi/actions@v5
with:
command: preview
stack-name: production
env:
PULUMI_ACCESS_TOKEN: ${{ secrets.PULUMI_ACCESS_TOKEN }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
Pulumi also maintains state. By default it's stored in Pulumi's cloud service (free tier available).
You can also self-host state in S3, GCS, or Azure Blob Storage with
pulumi login s3://my-state-bucket. The same rules apply: treat state as sacred,
don't delete it, don't corrupt it, and for team projects always use a shared remote backend.
Chapter Summary
- Pulumi lets you write infrastructure in TypeScript, Python, Go, Java, or C# โ real programming languages with full IDE support, loops, conditionals, functions, and unit tests.
- Pulumi uses the same cloud provider ecosystem as Terraform, via the Pulumi Terraform bridge. Almost every resource available in Terraform is available in Pulumi.
- The core concepts are: Project (your code directory), Stack (isolated environment instance), Resource (a cloud resource), Config (stack-specific settings), and Output (exported values).
- The CLI workflow mirrors Terraform:
pulumi preview(plan),pulumi up(apply),pulumi destroy(destroy),pulumi stack select(switch environments). - Pulumi's biggest differentiator is testability โ write real unit tests against mocked providers that run in milliseconds, catching security misconfigurations before they reach any real environment.
- Secrets are first-class in Pulumi โ marked with
--secret, encrypted in both state and config files. - Choose Pulumi when your infrastructure has complex logic, dynamic resource counts, or when your team wants to unit-test infrastructure. Use Terraform for teams that prefer simplicity and maximum community resources.