TL;DR
Master Infrastructure as Code using Terraform and AWS CloudFormation for efficient cloud resource management.
Infrastructure as Code: Best Practices with Terraform and CloudFormation
Executive Summary
Infrastructure as Code replaces console clicks and runbooks with declarative definitions that can be versioned, reviewed, tested, and applied repeatably. This guide covers the practice through its two most common tools — Terraform, the multi-cloud standard, and AWS CloudFormation, the native AWS service — including project structure, modules, remote state with locking, secrets handling, testing, and the CI workflow that turns a pull request into a reviewed infrastructure change. After reading it, you will be able to structure an IaC codebase that a team can safely change, and decide which tool fits a given estate.
Why This Matters
Manually built infrastructure is unrepeatable by definition. The staging environment that was "basically the same" as production diverges silently until a release behaves differently in each, and nobody can reconstruct a working environment after a failure because the knowledge lived in one engineer's memory and browser history. The costs arrive as incidents: a security group opened during debugging and never closed, a database parameter changed in the console and overwritten by the next deployment, a disaster-recovery environment that turns out to be a diagram rather than a fact. IaC converts infrastructure into an auditable artefact — every change is a diff that can be reviewed before it happens and blamed precisely after it happens. That review step is the real prize: most infrastructure incidents are caused by changes, and IaC is the only approach that puts a change in front of a second pair of eyes before it reaches production.
Core Concepts
The Declarative Model
Both tools are declarative: you describe the resources that should exist, and the engine computes and applies the difference from current state. Terraform expresses this in HCL; a provider plugin translates resources into cloud API calls.
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
Environment = "Production"
}
}Parameters go in as typed variables with descriptions and defaults, and results come out as outputs that other configurations or pipelines can consume:
# variables.tf
variable "environment" {
type = string
description = "Environment name"
default = "development"
}
variable "instance_type" {
type = string
description = "EC2 instance type"
default = "t2.micro"
}
# outputs.tf
output "instance_ip" {
value = aws_instance.web.public_ip
description = "Public IP of the web server"
}CloudFormation expresses the same idea in YAML or JSON templates organised into stacks, with Parameters, Resources, and Outputs as the top-level sections:
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Web Server Infrastructure'
Parameters:
EnvironmentName:
Type: String
Default: Development
Resources:
WebServerInstance:
Type: AWS::EC2::Instance
Properties:
InstanceType: t2.micro
ImageId: ami-0c55b159cbfafe1f0
Tags:
- Key: Name
Value: WebServer
- Key: Environment
Value: !Ref EnvironmentName
Outputs:
WebServerIP:
Description: Public IP of the web server
Value: !GetAtt WebServerInstance.PublicIpThe workflow differs in feel: Terraform shows you a plan to approve before applying, while CloudFormation computes a change set and manages the stack's lifecycle, including automatic rollback on failure. The mental model — desired state, computed diff, controlled apply — is the same.
Modules and Reuse
The unit of reuse in Terraform is the module: a directory of configuration with its own variables and outputs. Mature teams build a library of vetted modules for standard shapes — a VPC, a database, a service — so application teams consume reviewed infrastructure instead of inventing their own:
# modules/vpc/main.tf
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
name = var.vpc_name
cidr = var.vpc_cidr
azs = var.availability_zones
private_subnets = var.private_subnet_cidrs
public_subnets = var.public_subnet_cidrs
enable_nat_gateway = true
enable_vpn_gateway = false
tags = {
Environment = var.environment
Terraform = "true"
}
}CloudFormation's equivalent is the nested stack, where a parent stack composes child templates and passes values between them. In both ecosystems the discipline is identical: pin module and template versions, keep modules small and single-purpose, and treat a module's variables as a public API that other teams depend on.
State Management
State is where IaC stops being a scripting exercise. Terraform records what it manages in a state file; that file must live remotely, encrypted, with locking so two applies cannot interleave:
# backend.tf
terraform {
backend "s3" {
bucket = "terraform-state-bucket"
key = "prod/terraform.tfstate"
region = "us-west-2"
dynamodb_table = "terraform-locks"
encrypt = true
}
}One state per environment and per blast-radius boundary — a single global state means a single corrupted file or careless apply can affect everything. CloudFormation manages state for you inside the service, which removes this whole category of work, at the price of AWS lock-in. In both tools, drift is the standing enemy: changes made outside the tool make the next plan a surprise. Detect drift on a schedule (a nightly plan that should be empty) and treat out-of-band changes as incidents to reconcile, not conveniences to tolerate.
Secrets and Permissions
Infrastructure code references secrets; it never contains them. Read them at apply time from a secret manager:
# Using AWS Secrets Manager
data "aws_secretsmanager_secret_version" "db_password" {
secret_id = "prod/db/password"
}
resource "aws_db_instance" "database" {
password = data.aws_secretsmanager_secret_version.db_password.secret_string
# Other configuration...
}Note that Terraform state will contain values it manages in plaintext form inside the state file — another reason the backend bucket needs encryption and tightly scoped access. The identity running the apply should be equally scoped: a dedicated role whose policy allows the state bucket and the resource types the configuration manages, not the engineer's personal administrator credentials:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetObject",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::terraform-state-bucket",
"arn:aws:s3:::terraform-state-bucket/*"
]
}
]
}Testing and the Delivery Pipeline
Infrastructure code gets the same engineering rigour as application code, adjusted for the fact that applying it creates real resources. Static checks come first: formatting, validation, linting, and policy checks on the plan. Integration testing with a tool such as Terratest applies a configuration in a sandbox account, asserts on the outputs, and destroys everything afterwards:
# test/main_test.go
package test
import (
"testing"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
)
func TestTerraformWebServer(t *testing.T) {
terraformOptions := &terraform.Options{
TerraformDir: "../",
Vars: map[string]interface{}{
"environment": "test",
},
}
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
instanceID := terraform.Output(t, terraformOptions, "instance_id")
assert.NotEmpty(t, instanceID)
}The pipeline shape that works everywhere: on a pull request, run format checks, validate, and post the plan as a review artefact; on merge, apply with the same plan. Tagging ties the estate together for cost allocation and ownership — apply a common tag set from one local definition so every resource carries environment, project, and owner:
locals {
common_tags = {
Environment = var.environment
Project = var.project_name
Owner = var.team
CostCenter = var.cost_center
}
}For disaster recovery, the payoff of all this discipline is simple: a second region is the same modules with a different provider alias and variables, and a rebuild is an apply, not an archaeological expedition.
Decision Framework
| Situation | Recommendation |
|---|---|
| Multi-cloud estate, or plans to be | Terraform — one language and workflow across providers |
| AWS-only estate, minimal tooling appetite | CloudFormation — no state infrastructure to run, native rollback |
| AWS-only but heavy use of third-party tooling and modules | Terraform — the module ecosystem is substantially larger |
| Team already fluent in one tool | Stay with it; the tool matters less than state discipline and review |
| Regulated environment | Either, provided plans/change sets are reviewed artefacts and applies run from a scoped automation role |
| Small team, first IaC adoption | Start with one tool, one environment, remote state, and plan-on-PR before automating applies |
Implementation Checklist
Trade-offs
IaC front-loads effort: writing, reviewing, and testing a module takes longer than clicking through a console wizard, and the return only arrives on the second, third, and thirtieth use. State is a permanent liability — backed up, access-controlled, and occasionally repaired by hand when reality and the file disagree. Abstraction leaks too: modules hide detail operators sometimes need, and provider quirks surface through the tool in ways that require understanding both layers. CloudFormation trades away the state problem but binds you to AWS and its pace of supporting new services; Terraform's breadth means provider quality varies by vendor. Neither tool removes the need to understand the underlying cloud.
When Not to Use
Do not reach for IaC to manage a handful of long-lived, rarely changed resources for a tiny project — the state infrastructure and module discipline cost more than the manual setup they replace; document the manual steps instead and revisit when the estate grows. Do not use Terraform where the platform team has standardised on CloudFormation (or the reverse) without a compelling reason; two IaC tools in one estate means two state systems, two review cultures, and confused ownership. And never use IaC as the mechanism for rapid incident improvisation — during an outage, fix the problem, then reconcile the code to match reality afterwards; an apply fighting an incident response helps neither.
Conclusion
Infrastructure as Code pays off through one mechanism: every change becomes a reviewed, repeatable, reversible artefact instead of an unrecorded act. Choose Terraform for breadth or CloudFormation for AWS-native simplicity, then invest in the parts that actually determine success — remote locked state, secret hygiene, plan-based review, and drift detection. The tool is the easy decision; the discipline is the product.
References
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.