Infrastructure as Code with Terraform
The Concepts chapter showed four Terraform commands and one resource. This chapter builds a small but complete project: how a Terraform configuration is structured, what actually happens during plan and apply, why the state file matters so much, and the mistakes that bite most beginners.
Why Infrastructure as Code
Clicking through the AWS console works once. It doesn't tell anyone what you clicked, it can't be reviewed, and rebuilding the same setup for staging or after an accident is guesswork. With IaC the files are the documentation, changes go through pull requests like code, and apply produces the same result every time. Terraform is declarative (you describe the end state, it works out the steps) and works with hundreds of platforms through providers. Since 2023 Terraform is under the BSL licence; OpenTofu is an open-source fork with the same language and a tofu command.
The building blocks
- Provider: a plugin that talks to one platform's API (AWS, Azure, Cloudflare, GitHub…). Terraform downloads it during
init. - Resource: one thing to create and manage, written
resource "TYPE" "NAME". Its address, likeaws_s3_bucket.site, is how you refer to it elsewhere. - Variable: an input, so the same code works for different names, regions or environments.
- Output: a value printed after apply (an IP, a URL, an ARN) and readable by other tools.
- Data source: reads something that already exists without managing it, like the latest Ubuntu AMI.
Terraform loads every .tf file in the folder together, so splitting into files is just for readability.
A small, complete example: a private S3 bucket
# main.tf
terraform {
required_version = ">= 1.5"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0" # any 6.x, never a surprise 7.0
}
}
}
provider "aws" {
region = var.region
}
resource "aws_s3_bucket" "site" {
bucket = var.bucket_name
tags = {
Project = "devops-practice"
ManagedBy = "terraform"
}
}
resource "aws_s3_bucket_versioning" "site" {
bucket = aws_s3_bucket.site.id # a reference: Terraform creates the bucket first
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_public_access_block" "site" {
bucket = aws_s3_bucket.site.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
# variables.tf
variable "region" {
type = string
default = "eu-central-1"
}
variable "bucket_name" {
description = "Globally unique S3 bucket name"
type = string
}
# outputs.tf
output "bucket_arn" {
value = aws_s3_bucket.site.arn
}
# terraform.tfvars (loaded automatically)
bucket_name = "demee-devops-practice-2026"
References like aws_s3_bucket.site.id tell Terraform about dependencies, so it knows the bucket must exist before its versioning and access settings. Terraform finds AWS credentials the same way the AWS CLI does (aws configure, AWS_PROFILE, or environment variables). Never write access keys in a .tf file.
The workflow: init, plan, apply, destroy
$ terraform init # download providers and modules, set up the backend
$ terraform fmt # format the files
$ terraform validate # catch syntax and type errors without touching AWS
$ terraform plan
# aws_s3_bucket.site will be created
+ resource "aws_s3_bucket" "site" {
+ arn = (known after apply)
+ bucket = "demee-devops-practice-2026"
...
Plan: 3 to add, 0 to change, 0 to destroy.
$ terraform apply # shows the plan again, asks you to type "yes"
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
Outputs:
bucket_arn = "arn:aws:s3:::demee-devops-practice-2026"
$ terraform destroy # delete everything this configuration manages
Read plans carefully: + create, ~ update in place, - destroy, and -/+ destroy and re-create. Some attribute changes (like a bucket's name) can't be made in place, and -/+ on a database means losing its data. In CI, save the reviewed plan with terraform plan -out=tfplan and run terraform apply tfplan, so exactly what was reviewed is applied.
State, remote state and locking
After apply, Terraform writes terraform.tfstate: a JSON map from each resource address to the real object's ID and attributes. That's how it knows aws_s3_bucket.site is that bucket, and what to change next time. Two big problems with keeping it on your laptop: teammates don't have it, and it contains secrets in plain text (database passwords, keys). Teams use a remote backend:
terraform {
backend "s3" {
bucket = "demee-terraform-state"
key = "practice-site/terraform.tfstate"
region = "eu-central-1"
encrypt = true
use_lockfile = true # S3-native locking (Terraform 1.10+)
}
}
Locking stops two people (or two pipelines) running apply at the same time and corrupting the state. Older setups used a DynamoDB table for this; since Terraform 1.11 that option is deprecated in favour of use_lockfile. Other backends include HCP Terraform, Azure Blob Storage and Google Cloud Storage. Backend blocks can't use variables, and after changing one you run terraform init again. Useful state commands: terraform state list, terraform state show aws_s3_bucket.site, terraform output.
Modules
A module is a folder of .tf files you call like a function with inputs. Your root folder is itself a module. Write your own for repeated patterns, or use well-maintained ones from the Terraform Registry, always pinning a version:
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 6.0"
name = "practice"
cidr = "10.0.0.0/16"
}
module "logs_bucket" {
source = "./modules/bucket" # your own module in a subfolder
bucket_name = "demee-practice-logs"
}
Drift
Drift is when real infrastructure no longer matches the code, usually because someone changed it by hand in the console. terraform plan detects it ("Objects have changed outside of Terraform") and proposes changing it back. If the manual change was right, copy it into the code. terraform apply -refresh-only updates the state to match reality without changing any infrastructure. To bring an existing, hand-made resource under Terraform, write an import block (Terraform 1.5+) with the resource's address and real ID, then plan and apply.
Common mistakes
- Committing state or secrets. Add
.terraform/,*.tfstate,*.tfstate.*and any.tfvarsholding secrets to.gitignore. Do commit.terraform.lock.hcl: it pins exact provider versions for everyone. - Hard-coded credentials in the provider block. Use profiles locally and short-lived roles (OIDC) in CI.
- Renaming a resource in code (say
sitetowebsite) makes Terraform plan a destroy and a create. Add amovedblock withfrom = aws_s3_bucket.siteandto = aws_s3_bucket.websiteso it just updates the state. - Unpinned versions: a new major provider version can change behaviour. Always set
versionconstraints. Error: No valid credential sources found: Terraform can't find AWS credentials. Runaws configureoraws sso login, or setAWS_PROFILE.Error acquiring the state lock: someone else is running, or a crashed run left a lock. Wait; only if you're sure nothing is running, useterraform force-unlock LOCK_ID.BucketAlreadyExists: S3 names are global across all AWS accounts. Pick a more unique name.