Skip to content
DBDeependra Bhatta~/notes
Infrastructure as Code#aws · #ssh · #terraform · #ec2 · #s3

Terraform on AWS: EC2, State, Backends, Workspaces and Modules

A hands-on Terraform walkthrough on AWS: launch EC2, read the state file, handle drift, use map variables, provisioners, outputs, an S3 backend, workspaces and modules.

· updated · 29 min read
ON THIS PAGE

Terraform turns AWS infrastructure into code that can be reviewed, versioned and rebuilt, and the habits formed on a small project (reading plans, protecting state, catching drift) carry straight over to production. This guide manages EC2 instances from an Ubuntu VM (built with Vagrant): it starts with one instance in one file, then splits the project, examines the state file and drift, deploys a website with provisioners, moves the state to Amazon S3, and runs the same code in dev, stage and prod with workspaces. Along the way it explains what plan and apply do under the hood and the mistakes worth avoiding.

What Terraform is

Terraform is an infrastructure as code (IaC) tool. You describe resources such as servers, networks and DNS records in text files, and Terraform creates, changes and deletes them for you through the cloud provider's API. Because the files live in Git, the infrastructure can be reviewed, versioned and reused like any other code.

Common IaC choices:

ToolWhere it fits
TerraformMany platforms: AWS, Azure, GCP, Kubernetes, GitHub and thousands more through providers
AWS CloudFormationAWS only, native to AWS
Azure BicepAzure only
OpenTofuOpen-source fork of Terraform with the same language and workflow

Since version 1.6, Terraform is released under the Business Source License (BUSL), which is not an open-source license. That change is the reason OpenTofu exists, as covered in the OpenTofu part of this series.

Two concepts underpin everything that follows:

  • Provider: a plugin that communicates with one platform's API. The hashicorp/aws provider turns aws_instance blocks into EC2 API calls. Providers are published on the Terraform Registry.
  • Workflow: you write configuration, run terraform plan to see what will change, and run terraform apply to make the change. Terraform records what it created in a state file.

Prerequisites

  • An Ubuntu machine (the examples use an Ubuntu 24.04 VM).
  • An AWS account with the AWS CLI configured for an IAM user.
  • An existing security group and EC2 key pair in us-east-1, referenced by ID and name in the examples.

Install Terraform

Install Terraform by following the official install guide (the examples use Ubuntu 24.04), then verify the binary:

terminal
$ terraform --version
$ which terraform

Terminal showing terraform --version reporting Terraform v1.13.0 on linux_amd64

Terminal showing which terraform returning /usr/bin/terraform

Terraform uses the same credentials as the AWS CLI. Configure the CLI as described in the AWS IAM guide, then confirm that it can reach the account:

terminal
$ aws s3 ls

Terminal output of aws s3 ls listing the S3 buckets in the AWS account

Launch an EC2 instance with Terraform

Creating an instance with Terraform requires the same choices as the console: a name, an AMI, an instance type and a security group. The difference is that they are declared in a file rather than entered in a form.

The first configuration

Terraform reads every .tf file in the current directory. The first version uses two files: one for the provider and one for the instance.

TFproviders.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}
 
provider "aws" {
  region = "us-east-1"
}

The required_providers block declares which provider to download and which versions are allowed. Without it, Terraform guesses hashicorp/aws from the resource names and takes the latest version.

TFinstance.tf
resource "aws_instance" "demo_server_dipendra" {
  ami                    = "ami-0360c520857e3138f" # Ubuntu 24.04 in us-east-1
  instance_type          = "t2.micro"
  vpc_security_group_ids = ["sg-05694bdfc51f0d457"]
 
  tags = {
    Name       = "demo-vm-dipenra_Bhatta"
    created_by = "terraform"
  }
}

aws_instance is the resource type and demo_server_dipendra is the local name. Together they form the address aws_instance.demo_server_dipendra, which is how Terraform refers to this instance in plans and in the state.

terraform init

terraform init prepares the directory. It downloads the provider plugin and writes a lock file.

terminal
$ terraform init

terraform init installing hashicorp/aws v6.10.0 and creating the .terraform.lock.hcl lock file

After init there is a hidden .terraform directory that holds the provider binary, and a .terraform.lock.hcl file that records the exact provider version. The lock file is covered later.

tree of the .terraform directory showing the downloaded terraform-provider-aws v6.10.0 binary

terraform plan and terraform apply

terraform plan previews the actions Terraform will take. A + means create, ~ means update in place, and - means destroy.

terminal
$ terraform plan

terraform plan output showing aws_instance.demo_server_dipendra will be created with the Ubuntu AMI

terraform apply displays the same plan, asks for yes, and then makes the change.

terminal
$ terraform apply

terraform apply finishing with 1 added, and the EC2 console showing the new instance running as t2.micro

The state file

After the first apply, a new file appears: terraform.tfstate. It is a JSON file that maps each resource address to the real object in AWS, with all its attributes: instance ID, ARN, AMI, availability zone, IP addresses, security groups and more.

ls showing terraform.tfstate next to instance.tf, and cat of the state with type aws_instance and the AMI ID

How plan decides what to change

Running terraform plan again without editing anything reports no changes.

terraform plan refreshing state for the instance and reporting No changes, infrastructure matches the configuration

A common assumption is that Terraform compares the .tf files only with the local state file. The line Refreshing state... [id=i-0ca1640cbaed4eaf0] shows otherwise: by default, plan and apply first ask AWS for the current attributes of every resource in the state, then work through three elements:

  1. the configuration (.tf files),
  2. the state file, refreshed with the real values from AWS,
  3. and from that, the actions needed to make AWS match the configuration.

The state file tells Terraform which real objects it manages. The refresh tells it what they look like now.

To test an update, add an owner tag in instance.tf. The plan shows an update in place (~), not a replacement:

terraform plan showing an in-place update that adds the owner tag to tags and tags_all

A plan changes nothing in AWS. The console still shows only the old tags:

EC2 tags tab showing only the Name and created_by tags before apply

After terraform apply, the new tag is on the instance:

EC2 tags tab showing the new owner tag after terraform apply

State backup and destroy

After this second apply, Terraform also wrote terraform.tfstate.backup.

ls -al showing terraform.tfstate and terraform.tfstate.backup in the project directory

With the default local backend, Terraform keeps one backup: the state as it was before the last write. The backup helps to check what changed or to recover from a corrupted state file. It does not roll back the infrastructure, and it covers only one step.

terraform destroy deletes everything in the state. Afterwards terraform.tfstate has an empty resources list, and the backup still holds the instance that was just destroyed:

terminal
$ terraform destroy

terraform.tfstate with an empty resources list, and terraform.tfstate.backup still containing the destroyed instance

Split the project into files

Terraform ignores file names; it loads every .tf file in the directory. Splitting files by purpose makes the project easier to read. A typical layout:

FileContents
main.tf or instance.tfResources
providers.tfterraform block with required_providers, and provider blocks
variables.tfInput variables: values that change between runs or environments, such as AMIs, instance types, security groups and zones
outputs.tfValues to print after apply
terraform.tfvarsActual values for the variables

Move the hardcoded values into variables:

TFinstance.tf
resource "aws_instance" "demo_server_dipendra" {
  ami                    = var.AMIS
  instance_type          = var.INSTANCE_TYPE
  vpc_security_group_ids = [var.SECURITY_GROUP]
  availability_zone      = var.ZONE
 
  tags = {
    Name       = "demo-vm-dipendra-Bhatta"
    created_by = "terraform"
  }
}
TFvariables.tf
# The default is used when no other value is given.
variable "REGION" {
  description = "The region where resources are created"
  default     = "us-east-1"
  type        = string
}
 
variable "ZONE" {
  description = "The availability zone for the instance"
  default     = "us-east-1a"
  type        = string
}
 
variable "SECURITY_GROUP" {
  description = "Security group ID"
  default     = "sg-05694bdfc51f0d457"
  type        = string
}
 
variable "AMIS" {
  description = "The AMI ID of the instance"
  default     = "ami-0360c520857e3138f"
  type        = string
}
 
variable "INSTANCE_TYPE" {
  default = "t2.nano"
  type    = string
}

providers.tf stays as before. The upper-case variable names used here work, but the common convention is lower-case snake_case, for example instance_type.

ls -al and tree of the split project showing instance.tf, providers.tf, variables.tf, .terraform and the lock file

Then run the standard cycle:

terminal
$ terraform init
$ terraform validate
$ terraform plan
$ terraform apply

terraform validate checks the syntax and references without calling AWS.

Drift: when AWS and the configuration disagree

Drift means the real infrastructure no longer matches what Terraform expects. It happens when someone changes resources in the console or CLI, when another script or tool changes them, or when AWS itself replaces or removes something. The three tests below each make a manual change outside Terraform. The official drift tutorial goes deeper.

The instance was deleted

After the instance is terminated from the console, terraform apply discovers during the refresh that it is gone and plans to create it again:

terraform apply after the instance was terminated manually, refreshing state and planning to create it again

A tag was added in the console

Next, add a class = DevOps tag in the console:

EC2 tags tab with a manually added class tag set to DevOps

The local state does not include the tag yet:

terraform.tfstate tags block still showing only Name and created_by

After terraform refresh, the tag appears in the state:

terraform.tfstate after refresh now containing the class DevOps tag

Two points matter here:

  • terraform refresh is deprecated. The current way is terraform apply -refresh-only, which shows what will change in the state and asks before writing it. terraform plan -refresh-only only shows it.
  • Refreshing updates the state, not the configuration. The tag is still missing from instance.tf, so the next normal terraform apply will remove it to match the code. If a manual change should stay, add it to the configuration.

The instance was stopped

After the instance is stopped in the console, a refresh records the new instance_state:

terraform.tfstate showing instance_state as stopping after the instance was stopped in the console

Run terraform plan (or terraform plan -refresh-only) regularly so drift surfaces early rather than during an urgent change.

Map variables for region-specific values

AMI IDs differ between regions. The same Ubuntu 24.04 image has these IDs:

RegionAMI ID
us-east-1ami-0360c520857e3138f
us-east-2ami-0cfde0ea8edd312d4

A map variable stores one value per key, and var.AMIS[var.REGION] selects the matching AMI.

TFvariables.tf
variable "REGION" {
  description = "The region where resources are created"
  default     = "us-east-2"
  type        = string
}
 
variable "ZONE" {
  description = "The availability zone for the instance"
  default     = "us-east-1a"
  type        = string
}
 
variable "SECURITY_GROUP" {
  description = "Security group ID"
  default     = "sg-05694bdfc51f0d457"
  type        = string
}
 
variable "AMIS" {
  description = "The AMI ID for each region"
  type        = map(string)
  default = {
    us-east-1 = "ami-0360c520857e3138f"
    us-east-2 = "ami-0cfde0ea8edd312d4"
  }
}
 
variable "INSTANCE_TYPE" {
  default = "t2.nano"
  type    = string
}
TFinstance.tf
resource "aws_instance" "demo_server_dipendra" {
  ami                    = var.AMIS[var.REGION]
  instance_type          = var.INSTANCE_TYPE
  vpc_security_group_ids = [var.SECURITY_GROUP]
  availability_zone      = var.ZONE
 
  tags = {
    Name       = "demo-vm-dipendra-Bhatta"
    created_by = "terraform"
  }
}
TFproviders.tf (provider block)
provider "aws" {
  region = var.REGION
}

With REGION = "us-east-2", the plan picks the us-east-2 AMI:

terminal
$ terraform plan | grep region
$ terraform plan | grep ami

terraform plan filtered with grep showing region us-east-2 and AMI ami-0cfde0ea8edd312d4

With the default changed to us-east-1, the plan selects the us-east-1 AMI:

terraform plan filtered with grep showing region us-east-1 and AMI ami-0360c520857e3138f

Meta-arguments

Meta-arguments work on any resource type and change how Terraform handles the resource, not what the resource is.

depends_on

Terraform derives the order from references: if resource B uses an attribute of resource A, A is created first. depends_on is for the rare case where a dependency exists but is not visible in the code, so B must wait until A is fully done.

TFHCL
resource "aws_instance" "app" {
  # ...
  depends_on = [aws_iam_role_policy.example]
}

See the depends_on documentation.

lifecycle

Some changes cannot be made in place, for example a new AMI. By default, Terraform destroys the old instance first and then creates the new one, which causes downtime. The lifecycle block changes this behavior:

TFHCL
resource "aws_instance" "web" {
  # ...
  lifecycle {
    create_before_destroy = true
  }
}

The three most common rules:

RuleEffect
create_before_destroyCreate the replacement first, then destroy the old object
prevent_destroyFail any plan that would destroy this resource
ignore_changesIgnore changes to the listed attributes, for example tags managed by another tool

count and for_each

Both create several copies of a resource from one block.

  • count = 4 creates four instances, addressed by index: aws_instance.web[0] to aws_instance.web[3].
  • for_each takes a map or a set of strings and creates one instance per key, addressed by key: aws_instance.web["frontend"].

Prefer for_each in most cases. With count, the instances form a list. Removing an item from the middle shifts every later item down one index, so Terraform plans to change or replace those instances as well. With for_each, removing a key removes only that instance.

provider

A resource uses the default aws provider unless told otherwise. To use a second region in the same project, add a provider with an alias and select it with the provider meta-argument:

TFHCL
provider "aws" {
  alias  = "ohio"
  region = "us-east-2"
}
 
resource "aws_instance" "replica" {
  provider = aws.ohio
  # ...
}

Provisioners, and why they are a last resort

A provisioner runs a command or copies files as part of creating (or destroying) a resource. HashiCorp's documentation titles the page Provisioners are a Last Resort, for these reasons:

  • Plan cannot show them. terraform plan shows resource changes, but not what a provisioner will do. A bad script is only found during apply.
  • They need direct access. Most provisioners connect over SSH or WinRM, so Terraform needs network access to the server and login credentials. That widens the attack surface and puts more secrets in play.
  • More moving parts. The right software must be installed, the server must be reachable at the right time, and a failure leaves a half-configured resource that Terraform marks as tainted.

Better options for common cases:

  • Pass a startup script with user_data (cloud-init) on the instance.
  • Bake software into the image with a tool like Packer.
  • Use configuration management such as Ansible after Terraform creates the server.
  • Use a provider resource if one exists for the task.

Types of provisioners

ProvisionerRuns whereNeeds a connection block
local-execOn the machine running TerraformNo
remote-execOn the new resource, as inline commands or a scriptYes
fileCopies files or directories from the local machine to the new resourceYes

A minimal local-exec example:

TFHCL
resource "aws_instance" "web" {
  # ...
  provisioner "local-exec" {
    command = "echo The server's IP address is ${self.private_ip}"
  }
}

All provisioners also accept when (for example, run only at destroy time) and on_failure (fail or continue).

The connection block tells Terraform how to log in: the user, the private key (or password), and the host. self.public_ip refers to the instance being created.

Hands-on: deploy a website with file and remote-exec

Without Terraform, the manual approach is to copy a script with scp and run it over SSH:

terminal
$ scp -i demo-key deploy_app.sh ubuntu@54.212.10.0:/tmp

With Terraform, the file provisioner copies the script, remote-exec runs it, and connection holds the SSH details. The instance also needs key_name, so AWS installs the matching public key on it.

SHdeploy_app.sh
#!/bin/bash
# Runs as root through sudo from remote-exec.
apt install -y apache2 wget unzip
systemctl start apache2
systemctl enable apache2
cd /tmp
wget https://www.tooplate.com/zip-templates/2129_crispy_kitchen.zip
unzip -o 2129_crispy_kitchen.zip
cp -r 2129_crispy_kitchen/* /var/www/html/
systemctl restart apache2
TFinstance.tf
resource "aws_instance" "demo_server_dipendra" {
  ami                    = var.AMIS[var.REGION]
  instance_type          = var.INSTANCE_TYPE
  key_name               = "kp-dipendra-bhatta-aug4"
  vpc_security_group_ids = [var.SECURITY_GROUP]
  availability_zone      = var.ZONE
 
  tags = {
    Name       = "demo-vm-dipendra-Bhatta"
    created_by = "terraform"
    owner      = "Deependra-Bhatta"
  }
 
  # Copy the script from the local machine to the instance
  provisioner "file" {
    source      = "deploy_app.sh"
    destination = "/tmp/deploy_app.sh"
  }
 
  # Run the script on the instance
  provisioner "remote-exec" {
    inline = [
      "chmod u+x /tmp/deploy_app.sh",
      "sudo /tmp/deploy_app.sh"
    ]
  }
 
  # How Terraform logs in for the two provisioners above
  connection {
    type        = "ssh"
    user        = var.USER
    private_key = file("kp-dipendra-bhatta-aug4.pem")
    host        = self.public_ip
  }
}

Add the SSH user to variables.tf (the default user on Ubuntu AMIs is ubuntu):

TFvariables.tf (addition)
variable "USER" {
  default = "ubuntu"
  type    = string
}

The security group must allow SSH (port 22) from your IP for the provisioners, and HTTP (port 80) for the website.

During terraform apply, Terraform prints Provisioning with 'file'..., then connects over SSH and streams the script output:

remote-exec connecting over SSH as user ubuntu with a private key, then apt reading package lists

remote-exec unzipping the Crispy Kitchen template, then Apply complete with 1 resource added

The instance's public IP, shown in the console, serves the site:

EC2 instance details showing the public IPv4 address 18.209.20.178 and state Running

Browser at http://18.209.20.178 showing the Crispy Kitchen website served by Apache

Connecting through a bastion host

In a common setup, the frontend server has a public IP, but the database server sits in a private subnet with no public IP and no NAT gateway, so the internet cannot reach it. To configure the database server, connect through a bastion host (also called a jump host): a hardened server in a public subnet that you SSH into first, then hop to the private server.

The SSH connection block supports this directly with the bastion_* arguments:

TFHCL
connection {
  type        = "ssh"
  user        = "ubuntu"
  private_key = file("db-key.pem")
  host        = self.private_ip
 
  bastion_host        = aws_instance.bastion.public_ip
  bastion_user        = "ubuntu"
  bastion_private_key = file("bastion-key.pem")
}

I have not run this configuration yet; it is the pattern to use when a provisioner must reach a private instance.

Output values

Without outputs, finding the site's IP means searching the console or the state file. Output values print chosen attributes at the end of terraform apply. They also let a child module pass values to its parent, and let other configurations read them through the terraform_remote_state data source.

TFoutputs.tf
output "My_instance_public_ip_address" {
  value = aws_instance.demo_server_dipendra.public_ip
}
 
output "My_instance_private_ip" {
  value = aws_instance.demo_server_dipendra.private_ip
}
 
output "My_instance_public_url" {
  value = aws_instance.demo_server_dipendra.public_dns
}

Outputs can also sit at the bottom of instance.tf, but a separate outputs.tf is easier to find. The plan lists them as known after apply:

terraform plan Changes to Outputs listing the three outputs as known after apply

terraform apply then prints the real values:

terraform apply Outputs section printing the private IP, public IP and public DNS name of the instance

terraform output prints them again at any time without applying.

Remote state in Amazon S3

With the default local backend, terraform.tfstate exists only on the laptop of the person who ran apply. The code is in GitHub, but a teammate who clones it has no state. Terraform then assumes nothing exists and plans to create everything again, or the two people overwrite each other's work.

A backend determines where the state is stored. With the S3 backend, the state lives in a bucket that the whole team (and CI) can reach.

Create a bucket with default settings (here backend-bucket-dipendra-bhatta) and add one file to the provisioner project:

TFbackend.tf
terraform {
  backend "s3" {
    bucket = "backend-bucket-dipendra-bhatta"
    key    = "terraform" # object name of the state file in the bucket
    region = "us-east-1"
  }
}

The bucket must exist before terraform init; Terraform does not create it. The S3 backend docs strongly recommend turning on bucket versioning, so an old state can be recovered after a mistake. A path-like key such as ec2-demo/terraform.tfstate also lets one bucket hold the state of several projects.

terminal
$ terraform init

terraform init reporting Successfully configured the backend s3

After terraform apply, the project directory no longer contains terraform.tfstate:

ls -al of the project with backend.tf and no local terraform.tfstate file

The state is now the terraform object in the bucket:

S3 console showing the bucket backend-bucket-dipendra-bhatta with one object named terraform

Opening the object shows the same JSON as a local state file, including the outputs:

The state object opened from S3 in a browser, showing the outputs and the aws_instance resource

To simulate a teammate, copy only the code into a new directory (example6), with no state file, and run terraform init there. terraform refresh and terraform plan read the state from S3 and find the existing instance, with no changes needed:

In a fresh copy of the project, refresh and plan read state from S3 and report No changes

State locking

If two people run terraform apply on the same state at the same time, both write the state and one change can be lost or the state can break. State locking prevents this: while one run holds the lock, any other run that could write state waits or fails until the lock is released.

The backend.tf above has no locking. In current Terraform, the S3 backend can lock with a lock file stored next to the state in the same bucket:

±backend.tf+1−0
 terraform {
   backend "s3" {
     bucket = "backend-bucket-dipendra-bhatta"
     key    = "terraform"
     region = "us-east-1"
+    use_lockfile = true
   }
 }

Run terraform init again after changing backend settings. Older guides use a DynamoDB table (dynamodb_table) for the lock; the S3 backend docs now mark DynamoDB-based locking as deprecated.

If a run crashes and leaves a lock behind, terraform force-unlock <LOCK_ID> releases it. Use it only after confirming that no other run is active.

Workspaces

Running dev, stage and prod from copies of the same code leads to duplicated files, harder maintenance and accidental changes to the wrong environment. Workspaces let one configuration keep several separate states. Each workspace has its own state, so the same code can create one set of resources per environment.

The terraform workspace subcommands:

CommandWhat it does
terraform workspace listList workspaces; * marks the current one
terraform workspace showPrint the current workspace name
terraform workspace new <name>Create a workspace and switch to it
terraform workspace select <name>Switch to an existing workspace
terraform workspace delete <name>Delete a workspace

Every project starts with a workspace named default. Create three more:

terminal
$ terraform workspace new dev
$ terraform workspace new stage
$ terraform workspace new prod
$ terraform workspace select prod
Switched to workspace "prod".

terraform workspace new dev reporting Created and switched to workspace dev, a new empty workspace

terraform workspace list showing default, dev, prod and stage with stage selected

The current workspace name is stored in .terraform/environment:

tree of .terraform showing the environment file next to the providers directory

Using the workspace name in the code

terraform.workspace holds the current workspace name. The configuration below uses it to set the name tag and to choose an instance type per environment:

TFmain.tf
resource "aws_instance" "demo_server_dipendra" {
  ami                    = var.AMIS[var.REGION]
  key_name               = "kp-dipendra-bhatta-aug4"
  instance_type          = lookup(var.INSTANCE_TYPE, terraform.workspace, "t2.micro")
  vpc_security_group_ids = [var.SECURITY_GROUP]
  availability_zone      = var.ZONE
 
  tags = {
    Name       = "${terraform.workspace}-vm-dipendra-bhatta"
    created_by = "Terraform-code"
    owner      = "Deependra-Bhatta"
  }
}
 
output "instance_id" {
  value = aws_instance.demo_server_dipendra.id
}
 
output "instance_name" {
  value = terraform.workspace
}
TFvariables.tf
variable "REGION" {
  description = "The region where resources are created"
  default     = "us-east-1"
  type        = string
}
 
variable "ZONE" {
  description = "The availability zone for the instance"
  default     = "us-east-1b"
  type        = string
}
 
variable "SECURITY_GROUP" {
  description = "Security group ID"
  default     = "sg-05694bdfc51f0d457"
  type        = string
}
 
variable "AMIS" {
  description = "The AMI ID for each region"
  type        = map(string)
  default = {
    us-east-1 = "ami-0360c520857e3138f"
    us-east-2 = "ami-0cfde0ea8edd312d4"
  }
}
 
variable "INSTANCE_TYPE" {
  type = map(string)
  default = {
    dev   = "t2.micro"
    stage = "t2.nano"
    prod  = "t2.small"
  }
}

providers.tf is the same as before, with region = var.REGION.

The lookup function

lookup(map, key, default) returns the value for key from map, or default if the key is not there. Here, lookup(var.INSTANCE_TYPE, terraform.workspace, "t2.micro") gives t2.small in prod and falls back to t2.micro in any workspace that is not in the map, such as default. The default argument is technically optional, but leaving it out is deprecated; without a fallback, plain indexing var.INSTANCE_TYPE[terraform.workspace] does the same thing and fails on a missing key.

Result

Running terraform apply in each workspace creates three instances from the same code, with different names and types:

EC2 console with three running instances: statge, prod and dev, with types t2.micro, t2.small and t2.micro

Note the stage instance: it is named statge and got t2.micro, not t2.nano, because I created that workspace with a typo. statge is not a key in the map, so lookup silently used the fallback. A fallback default is convenient, but it can hide mistakes like this one.

With the local backend, each workspace's state is stored under terraform.tfstate.d/<workspace>/:

Project tree with the shared .tf and .tfvars files, and terraform.tfstate.d holding one state per workspace

The .tfvars files in that tree are empty for now; they are the place for environment-specific values, passed with terraform apply -var-file=prod.tfvars.

terraform destroy only touches the current workspace. Destroying in the stage workspace terminated only that instance:

EC2 console with the statge instance terminated while the prod and dev instances keep running

Without workspaces: one directory per environment

The other common approach is a directory per environment, each with its own main.tf, variables.tf, outputs.tf and terraform.tfvars, sharing code through modules:

Project tree with Environments/dev, prod and stage directories plus shared instance.tf, providers.tf, variables.tf and a modules folder

Here variables.tf declares the variables, and each terraform.tfvars sets the actual values for that environment. Values that change often stay out of the main code.

Modules

A module is a directory of .tf files used as one unit. Modules let you define a piece of infrastructure once and reuse it, much like a function in a program.

  • Root module: the .tf files in the directory where you run Terraform. Every configuration has one.
  • Child module: a module called from another module with a module block. One child module can be called many times, with different inputs.
  • Published module: a module loaded from a registry instead of a local path. The Terraform Registry has many public modules, and HCP Terraform and Terraform Enterprise offer private registries.

Calling a local module:

TFHCL
module "servers" {
  source = "./app-cluster"
 
  servers = 5
}

Calling a module from the registry, pinned to a version:

TFHCL
module "consul" {
  source  = "hashicorp/consul/aws"
  version = "0.0.5"
 
  servers = 3
}

Run terraform init after adding a module so Terraform can download it. For common building blocks such as a VPC, a well-maintained registry module is usually a better starting point than writing everything from scratch.

The dependency lock file

terraform init writes .terraform.lock.hcl, which records the exact provider version and its checksums:

cat .terraform.lock.hcl showing provider registry.terraform.io/hashicorp/aws pinned to version 6.10.0 with hashes

In a team, the lock file keeps provider versions consistent. If developer A built the infrastructure with AWS provider 6.10.0 and developer B clones the repository months later, terraform init without a lock file would select the newest provider, and a different provider version can plan different changes. With the lock file committed to Git, everyone gets the same version:

terraform init reusing hashicorp/aws v6.10.0 from the dependency lock file

To move to a newer provider on purpose, run terraform init -upgrade and commit the updated lock file.

A .gitignore for a Terraform project should contain at least:

TXT.gitignore
.terraform/
*.tfstate
*.tfstate.*
*.pem

Commit .terraform.lock.hcl; ignore the .terraform/ directory.

Command reference

CommandWhat it does
terraform -helpList all commands
terraform initPrepare the directory: download providers and modules, configure the backend
terraform fmtRewrite .tf files in the standard style
terraform validateCheck syntax and references
terraform planShow the changes needed to match the configuration
terraform applyMake the changes (asks for yes)
terraform apply -auto-approveApply without asking. Use only in automation or immediately after reviewing the plan
terraform apply -refresh-onlyUpdate the state from real infrastructure (replaces terraform refresh)
terraform destroyDestroy everything in the current state
terraform outputPrint output values
terraform showShow the current state or a saved plan
terraform graphPrint the dependency graph in DOT format, for example terraform graph | dot -Tsvg > graph.svg with Graphviz
terraform importBring an existing resource under Terraform management
terraform force-unlockRelease a stuck state lock
terraform workspaceManage workspaces
terraform stateInspect and change the state (see below)
terraform consoleTry expressions interactively

terraform console evaluates expressions and functions interactively before they go into code, for example to check a variable or read a file:

terminal
$ terraform console
> length(var.ZONE)
10

terraform console evaluating file() on instance.tf and printing the file contents

The terraform state subcommands:

CommandWhat it does
terraform state listList resources in the state
terraform state show <address>Show one resource
terraform state mvMove or rename an item in the state
terraform state rmStop managing a resource without destroying it
terraform state pullPrint the current state, for example from S3
terraform state pushOverwrite the remote state with a local file (use with great care)
terraform state replace-providerChange the provider source recorded in the state

Troubleshooting

The following problems came up, or nearly did, while building these examples.

ProblemCauseFix
region = us-east-1 gives an invalid reference errorWithout quotes, Terraform reads it as an expression, not textQuote strings: region = "us-east-1"
File provisioner cannot find the scriptsource = "deployapp.sh" did not match the real file name deploy_app.shUse the exact file name, relative to the directory where you run Terraform
Provisioner times out connecting over SSHThe instance had no key_name, so the key in connection did not match; or port 22 was closedSet key_name, open SSH from your IP in the security group
sudo cd /tmp/ fails in the scriptcd is a shell built-in, so sudo cannot run itUse plain cd /tmp; the whole script already runs through sudo
An environment gets the wrong instance typeWorkspace created as statge; lookup fell back to the defaultCheck terraform workspace show; consider plain indexing so a missing key fails
Apply fails after switching regionAMI, availability zone and security group IDs are region-specificMap every regional value, not only the AMI
Manual console change disappears on next applyRefresh updated the state, but the configuration still differsAdd the change to the .tf files if it should stay
Every run reports a lock errorA crashed run left the state lockterraform force-unlock <LOCK_ID> after confirming no run is active

Key takeaways

  • plan refreshes real resources from AWS before comparing; the state file tells Terraform which objects it owns.
  • Keep state out of Git and in a remote backend such as S3, with versioning and locking (use_lockfile = true).
  • Commit .terraform.lock.hcl so everyone uses the same provider versions.
  • Detect drift with terraform plan -refresh-only and move manual changes back into code.
  • Use provisioners only when nothing else works; prefer user_data, images or Ansible.
  • Workspaces give one state per environment from the same code, but defaults in lookup can hide typos.

Next in this series: OpenTofu.