Infrastructure as code
Clicking through a web console is fine for learning, but it doesn't scale: nobody remembers exactly which 40 settings they chose, the staging environment slowly drifts from production, and recreating everything after a mistake takes days. Infrastructure as code (IaC) describes your cloud resources in text files, kept in Git, reviewed like code, and applied by a tool that creates, updates and deletes resources to match.
Why it matters
| Without IaC | With IaC |
|---|---|
| "Who changed the firewall rule?" | Every change is a reviewed Git commit |
| Staging and production differ in mysterious ways | Both come from the same files, with different variables |
| Rebuilding after a disaster takes days | apply recreates it in minutes |
| New region or new customer = repeat 200 clicks | Copy a folder, change a variable |
| Unused resources pile up, nobody knows what's safe to delete | Everything belongs to a stack you can destroy as a unit |
The tools
| Tool | Clouds | Language |
|---|---|---|
| Terraform / OpenTofu | All (thousands of providers) | HCL |
| CloudFormation | AWS | YAML / JSON |
| AWS CDK | AWS | TypeScript, Python, Java, Go… (generates CloudFormation) |
| Bicep / ARM templates | Azure | Bicep / JSON |
| Pulumi | All | TypeScript, Python, Go, C#… |
| Google Cloud Infrastructure Manager | Google Cloud | Terraform |
They all work the same way: you declare the desired state ("a bucket with versioning, a queue, a table"), and the tool works out what to create, change or delete.
CloudFormation: a stack from a template
A template declares resources (and optional parameters and outputs). CloudFormation creates them as one stack:
AWSTemplateFormatVersion: "2010-09-09"
Description: Order processing - storage, queue and table
Parameters:
Env:
Type: String
AllowedValues: [dev, prod]
Default: dev
Resources:
InvoiceBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "acme-invoices-${Env}"
VersioningConfiguration:
Status: Enabled
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
OrdersDeadLetterQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "orders-dlq-${Env}"
OrdersQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "orders-${Env}"
VisibilityTimeout: 60
RedrivePolicy:
deadLetterTargetArn: !GetAtt OrdersDeadLetterQueue.Arn
maxReceiveCount: 3
OrdersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub "orders-${Env}"
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- { AttributeName: customer, AttributeType: S }
- { AttributeName: order_date, AttributeType: S }
KeySchema:
- { AttributeName: customer, KeyType: HASH }
- { AttributeName: order_date, KeyType: RANGE }
Outputs:
QueueUrl:
Value: !Ref OrdersQueue
BucketName:
Value: !Ref InvoiceBucket!Subinserts values (${Env}) into strings;!Refand!GetAttreference other resources, which also tells CloudFormation the order to create them in (the dead-letter queue before the queue that uses it).- Parameters make one template serve several environments.
- Outputs publish useful values (the queue URL, the bucket name) for other stacks and scripts:
aws cloudformation describe-stacks --stack-name orders-dev --query "Stacks[0].Outputs".
aws cloudformation validate-template --template-body file://orders-stack.yaml --query "Parameters[].ParameterKey" --output text
aws cloudformation deploy --stack-name orders-dev --template-file orders-stack.yaml --parameter-overrides Env=dev 2>&1 | grep -v "^$"
aws cloudformation describe-stacks --stack-name orders-dev --query "Stacks[0].[StackName, StackStatus]" --output text
aws cloudformation describe-stack-resources --stack-name orders-dev \
--query "StackResources[].[LogicalResourceId, ResourceType, ResourceStatus]" --output tableWaiting for changeset to be created.. Waiting for stack create/update to complete Successfully created/updated stack - orders-dev orders-dev CREATE_COMPLETE ---------------------------------------------------------------------- | DescribeStackResources | +-----------------------+------------------------+-------------------+ | InvoiceBucket | AWS::S3::Bucket | CREATE_COMPLETE | | OrdersDeadLetterQueue| AWS::SQS::Queue | CREATE_COMPLETE | | OrdersQueue | AWS::SQS::Queue | CREATE_COMPLETE | | OrdersTable | AWS::DynamoDB::Table | CREATE_COMPLETE | +-----------------------+------------------------+-------------------+
Changing infrastructure safely
Edit the template, and CloudFormation works out the difference. A change set previews it before anything happens, like git diff for infrastructure:
sed -i 's/VisibilityTimeout: 60/VisibilityTimeout: 120/' orders-stack.yaml
aws cloudformation deploy --stack-name orders-dev --template-file orders-stack.yaml --no-execute-changeset 2>&1 \
| grep -E "^Changeset created"
cs=$(aws cloudformation list-change-sets --stack-name orders-dev --query "Summaries[-1].ChangeSetId" --output text)
echo "--- what will change:"
aws cloudformation describe-change-set --change-set-name "$cs" --query "Changes[].ResourceChange.[Action, LogicalResourceId]" --output text
aws cloudformation execute-change-set --change-set-name "$cs" && aws cloudformation wait stack-update-complete --stack-name orders-dev
q=$(aws sqs get-queue-url --queue-name orders-dev --query QueueUrl --output text)
echo "--- queue visibility timeout is now: $(aws sqs get-queue-attributes --queue-url "$q" --attribute-names VisibilityTimeout --query Attributes.VisibilityTimeout --output text)"Changeset created successfully. Run the following command to review changes: --- what will change: Modify OrdersQueue --- queue visibility timeout is now: 120
--no-execute-changeset creates the change set without applying it, so you (or a reviewer) can inspect it first. On a real account, describe-change-set also shows a Replacement column for each change: always check it. Some changes (like renaming a database) can't be made in place: CloudFormation creates a new resource and deletes the old one, with its data. Protect important resources with DeletionPolicy: Retain, stack termination protection, and backups.
Terraform: the multi-cloud standard
Terraform (and its open-source fork OpenTofu) is the most widely used IaC tool. The same idea, in HCL:
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
backend "s3" { # where Terraform keeps its state (shared, locked)
bucket = "acme-terraform-state"
key = "orders/dev.tfstate"
region = "ap-south-1"
use_lockfile = true
}
}
provider "aws" {
region = "ap-south-1"
default_tags { tags = { project = "orders", env = var.env, managed_by = "terraform" } }
}
variable "env" { type = string }
resource "aws_sqs_queue" "orders_dlq" {
name = "orders-dlq-${var.env}"
}
resource "aws_sqs_queue" "orders" {
name = "orders-${var.env}"
visibility_timeout_seconds = 60
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.orders_dlq.arn
maxReceiveCount = 3
})
}
output "queue_url" { value = aws_sqs_queue.orders.url }terraform init # download providers, connect the state backend
terraform plan -var env=dev # preview: what will be created, changed, destroyed
terraform apply -var env=dev # make it so (asks for confirmation)
terraform destroy -var env=dev # delete everything this configuration createdExample output of terraform plan:
Terraform will perform the following actions:
# aws_sqs_queue.orders will be created
+ resource "aws_sqs_queue" "orders" {
+ name = "orders-dev"
+ visibility_timeout_seconds = 60
...
}
# aws_sqs_queue.orders_dlq will be created
+ resource "aws_sqs_queue" "orders_dlq" {
+ name = "orders-dlq-dev"
...
}
Plan: 2 to add, 0 to change, 0 to destroy.Terraform records what it manages in a state file. Keep it in a shared, locked backend (an S3 bucket, a Google Cloud Storage bucket, Azure Storage or HCP Terraform), never in Git, because it can contain secrets. The Terraform course on this site goes much deeper.
Good practices
- Everything in Git, changed through pull requests. Run
plan(or a change set) in CI and post it on the pull request for review. - The same code for every environment, with variables for the differences (sizes, counts, names).
- Small, focused stacks/modules (network, data, app) rather than one giant file.
- No manual changes in the console for IaC-managed resources: they cause drift. Detect it with
terraform planor CloudFormation drift detection. - Tag everything (
project,env,owner) through default tags: it makes costs and clean-up traceable. - Protect stateful resources (databases, buckets with data) from accidental deletion.
- Secrets come from the secret manager at runtime, not from IaC files.
Clean up
Deleting the stack deletes everything in it, in the right order:
aws s3 rm s3://acme-invoices-dev --recursive > /dev/null 2>&1
aws cloudformation delete-stack --stack-name orders-dev
aws cloudformation wait stack-delete-complete --stack-name orders-dev && echo "stack deleted"
aws sqs list-queues --queue-name-prefix orders --query "length(QueueUrls || \`[]\`)"stack deleted 0
Practice
- Add a second queue
notifications-${Env}to the template, preview it with a change set, then apply it. - Deploy the same template as a
prodstack and confirm the names differ. - Write the Terraform for an S3 bucket with versioning and a lifecycle rule.
- Explain why the Terraform state file should be in a locked, shared backend.
1.What does terraform plan (or a CloudFormation change set) do?
2.What is "drift"?
3.How should one template serve both dev and prod?
4.Which IaC tool works across AWS, Google Cloud and Azure?