Infrastructure as Code
Infrastructure as Code (IaC) means defining your servers, networks, databases, and cloud resources in code files that are stored in version control. You apply those files to provision infrastructure, the same way you apply code changes to an application.
Instead of clicking through a cloud console or SSHing into servers to configure them, your infrastructure is declared in files and deployed automatically.
Why It Matters
Without IaC, infrastructure is configured manually. This causes problems:
- Drift — staging and production diverge over time as ad-hoc changes are made to one and not the other
- Undocumented state — nobody knows exactly what is running or why it was set up that way
- Broken deployments — "works in staging, broken in production" is often an infrastructure difference, not a code difference
- No rollback — there is no way to revert manual infrastructure changes reliably
IaC solves all of these by making infrastructure changes reviewable, repeatable, and reversible.
Key Principles
- Declarative — describe the desired state, let the tool work out how to get there
- Idempotent — applying the same configuration multiple times produces the same result
- Version controlled — infrastructure changes go through pull requests, just like code
- Environment parity — dev, staging, and production are defined from the same configuration with environment-specific variables
Popular Tools
| Tool | Notes |
|---|---|
| Terraform | Most widely adopted IaC tool, cloud-agnostic, HCL syntax |
| OpenTofu | Open source Terraform fork maintained by the Linux Foundation |
| Pulumi | IaC using real programming languages (TypeScript, Python, Go) |
| AWS CloudFormation | AWS-native IaC, YAML or JSON |
| AWS CDK | Define AWS infrastructure in TypeScript/Python, compiles to CloudFormation |
| Ansible | Configuration management and server provisioning, YAML-based |
Terraform Example
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = {
Name = "web-server"
Environment = "production"
}
}
Run terraform plan to preview changes, terraform apply to provision.
Workflow
- Write or update the infrastructure definition
- Open a pull request — reviewers can see exactly what will change
- Run
terraform planin CI to show the diff as a PR comment - Merge the PR
- Apply the changes via CI/CD pipeline in the target environment
State Management
Terraform tracks what has been deployed in a state file. In a team, this state must be stored remotely (e.g. in an S3 bucket with locking via DynamoDB) so multiple engineers are not applying changes simultaneously with conflicting local state files.