Infrastructure as Code
Managing infrastructure with code — declarative vs imperative tools, Terraform resources, state, plan and apply, modules and environments, drift, Pulumi and CDK, configuration management with Ansible, immutable infrastructure, and policy as code.
Clicking through a cloud console doesn't scale: it's slow, error-prone, undocumented and impossible to reproduce. Infrastructure as Code (IaC) defines servers, networks, databases and permissions in version-controlled files, applied by tools.
Benefits:
- Reproducible: create identical staging and production environments; rebuild after a disaster.
- Reviewable: infrastructure changes go through pull requests like application code.
- Auditable: Git history shows who changed what and why.
- Automated: applied from CI/CD pipelines.
Declarative vs imperative
| Declarative | Imperative |
|---|---|
| Describe the desired end state ("there is a bucket named X with versioning on") | Describe the steps ("create a bucket, then enable versioning") |
| The tool computes the diff and the actions | You handle ordering and existing state |
| Terraform/OpenTofu, CloudFormation, Pulumi, Kubernetes manifests | Shell scripts, CLI calls, (partly) Ansible |
Declarative tools are idempotent: applying the same config twice changes nothing the second time.
Terraform
Terraform (and its open-source fork OpenTofu) is the most widely used multi-cloud IaC tool. You write HCL describing resources from providers (AWS, GCP, Azure, Cloudflare, GitHub, Datadog — thousands exist).
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.0" }
}
backend "s3" { # remote state, with locking
bucket = "acme-terraform-state"
key = "prod/network.tfstate"
region = "ap-south-1"
use_lockfile = true
}
}
provider "aws" { region = var.region }
variable "region" { default = "ap-south-1" }
variable "environment" { type = string }
resource "aws_s3_bucket" "uploads" {
bucket = "acme-uploads-${var.environment}"
tags = { Environment = var.environment, Team = "platform" }
}
resource "aws_s3_bucket_versioning" "uploads" {
bucket = aws_s3_bucket.uploads.id # reference → implicit dependency
versioning_configuration { status = "Enabled" }
}
resource "aws_db_instance" "main" {
identifier = "app-${var.environment}"
engine = "postgres"
engine_version = "17"
instance_class = var.environment == "prod" ? "db.r6g.large" : "db.t4g.micro"
allocated_storage = 50
multi_az = var.environment == "prod"
username = "app"
manage_master_user_password = true # password generated and kept in Secrets Manager
deletion_protection = true
}
output "bucket_name" { value = aws_s3_bucket.uploads.bucket }The workflow
terraform init # download providers, configure the backend
terraform fmt && terraform validate
terraform plan # show what will change: + create, ~ update, - destroy, -/+ replace
terraform apply # execute the plan (after review)
terraform destroy # tear everything downTerraform builds a dependency graph from references and creates resources in parallel where possible.
State
Terraform records what it created in a state file, mapping config to real resource IDs. State is crucial and sensitive:
- Store it remotely (S3, GCS, Terraform Cloud) with locking, so two people can't apply at once.
- It may contain secrets — encrypt it and restrict access.
- Never edit it by hand; use
terraform state mv,importandremoved/movedblocks for refactors. - Drift: if someone changes infrastructure manually,
planshows the difference. Detect drift regularly and fix the process that caused it.
Modules and environments
Modules package reusable infrastructure (a VPC, a service with its load balancer and alarms):
module "api" {
source = "./modules/ecs-service"
name = "api"
image = "registry.example.com/api:${var.image_tag}"
desired_count = 3
vpc_id = module.network.vpc_id
}Separate environments with separate state (directories per environment, or workspaces) and keep blast radius small — split state by component (network, data, apps) so one bad apply can't destroy everything.
Other IaC tools
| Tool | Style | Notes |
|---|---|---|
| CloudFormation | Declarative YAML/JSON | AWS-native; state managed by AWS |
| AWS CDK | General-purpose languages → CloudFormation | Loops, classes, types; AWS-focused |
| Pulumi | TypeScript, Python, Go, C#, Java | Multi-cloud; real programming languages and testing |
| Bicep | Declarative DSL | Azure-native |
| Crossplane | Kubernetes CRDs | Manage cloud resources via the Kubernetes API (GitOps-friendly) |
// Pulumi (TypeScript)
import * as aws from "@pulumi/aws";
const bucket = new aws.s3.BucketV2("uploads", { tags: { team: "platform" } });
export const bucketName = bucket.id;Configuration management
Provisioning tools create infrastructure; configuration management tools configure what runs on servers — packages, files, users, services. Ansible (agentless, over SSH, YAML playbooks), Chef, Puppet and Salt:
- hosts: web
become: true
tasks:
- name: Install nginx
ansible.builtin.apt: { name: nginx, state: present, update_cache: true }
- name: Deploy config
ansible.builtin.template: { src: nginx.conf.j2, dest: /etc/nginx/nginx.conf }
notify: Reload nginx
handlers:
- name: Reload nginx
ansible.builtin.service: { name: nginx, state: reloaded }Immutable infrastructure
Instead of patching servers in place (which causes configuration drift and unique "snowflake" servers), replace them: bake a new machine image (Packer) or container image, deploy new instances, destroy the old ones. Containers and Kubernetes made this the default. Treat servers as cattle, not pets.
Policy as code and testing
- Policy as code: enforce rules automatically in CI — "no public S3 buckets", "all resources tagged", "only approved instance types" — with Open Policy Agent (Conftest), Sentinel, Checkov, tfsec/Trivy.
- Testing:
terraform validate, linting (TFLint), plan review in PRs (Atlantis, Terraform Cloud, Spacelift), and integration tests that create real infrastructure in a sandbox account (Terratest,terraform test). - Secrets: never hard-code them; reference a secrets manager.
- IaC makes infrastructure reproducible, reviewable, auditable and automatable.
- Declarative tools describe the end state and compute the changes; they're idempotent.
- Terraform: providers and resources in HCL; init → plan → apply; references form a dependency graph.
- State maps config to real resources: keep it remote, locked, encrypted and split by component.
- Modules for reuse; separate state per environment; watch for drift.
- Pulumi/CDK use general-purpose languages; Ansible configures servers; immutable infrastructure replaces instead of patching.
- Enforce policies and test infrastructure code in CI.