Terraform Infrastructure as Code: Complete Guide
· Pavan Y N · terraform, devops, aws, cloud
Terraform is an infrastructure as code (IaC) tool from HashiCorp, which IBM acquired in early 2025. It provisions cloud and SaaS resources from declarative configuration files written in HashiCorp Configuration Language (HCL), tracks what it created in a state file, and plans every change before applying it. EduGeek explains the workflow, the building blocks, state management on AWS, and the practices that keep a Terraform codebase safe to change. The examples were validated against Terraform 1.15 and the AWS provider 6.x; Terraform 1.16 is the current release line as of October 2026.
# What Terraform is
Terraform reads configuration files that describe the infrastructure you want, compares them with the state it recorded after the last run, and calls provider APIs to close the gap. The same workflow applies to AWS, Azure, Google Cloud, Kubernetes, and thousands of providers published in the Terraform Registry.
## Licensing, OpenTofu, and product names
Older tutorials, including earlier versions of this guide, call Terraform "open source." That is no longer accurate:
- →License: Terraform 1.6.0 and later is licensed under the Business Source License 1.1 (BSL). The source is public and production use is allowed, but the license restricts offering Terraform as a hosted or embedded product that competes with IBM's paid versions.
- →OpenTofu: OpenTofu is an open source (Mozilla Public License 2.0) fork under the Linux Foundation. It is positioned as a drop-in replacement and reads the same HCL, so the patterns in this guide carry over for everyday work. Check each tool's release notes for features added after the fork.
- →HCP Terraform: The hosted service formerly called Terraform Cloud was renamed HCP Terraform on April 22, 2024. Its functionality did not change with the rename.
## Core concepts
- →Providers are plugins that talk to an API (AWS, Azure, Kubernetes, and so on).
- →Resources are the infrastructure objects to manage: virtual networks, instances, databases.
- →Data sources read information that Terraform does not manage, such as the latest machine image.
- →State records the real objects Terraform manages and how they map to configuration.
- →Modules are reusable groups of resources with their own inputs and outputs.
- →Variables and outputs parameterize a configuration and export values from it.
## The workflow
- •Write the configuration in
.tffiles. - •Init (
terraform init) downloads providers and modules and configures the backend. - •Plan (
terraform plan) previews exactly what would change. - •Apply (
terraform apply) makes the changes and updates state. - •Destroy (
terraform destroy) removes everything the configuration manages, when that is the intent.
# Getting started
## Installation
On macOS, install from HashiCorp's Homebrew tap. The plain brew install terraform command found in older tutorials no longer works because Homebrew's core repository no longer carries a terraform formula.
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
terraform version
On Linux, HashiCorp publishes apt and yum/dnf repositories, and binaries are available for direct download. The official install page lists the exact commands for each platform.
## A first configuration
The configuration below builds a small web tier: a VPC (Virtual Private Cloud), one public subnet and one EC2 (Elastic Compute Cloud) instance per Availability Zone, and a security group. It uses the AWS provider 6.x, Amazon Linux 2023, and S3-native state locking.
main.tf:
terraform {
required_version = ">= 1.11.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true
}
}
provider "aws" {
region = var.aws_region
default_tags {
tags = {
Environment = var.environment
ManagedBy = "Terraform"
Project = var.project_name
}
}
}
locals {
# One subnet and one instance per Availability Zone, keyed by AZ name
az_indexes = { for index, az in var.availability_zones : az => index }
}
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = true
enable_dns_support = true
tags = {
Name = "${var.project_name}-vpc"
}
}
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
tags = {
Name = "${var.project_name}-igw"
}
}
resource "aws_subnet" "public" {
for_each = local.az_indexes
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, each.value)
availability_zone = each.key
map_public_ip_on_launch = true
tags = {
Name = "${var.project_name}-public-${each.key}"
Type = "public"
}
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
tags = {
Name = "${var.project_name}-public-rt"
}
}
resource "aws_route_table_association" "public" {
for_each = aws_subnet.public
subnet_id = each.value.id
route_table_id = aws_route_table.public.id
}
resource "aws_security_group" "web" {
name = "${var.project_name}-web-sg"
description = "Security group for web servers"
vpc_id = aws_vpc.main.id
tags = {
Name = "${var.project_name}-web-sg"
}
}
# One rule per resource: the pattern the AWS provider documentation recommends
# instead of inline ingress/egress blocks.
resource "aws_vpc_security_group_ingress_rule" "http" {
security_group_id = aws_security_group.web.id
description = "HTTP from anywhere"
ip_protocol = "tcp"
from_port = 80
to_port = 80
cidr_ipv4 = "0.0.0.0/0"
}
resource "aws_vpc_security_group_ingress_rule" "https" {
security_group_id = aws_security_group.web.id
description = "HTTPS from anywhere"
ip_protocol = "tcp"
from_port = 443
to_port = 443
cidr_ipv4 = "0.0.0.0/0"
}
resource "aws_vpc_security_group_egress_rule" "all" {
security_group_id = aws_security_group.web.id
description = "Allow all outbound"
ip_protocol = "-1"
cidr_ipv4 = "0.0.0.0/0"
}
# Latest Amazon Linux 2023 AMI, resolved through the public SSM parameter
data "aws_ssm_parameter" "al2023_ami" {
name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
}
resource "aws_instance" "web" {
for_each = aws_subnet.public
ami = data.aws_ssm_parameter.al2023_ami.value
instance_type = var.instance_type
subnet_id = each.value.id
vpc_security_group_ids = [aws_security_group.web.id]
user_data = <<-EOT
#!/bin/bash
dnf install -y nginx
systemctl enable --now nginx
EOT
user_data_replace_on_change = true
metadata_options {
http_tokens = "required" # require IMDSv2
}
root_block_device {
volume_size = 20
volume_type = "gp3"
encrypted = true
}
tags = {
Name = "${var.project_name}-web-${each.key}"
}
}
Two notes on this file. First, the previous version of this guide looked up an Amazon Linux 2 image, but Amazon Linux 2 reached end of support on June 30, 2026, so new instances should use Amazon Linux 2023. Second, backend blocks cannot reference variables; pass environment-specific values with terraform init -backend-config=... instead.
variables.tf:
variable "aws_region" {
description = "AWS Region for resources"
type = string
default = "us-east-1"
}
variable "environment" {
description = "Environment name"
type = string
default = "production"
validation {
condition = contains(["development", "staging", "production"], var.environment)
error_message = "Environment must be development, staging, or production."
}
}
variable "project_name" {
description = "Project name for resource naming"
type = string
}
variable "vpc_cidr" {
description = "CIDR block for the VPC"
type = string
default = "10.0.0.0/16"
validation {
condition = can(cidrhost(var.vpc_cidr, 0))
error_message = "Must be a valid IPv4 CIDR block."
}
}
variable "availability_zones" {
description = "Availability Zones to use, one subnet and one instance per zone"
type = list(string)
default = ["us-east-1a", "us-east-1b", "us-east-1c"]
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t3.micro"
}
outputs.tf:
output "vpc_id" {
description = "ID of the VPC"
value = aws_vpc.main.id
}
output "public_subnet_ids" {
description = "IDs of the public subnets, keyed by Availability Zone"
value = { for az, subnet in aws_subnet.public : az => subnet.id }
}
output "web_instance_ids" {
description = "IDs of the web servers, keyed by Availability Zone"
value = { for az, instance in aws_instance.web : az => instance.id }
}
output "web_instance_public_ips" {
description = "Public IPs of the web servers, keyed by Availability Zone"
value = { for az, instance in aws_instance.web : az => instance.public_ip }
}
output "security_group_id" {
description = "ID of the web security group"
value = aws_security_group.web.id
}
terraform.tfvars:
aws_region = "us-east-1"
environment = "production"
project_name = "my-web-app"
vpc_cidr = "10.0.0.0/16"
availability_zones = ["us-east-1a", "us-east-1b", "us-east-1c"]
instance_type = "t3.small"
## Everyday commands
terraform init # download providers and modules, configure the backend
terraform fmt -recursive # canonical formatting
terraform validate # syntax and internal consistency
terraform plan -out=tfplan # preview changes and save the plan
terraform apply tfplan # apply exactly the plan that was reviewed
terraform apply -refresh-only # reconcile state with real infrastructure
terraform output vpc_id # read one output
terraform state list # list resources in state
terraform state show 'aws_instance.web["us-east-1a"]'
terraform destroy
Apply a saved plan rather than using -auto-approve on a fresh plan, so the change that was reviewed is the change that runs. The older terraform refresh command is deprecated; HashiCorp's documentation replaces it with terraform apply -refresh-only, which shows detected drift and asks for confirmation before writing it to state. Likewise, prefer import blocks (described below) over the imperative terraform import command.
# Core patterns
## Modules
A module is a directory of .tf files that other configurations call. Keep the interface small: input variables in, outputs out.
modules/
└── vpc/
├── main.tf
├── variables.tf
├── outputs.tf
└── versions.tf
module "vpc" {
source = "./modules/vpc"
name = "production-vpc"
vpc_cidr = "10.0.0.0/16"
az_count = 3
}
resource "aws_instance" "app" {
ami = data.aws_ssm_parameter.al2023_ami.value
instance_type = "t3.micro"
subnet_id = module.vpc.public_subnet_ids["us-east-1a"]
}
Modules from the Terraform Registry need a version constraint (for example version = "~> 6.0") so an upgrade is always a deliberate change. Advanced Terraform: Modules and State Management builds a complete VPC module with tests.
## for_each versus count
Resources created with count are addressed by position. Removing one element from the middle of a list shifts every later index, which can force Terraform to destroy and recreate instances that did not change. for_each addresses instances by a stable string key, so that does not happen. This guide uses for_each for per-AZ resources and keeps count for simple on/off toggles (count = var.enabled ? 1 : 0).
## Dynamic blocks
Use a dynamic block to generate repeated nested blocks from data.
variable "extra_volumes" {
description = "Additional EBS volumes to attach, keyed by device name"
type = map(object({
size = number
type = optional(string, "gp3")
}))
default = {
"/dev/sdf" = { size = 100 }
"/dev/sdg" = { size = 50, type = "gp3" }
}
}
resource "aws_instance" "with_volumes" {
ami = data.aws_ssm_parameter.al2023_ami.value
instance_type = "t3.micro"
dynamic "ebs_block_device" {
for_each = var.extra_volumes
content {
device_name = ebs_block_device.key
volume_size = ebs_block_device.value.size
volume_type = ebs_block_device.value.type
encrypted = true
}
}
}
Security group rules are a poor fit for dynamic blocks. The AWS provider documentation recommends separate aws_vpc_security_group_ingress_rule resources, which can be generated with for_each and give each rule its own ID, tags, and description.
## Conditional resources
variable "create_database" {
description = "Whether to create the database"
type = bool
default = true
}
variable "environment" {
description = "Environment name"
type = string
}
variable "db_subnet_ids" {
type = list(string)
}
resource "aws_db_subnet_group" "main" {
count = var.create_database ? 1 : 0
name = "myapp-db"
subnet_ids = var.db_subnet_ids
}
resource "aws_db_instance" "main" {
count = var.create_database ? 1 : 0
identifier = "myapp-db"
engine = "postgres"
engine_version = "17" # version prefix; RDS selects the current minor
instance_class = var.environment == "production" ? "db.t4g.medium" : "db.t4g.micro"
allocated_storage = var.environment == "production" ? 100 : 20
username = "appadmin"
manage_master_user_password = true # RDS stores and rotates the password in Secrets Manager
db_subnet_group_name = aws_db_subnet_group.main[0].name
storage_encrypted = true
skip_final_snapshot = var.environment != "production"
}
output "database_endpoint" {
value = var.create_database ? aws_db_instance.main[0].endpoint : null
}
Pinning an exact minor version such as 15.3, as older examples do, eventually breaks when RDS retires that version. When auto_minor_version_upgrade is enabled (the default), the AWS provider accepts a version prefix such as 17 and RDS picks a supported minor release; run aws rds describe-db-engine-versions --engine postgres to see what is available in your Region.
## For expressions
variable "users" {
type = list(string)
default = ["alice", "bob", "charlie"]
}
resource "aws_iam_user" "users" {
for_each = toset(var.users)
name = each.value
}
locals {
# Map of user name to ARN
user_arns = {
for name, user in aws_iam_user.users : name => user.arn
}
# Filter and transform: instance IDs for production only. tags_all includes
# the provider's default_tags, which plain tags does not.
production_instance_ids = {
for key, instance in aws_instance.web : key => instance.id
if lookup(instance.tags_all, "Environment", "") == "production"
}
}
## Workspaces
CLI workspaces let one configuration keep several state files under the same backend.
terraform workspace list
terraform workspace new staging
terraform workspace select production
terraform workspace show
terraform workspace delete staging
locals {
environment = terraform.workspace
instance_counts = {
default = 1
staging = 2
production = 5
}
instance_types = {
default = "t3.micro"
staging = "t3.small"
production = "t3.medium"
}
}
resource "aws_instance" "app" {
count = local.instance_counts[local.environment]
ami = data.aws_ssm_parameter.al2023_ami.value
instance_type = local.instance_types[local.environment]
tags = {
Name = "app-${local.environment}-${count.index + 1}"
Environment = local.environment
}
}
Workspaces are convenient for short-lived copies of one stack, but HashiCorp's documentation is explicit about their limits. All workspaces in a working directory share one backend and its credentials, so they are "not a suitable isolation mechanism" when development, staging, and production need different access controls. For real environment separation, use a small root configuration per environment, each with its own backend, that instantiates shared modules.
# State management
## Remote state in S3 with native locking
State must live in a shared, locked, versioned backend as soon as more than one person or pipeline runs Terraform. For AWS the usual choice is an S3 bucket.
Locking has changed since the first version of this guide:
- →Terraform 1.10 added S3-native state locking, and Terraform 1.11 made it generally available through the
use_lockfileargument. - →DynamoDB-based locking (
dynamodb_table) is deprecated and will be removed in a future minor version. The two mechanisms can run side by side while you migrate; onceuse_lockfile = trueworks for every user and pipeline, removedynamodb_table. - →The lock is a file stored next to the state, at the state key with
.tflockappended (for exampleprod/terraform.tfstate.tflock). The identity running Terraform needss3:GetObjectands3:PutObjecton the state object,s3:GetObject,s3:PutObject, ands3:DeleteObjecton the lock object, ands3:ListBucketon the bucket. - →With
kms_key_idset, Terraform also needskms:Encrypt,kms:Decrypt, andkms:GenerateDataKeyon that key. - →HashiCorp highly recommends enabling bucket versioning so an earlier state version can be restored after an accidental deletion or bad write.
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true
kms_key_id = "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"
}
}
## Bootstrapping the backend
The bucket must exist before Terraform can use it as a backend. Create it once from a separate configuration with local state, then migrate with terraform init -migrate-state in the configurations that use it.
resource "aws_s3_bucket" "terraform_state" {
bucket = "my-terraform-state"
lifecycle {
prevent_destroy = true
}
}
resource "aws_s3_bucket_versioning" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
kms_master_key_id = aws_kms_key.terraform_state.arn
}
bucket_key_enabled = true
}
}
resource "aws_s3_bucket_public_access_block" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_kms_key" "terraform_state" {
description = "KMS key for Terraform state encryption"
deletion_window_in_days = 10
enable_key_rotation = true
}
New S3 buckets already encrypt objects with SSE-S3 and block public access by default, so the KMS key and the explicit public access block are choices made for key control and for making the intent visible in code, not corrections to an insecure default. The DynamoDB table from earlier versions of this guide is no longer needed.
## Changing state safely
Terraform 1.1 and later can record state changes in configuration, where they are reviewed in a pull request and shown in the plan. Prefer these blocks over editing state by hand.
# Rename a resource without destroying it (Terraform 1.1+)
moved {
from = aws_instance.app_legacy
to = aws_instance.app
}
# Adopt an existing resource into state (Terraform 1.5+)
import {
to = aws_s3_bucket.logs
id = "my-existing-logs-bucket"
}
resource "aws_s3_bucket" "logs" {
bucket = "my-existing-logs-bucket"
}
# Stop managing a resource but keep it in AWS (Terraform 1.7+)
removed {
from = aws_s3_bucket.scratch
lifecycle {
destroy = false
}
}
The imperative commands still exist for one-off repairs:
terraform state mv aws_instance.web aws_instance.app
terraform state rm 'aws_instance.web["us-east-1a"]'
terraform state pull > backup.tfstate
terraform state replace-provider hashicorp/aws registry.example.com/acme/aws
Take a backup with terraform state pull before running any command that rewrites state.
# Troubleshooting
## Issue 1: state lock errors
Symptoms:
- →"Error acquiring the state lock" messages
- →Terraform commands refuse to run
Diagnosis and fix:
# The error prints the lock ID, who holds it, and when it was taken.
# Check whether that run is still alive (a CI job, a colleague's terminal).
# Only if the holder is certain to be dead, for example a crashed CI runner:
terraform force-unlock <LOCK_ID>
Other causes to rule out are network problems reaching S3 and missing s3:PutObject or s3:DeleteObject permission on the .tflock object. With the older DynamoDB mechanism, the equivalent check was permissions on the lock table.
## Issue 2: resource already exists
Symptoms:
- →"AlreadyExists" errors during apply
- →Resources were created outside Terraform
Solution: Add an import block for the existing object (shown above) and run terraform plan. Terraform shows the import as part of the plan, and you can adjust the configuration until the plan is clean.
## Issue 3: dependency errors
Symptoms:
- →Resources created in the wrong order
- →Dependency cycle errors
Solution: Reference attributes of one resource from another so Terraform infers the order. Use depends_on only when the dependency is real but invisible to Terraform.
# Implicit dependency (preferred): the reference creates the ordering
resource "aws_instance" "web" {
vpc_security_group_ids = [aws_security_group.web.id]
}
# Explicit dependency: only when no attribute reference exists
resource "aws_nat_gateway" "this" {
# ... configuration
depends_on = [aws_internet_gateway.main]
}
## Issue 4: provider version conflicts
Symptoms:
- →Provider initialization failures
- →Incompatible provider versions between modules
Solution: Constrain versions in required_providers, commit .terraform.lock.hcl to version control, and generate hashes for every platform your team and CI use.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0" # any 6.x release, never 7.0
}
}
}
terraform providers lock \
-platform=linux_amd64 \
-platform=darwin_arm64 \
-platform=windows_amd64
Major provider upgrades can contain breaking changes. The 6.0 release, for example, made owners or an identifying filter mandatory when aws_ami uses most_recent = true, and removed the vpc argument from aws_eip in favor of domain. Read the provider's upgrade guide before changing ~> 5.0 to ~> 6.0.
# Best practices
## Code organization
- →Use modules for repeated patterns and keep their interfaces small.
- →Separate environments with one root configuration and one backend per environment rather than relying on workspaces for isolation.
- →Use
for_eachwith stable keys for collections. - →Follow one naming and tagging convention, and apply common tags with the provider's
default_tags.
## State
- →Use a remote backend with locking, versioning, and encryption for anything shared.
- →Never edit state files by hand; use
moved,import, andremovedblocks. - →Restrict who can read state, because it can contain secrets in plain text.
## Security
- →Keep secrets out of version control and out of
.tfvarsfiles; use a secrets manager and the provider features that read from it (for examplemanage_master_user_passwordfor RDS). - →Give the identity that runs Terraform only the permissions it needs.
- →Scan configurations in CI with a policy scanner such as Trivy, which absorbed the tfsec project, or Checkov.
## Testing and review
- →Run
terraform fmt -check,terraform validate, andterraform planon every pull request. - →Add
terraform testfor modules; the next article in this series shows a mocked-provider test. - →Review the plan, not only the code, and apply the reviewed plan file.
- →Apply to a non-production environment first.
## Adopting Terraform in an existing estate
- •Inventory what exists and group it by lifecycle and ownership.
- •Write configuration for one group at a time and bring existing resources under management with
importblocks. - •Run
terraform planuntil it reports no changes, which proves the code matches reality. - •Move to the next group, and add CI checks before more people start changing infrastructure.
For the configuration-management side of the same estate, Ansible Automation: Complete Configuration Management Guide covers what to do on the servers Terraform creates, and AWS Cloud Fundamentals for DevOps Engineers explains the services used above.
# Key takeaways
- →Terraform 1.6.0 and later uses the Business Source License, and OpenTofu is the open source fork under the Linux Foundation, so license policy is part of the tool choice.
- →Pin the AWS provider with
~> 6.0, commit.terraform.lock.hcl, and read the upgrade guide before moving across a major version. - →S3-native locking with
use_lockfile = truereplaces the DynamoDB lock table; DynamoDB locking is deprecated. - →Use
for_eachwith stable keys instead ofcountfor collections, so removing one item does not reshuffle the rest. - →Prefer
moved,import, andremovedblocks overterraform statecommands, and useterraform apply -refresh-onlyinstead of the deprecatedterraform refresh. - →Workspaces share a backend and its credentials, so they are not a substitute for separate configurations per environment.
- →Use Amazon Linux 2023 or another supported image; Amazon Linux 2 reached end of support on June 30, 2026.
# Further reading
Test yourself: Terraform Infrastructure as Code assessment