The Frustration with Domain-Specific Languages
Most DevOps teams eventually hit a wall with Domain-Specific Languages (DSLs) like HashiCorp Configuration Language (HCL). What begins as clean, readable syntax can quickly spiral out of control. As stacks expand past 50 resources, teams often find themselves tangled in messy string interpolations, brittle dynamic blocks, and awkward for_each workarounds.
Simple tasks become frustrating chores. Want to validate an IP range with regex, tag resources conditionally from an external CMDB, or fetch an auth token via an HTTP endpoint? In standard HCL, you either hack together external data sources or surrender and write Bash wrappers.
Testing presents an even steeper hurdle. Validating a subnet calculation often demands spinning up an entire sandbox environment on AWS, burning 10 to 15 minutes per run. If something fails, you wait another 5 minutes for teardown.
Pulumi eliminates this friction by treating infrastructure as real software. Choosing Python lets you tap into language staples you already use every day: native loops, classes, PyPI packages, standard formatters like Black, and unit test suites running in pytest within 150 milliseconds.
Core Concepts: How Pulumi Works Under the Hood
Pulumi is not just a thin wrapper sending raw boto3 calls to AWS. It separates intent from execution through a decoupled architecture with three distinct layers:
- The Language Host: Executes your Python code (Python 3.9+) and registers declared resources with the central engine.
- The Pulumi Engine: Compares your target code against the current state file (stored in Pulumi Cloud, an S3 bucket, or a GitLab HTTP backend) and computes an optimized dependency graph.
- Resource Providers: Translates state operations into concrete cloud API actions through standard gRPC interfaces.
Understanding Inputs and Outputs
Cloud provisioning runs asynchronously. Because AWS assigns attributes like an EC2 public IP or an RDS endpoint only after resource creation, Pulumi models these values as Output[T] types. Think of them like Python promises or futures.
Outputs wire dependencies automatically. Passing vpc.id into a subnet definition tells the engine to hold subnet creation until the VPC exists. When you need to manipulate an output string—such as combining a database host and port into a connection URL—use the .apply() method instead of direct string interpolation:
db_url = db_instance.endpoint.apply(
lambda ep: f"postgresql://dbadmin:{db_password}@{ep}/production_db"
)
Hands-on Practice: Building a VPC, EC2, and RDS with Python
Replacing static configurations with object-oriented code makes architectural patterns easily shareable across internal squads. Let us build a resilient baseline topology: an isolated VPC, an Nginx web tier, and a private PostgreSQL instance.
Step 1: Initializing the Project
First, verify your AWS CLI credentials (e.g., via aws sts get-caller-identity). Then create a clean project directory and scaffold the stack:
mkdir pulumi-aws-platform && cd pulumi-aws-platform
pulumi new aws-python --name platform-infra
The CLI generates a virtual environment along with two critical files: Pulumi.yaml and __main__.py. Activate the virtual environment and install the AWS provider:
source venv/bin/activate
pip install pulumi-aws==6.30.0
Step 2: Defining a Reusable Network Topology (VPC)
Open __main__.py. We will create a VPC with a /16 CIDR, one public subnet in us-east-1a, and two isolated private subnets across two Availability Zones for database high availability:
import pulumi
import pulumi_aws as aws
# Base resource tags
default_tags = {
"Project": "PlatformInfra",
"Environment": "Production",
"ManagedBy": "Pulumi",
}
# Create VPC with a /16 block (65,536 potential IPs)
vpc = aws.ec2.Vpc(
"app-vpc",
cidr_block="10.0.0.0/16",
enable_dns_hostnames=True,
enable_dns_support=True,
tags={**default_tags, "Name": "app-vpc"},
)
# Attach Internet Gateway for outbound connectivity
gateway = aws.ec2.InternetGateway(
"app-igw",
vpc_id=vpc.id,
tags={**default_tags, "Name": "app-igw"},
)
# Public Subnet (10.0.1.0/24 - 251 usable IPs)
public_subnet = aws.ec2.Subnet(
"app-public-subnet-1a",
vpc_id=vpc.id,
cidr_block="10.0.1.0/24",
availability_zone="us-east-1a",
map_public_ip_on_launch=True,
tags={**default_tags, "Name": "app-public-subnet-1a"},
)
# Private Subnets across us-east-1a and us-east-1b for RDS requirements
private_subnet_a = aws.ec2.Subnet(
"app-private-subnet-1a",
vpc_id=vpc.id,
cidr_block="10.0.10.0/24",
availability_zone="us-east-1a",
tags={**default_tags, "Name": "app-private-subnet-1a"},
)
private_subnet_b = aws.ec2.Subnet(
"app-private-subnet-1b",
vpc_id=vpc.id,
cidr_block="10.0.11.0/24",
availability_zone="us-east-1b",
tags={**default_tags, "Name": "app-private-subnet-1b"},
)
# Public Routing Table directing 0.0.0.0/0 out through IGW
public_rt = aws.ec2.RouteTable(
"app-public-rt",
vpc_id=vpc.id,
routes=[
aws.ec2.RouteTableRouteArgs(
cidr_block="0.0.0.0/0",
gateway_id=gateway.id,
)
],
tags={**default_tags, "Name": "app-public-rt"},
)
aws.ec2.RouteTableAssociation(
"app-public-rta",
subnet_id=public_subnet.id,
route_table_id=public_rt.id,
)
Step 3: Provisioning the Compute Layer (EC2 with Custom User Data)
Next, define a security group that allows inbound HTTP traffic on port 80, query the latest Amazon Linux 2023 AMI image, and launch a budget-friendly t3.micro instance running Nginx:
# Security group for web instances
web_sg = aws.ec2.SecurityGroup(
"web-sg",
vpc_id=vpc.id,
description="Allow port 80 ingress and all egress",
ingress=[
aws.ec2.SecurityGroupIngressArgs(
protocol="tcp",
from_port=80,
to_port=80,
cidr_blocks=["0.0.0.0/0"],
)
],
egress=[
aws.ec2.SecurityGroupEgressArgs(
protocol="-1",
from_port=0,
to_port=0,
cidr_blocks=["0.0.0.0/0"],
)
],
tags={**default_tags, "Name": "web-sg"},
)
# Query the latest official Amazon Linux 2023 minimal image
ami = aws.ec2.get_ami(
most_recent=True,
owners=["amazon"],
filters=[
aws.ec2.GetAmiFilterArgs(
name="name",
values=["al2023-ami-2023.*-x86_64"],
)
],
)
# Bootstrap script for Nginx
user_data = """#!/bin/bash
dnf update -y
dnf install -y nginx
systemctl enable --now nginx
echo "<h1>Production Ready: Pulumi + Python</h1>" > /usr/share/nginx/html/index.html
"""
web_server = aws.ec2.Instance(
"web-server",
instance_type="t3.micro",
vpc_security_group_ids=[web_sg.id],
ami=ami.id,
subnet_id=public_subnet.id,
user_data=user_data,
tags={**default_tags, "Name": "web-server"},
)
Step 4: Provisioning the Database Layer (RDS PostgreSQL)
Direct database exposure to the internet is a common vulnerability. Here, our RDS instance resides strictly within the two private subnets. Its firewall rule accepts connections on port 5432 exclusively from members of web_sg:
# RDS multi-AZ subnet group
db_subnet_group = aws.rds.SubnetGroup(
"db-subnet-group",
subnet_ids=[private_subnet_a.id, private_subnet_b.id],
tags={**default_tags, "Name": "app-db-subnet-group"},
)
# Database firewall allowing PostgreSQL traffic solely from web instances
db_sg = aws.ec2.SecurityGroup(
"db-sg",
vpc_id=vpc.id,
description="Permit PostgreSQL from web security group only",
ingress=[
aws.ec2.SecurityGroupIngressArgs(
protocol="tcp",
from_port=5432,
to_port=5432,
security_groups=[web_sg.id],
)
],
egress=[
aws.ec2.SecurityGroupEgressArgs(
protocol="-1",
from_port=0,
to_port=0,
cidr_blocks=["0.0.0.0/0"],
)
],
tags={**default_tags, "Name": "db-sg"},
)
# Retrieve encrypted credentials from stack config
config = pulumi.Config()
db_password = config.require_secret("dbPassword")
# Provision managed PostgreSQL 15.4
db_instance = aws.rds.Instance(
"postgres-db",
allocated_storage=20,
max_allocated_storage=50,
engine="postgres",
engine_version="15.4",
instance_class="db.t3.micro",
db_name="production_db",
username="dbadmin",
password=db_password,
db_subnet_group_name=db_subnet_group.name,
vpc_security_group_ids=[db_sg.id],
skip_final_snapshot=True,
tags={**default_tags, "Name": "postgres-db"},
)
# Stack outputs for operational access
pulumi.export("vpc_id", vpc.id)
pulumi.export("web_public_ip", web_server.public_ip)
pulumi.export("db_endpoint", db_instance.endpoint)
Step 5: Executing and Validating Deployments
Store your database master password safely. Pulumi encrypts secrets with per-stack AES-256 GCM keys before persisting anything to state:
pulumi config set --secret dbPassword "P@ssw0rdSecure2024!Val"
Run a dry run first. Pulumi parses the Python dependency tree and lists planned creations in seconds:
pulumi preview
If the preview looks correct, apply the changes. AWS takes roughly 4 to 6 minutes to allocate the storage and bring up the RDS instance:
pulumi up --yes
Once provisioned, inspect your web tier directly from the command line:
curl http://$(pulumi stack output web_public_ip)
You should see <h1>Production Ready: Pulumi + Python</h1> returned instantly. To tear down every resource and prevent unexpected AWS charges, run:
pulumi destroy --yes
Practical Recommendations for Teams
Writing infrastructure in Python bridges the gap between software engineers and cloud architects. You can enforce standard software quality controls: distribute baseline VPC blueprints as versioned internal PyPI wheels, run pytest with mocks to catch IP allocation conflicts before deploying, and pipe Bandit scans through GitHub Actions.
Hold infrastructure code to the same standards as customer-facing code. Leverage Python type hints (mypy) to catch typos in resource arguments early. Keep stack secrets encrypted, enforce strict security group boundaries, and let real programming abstractions handle complex cloud architectures.

