TL;DR
Learn the fundamentals of Terraform for infrastructure automation. This guide covers core concepts, basic commands, and best practices for managing cloud infrastructure as code.
Terraform Basics: A Comprehensive Guide to Infrastructure as Code
Executive Summary
Terraform is HashiCorp's infrastructure as code tool: you describe the infrastructure you want in declarative configuration files, and Terraform works out how to create, update, or delete resources to match. This guide covers the building blocks — providers, resources, variables, outputs, data sources, and state — and the core workflow of init, plan, and apply. It also covers the habits that matter from day one: pinning versions, keeping state remote, and structuring a project cleanly. After reading it, you should be able to write a small configuration, run it safely, and know which practices to adopt before the codebase grows.
Why This Matters
The alternative to infrastructure as code is clicking through consoles and running one-off scripts. That works until you need a second environment, a second engineer, or an answer to the question "why does production look like this?" Manual infrastructure cannot be reviewed before it exists, cannot be reproduced after it breaks, and drifts silently as people make fixes under pressure. Terraform's model — a declared desired state, a previewable plan, and a recorded state file — is what makes infrastructure reviewable, repeatable, and recoverable. Learning the basics properly matters because the common beginner mistakes, such as local state and unpinned providers, are exactly the ones that become painful to unwind later.
Core Concepts
Declarative Configuration and Providers
You declare resources; Terraform computes the changes. A provider is the plug-in that teaches Terraform to talk to a platform — AWS, Azure, Google Cloud, Kubernetes, and many others. Providers are declared with a source and a version constraint, and configured per environment:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-west-2"
}Credentials are deliberately not part of this block in real projects. Providers pick up credentials from their platform's standard chain — environment variables, shared config files, or the identity of the machine or CI role running Terraform. Hard-coding access keys in configuration is a leak waiting for a commit.
Resources
A resource block declares one piece of infrastructure. The first label is the type, the second is your local name for it, and the body sets its arguments:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "example-instance"
}
}Resources reference each other by address — aws_instance.example.id — and those references are how Terraform builds its dependency graph and orders creation and destruction correctly. Explicit depends_on exists for dependencies Terraform cannot infer, and should be the exception, not the pattern.
Variables, Locals, and Outputs
Variables parameterise a configuration, outputs expose values from it, and locals name expressions you reuse:
# variables.tf
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
# outputs.tf
output "instance_ip" {
description = "Public IP of the instance"
value = aws_instance.example.public_ip
}Give every variable a type and a description. Use validation blocks for values with a fixed set of acceptable answers, and mark secrets sensitive = true so they stay out of CLI output — while remembering they still land in the state file.
Data Sources
Data sources read information that already exists outside the configuration — an AMI published by Canonical, a VPC managed elsewhere, a DNS zone:
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical
}Prefer a data source over a hard-coded ID whenever the value is owned by someone else; the ID will change, and the lookup will not.
State
Terraform records what it manages in a state file. State maps configuration to real resource IDs, stores the attributes providers return, and lets Terraform compute a precise diff instead of guessing. Two rules follow from this. First, state belongs in a remote backend with locking as soon as anyone shares the configuration:
# Backend configuration for state management
terraform {
backend "s3" {
bucket = "terraform-state-bucket"
key = "terraform.tfstate"
region = "us-west-2"
}
}Second, state contains sensitive values in plain text, so access to it is access to your infrastructure's secrets. Never commit it to source control.
The Core Workflow
Four commands cover daily work:
terraform init
Downloads providers and modules, configures the backend, and writes a lock file recording the exact provider versions selected. Commit the lock file; it is what makes runs reproducible across machines.
terraform plan
Shows precisely what will be created, changed, or destroyed, without changing anything. Read plans. Surprises belong here, not in apply output.
terraform apply
Executes the plan after confirmation and updates state. In team settings, apply a previously saved plan file so the change you reviewed is the change that runs.
terraform destroy
Removes everything the configuration manages. Useful for ephemeral environments, dangerous everywhere else; treat it accordingly.
Two supporting commands earn their place quickly: terraform fmt normalises formatting (run it in CI with -check), and terraform validate catches syntax and reference errors before a plan ever runs.
Project Layout and Version Pinning
A conventional layout keeps declarations findable as the project grows:
project/ ├── main.tf # Main configuration ├── variables.tf # Variable declarations ├── outputs.tf # Output declarations ├── terraform.tfvars # Variable values └── providers.tf # Provider configuration
Pin both the Terraform version and provider versions. Unpinned providers upgrade silently and change behaviour under you; constraints plus the lock file make upgrades deliberate, reviewable events:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0.0" # Use version constraints
}
}
required_version = ">= 1.0.0"
}Decision Framework
| Situation | Recommendation |
|---|---|
| First configuration, learning | Local state, one provider, a handful of resources; run plan before every apply |
| Second person or CI joins | Move state to a remote backend with locking before anything else changes |
| Same pattern needed twice | Extract a module rather than copying resource blocks |
| Value owned outside this configuration | Data source, not a hard-coded ID or a variable someone must look up |
| Secret values | Variables marked sensitive, supplied via environment or a secret store; never committed tfvars |
| Repeating an environment | Separate root configurations per environment, not one config with conditional everything |
Implementation Checklist
.terraform.lock.hcl is committedterraform fmt -check and terraform validate pass in CITrade-offs
Terraform's declarative model is its strength and its constraint. You describe outcomes, which makes changes predictable, but expressing genuinely procedural logic — ordered multi-step processes, complex conditionals — fights the language. The state file is a single point of operational truth that must be stored, locked, backed up, and access-controlled; teams that ignore that discover it during an incident. Provider quality also varies: the major cloud providers are mature, while smaller providers can lag the APIs they wrap, and every provider upgrade is a change to test rather than a formality. Finally, Terraform manages the resources it creates well and the things that happen inside them — packages, files, application config — poorly; that boundary shapes the next section.
When Not to Use
Conclusion
Terraform's basics are few: providers supply resources, variables and outputs form the interface, state records reality, and init, plan, and apply drive the workflow. The craft is in the surrounding habits — pinned versions, remote locked state, reviewed plans, no credentials in code. Build those habits on your first small configuration and they will still be serving you when the estate is large.
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.