Terraform in practice: variables, modules and environments
Chapter 5 built one bucket from one file. Real infrastructure has a dev and a production copy that should differ only in size and names, pieces that repeat, resources that already exist, and a team that changes it through pull requests. This chapter covers the Terraform features that make that manageable.
Variables, outputs and locals
Variables are a configuration's inputs, outputs are what it reports back, and locals are named values you compute inside it:
# variables.tf
variable "env" {
type = string
description = "dev, staging or prod"
validation {
condition = contains(["dev", "staging", "prod"], var.env)
error_message = "env must be dev, staging or prod."
}
}
variable "instance_type" {
type = string
default = "t3.micro"
}
variable "db_password" {
type = string
sensitive = true # hidden in plan output
}
# main.tf
locals {
name = "shop-${var.env}"
tags = { project = "shop", env = var.env, managed_by = "terraform" }
}
resource "aws_s3_bucket" "assets" {
bucket = "${local.name}-assets"
tags = local.tags
}
# outputs.tf
output "assets_bucket" {
value = aws_s3_bucket.assets.bucket
}
Values come from, in rising priority: the default, a terraform.tfvars or *.auto.tfvars file (loaded automatically), -var-file=prod.tfvars, and -var "env=prod" on the command line. Environment variables named TF_VAR_db_password also work, which is how CI passes secrets without writing them to a file.
Many of the same thing: count and for_each
# count: N copies, numbered 0, 1, 2...
resource "aws_instance" "web" {
count = 3
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
tags = { Name = "web-${count.index}" }
}
# for_each: one per key, named by the key
resource "aws_s3_bucket" "store" {
for_each = toset(["logs", "backups", "uploads"])
bucket = "${local.name}-${each.key}"
}
Prefer for_each for anything with a name. With count, removing the middle item renumbers everything after it, and Terraform destroys and recreates resources that didn't need to change. With for_each, each resource is tracked by its key (aws_s3_bucket.store["logs"]), so removing one touches only that one.
Data sources: read what already exists
A data block looks something up instead of creating it: the newest Ubuntu image, the current account ID, a VPC another team manages.
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical, the publisher of Ubuntu
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
}
}
data "aws_caller_identity" "current" {}
output "account_id" { value = data.aws_caller_identity.current.account_id }
Modules: write it once, use it everywhere
A module is just a folder of .tf files with variables and outputs. Every configuration is already a module (the root module); you can call others from it:
modules/
web_service/
variables.tf # name, instance_type, instance_count, vpc_id...
main.tf # the security group, instances, load balancer target group
outputs.tf # the load balancer DNS name
envs/
dev/main.tf
prod/main.tf
# envs/prod/main.tf
module "api" {
source = "../../modules/web_service"
name = "shop-api-prod"
instance_type = "t3.medium"
instance_count = 3
}
output "api_url" { value = module.api.url }
Run terraform init again after adding or changing a module's source. Public modules from the Terraform Registry work the same way with source = "terraform-aws-modules/vpc/aws" and a version constraint; read one before you use it, since you're taking on all of its choices.
Environments: one folder each
The simplest layout that stays safe is a folder per environment, each with its own backend (its own state file) and a small main.tf that calls the shared modules. Dev and prod can't touch each other's state, plans are easy to read, and prod can pin an older module version while dev tries a new one.
Terraform also has workspaces (terraform workspace new dev), several state files for one folder of code, with terraform.workspace holding the current name. They're handy for short-lived copies, but it's easy to run apply in the wrong one, so most teams use separate folders for real environments.
Importing and moving without destroying
Resources made by hand can be brought under Terraform with an import block (Terraform 1.5 and later). Terraform can even write the resource block for you:
import {
to = aws_s3_bucket.legacy
id = "shop-old-uploads" # the bucket's real name
}
$ terraform plan -generate-config-out=generated.tf # writes a starting resource block
$ terraform apply # now it's in state; tidy generated.tf by hand
Renaming a resource in code normally means "destroy the old one, create a new one". A moved block tells Terraform it's the same thing under a new address:
moved {
from = aws_s3_bucket.assets
to = aws_s3_bucket.store["assets"]
}
Guard rails with lifecycle
resource "aws_db_instance" "main" {
# ...
lifecycle {
prevent_destroy = true # any plan that would delete it fails
ignore_changes = [tags["last_backup"]] # changed by something else, don't fight it
}
}
Terraform in a team: plan in the PR, apply on merge
- Every pull request runs
terraform fmt -check,terraform validate, a linter such as tflint, a config scan (trivy config, see DevOps chapter 11) andterraform plan, and posts the plan as a comment. - The reviewer reads the plan, not just the code: "3 to add, 0 to change, 0 to destroy" is the line that matters.
- After merge, CI runs
terraform applyon that same plan, using OIDC credentials (no stored keys) and the shared, locked remote state from chapter 5.
Nobody runs apply from a laptop against prod. That one rule prevents most Terraform disasters.
Common mistakes
- Hard-coding names and sizes so dev and prod need separate copies of the code. Make them variables and keep one module.
- Using count for named things, then watching Terraform rebuild half of them after one deletion. Use for_each.
- Secrets in .tfvars files committed to Git. Pass them as
TF_VAR_environment variables from the CI secret store, or read them from a secrets manager with a data source. Remember the state file still contains them, so keep state encrypted and private. - Renaming without a moved block, and a "simple refactor" plan wants to destroy a database. Always read the plan.
- Huge root modules where one plan takes ten minutes and touches everything. Split by lifetime and owner: network, data, apps.