Bookmarks
ReferenceDevOps & cloudVerified

Terraform

Terraform is an infrastructure-as-code tool for cloud resources. This reference covers HCL, providers, state, modules, plan and apply, and OpenTofu.

checked 1 Nov · next check 8 Nov · 47 min read

Sections
12
Reading
47 min
Current version
1.17.1
Written from
developer.hashicorp.com/terraform/docs

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Terraform is and how it works

Terraform is an infrastructure-as-code tool. You describe the resources you need in .tf files, and Terraform creates, changes and deletes them through the APIs of clouds and services. Before every change it shows a plan and waits for your confirmation.

Terraform suits anything that can be created through an API: virtual machines, networks and storage in the cloud, DNS records, SaaS settings. One configuration can bring up several environments in the same way — dev, staging and production. Installing and configuring software inside an existing machine is not its job; configuration management tools such as Ansible do that.

Terraform itself cannot work with any cloud. That is done by providers — plugins, each for the API of its own platform. Terraform Core reads the configuration and the state — a file that records which real objects correspond to the resources in the configuration. Core builds a plan from the difference between them, and terraform apply carries it out through the providers and records the result in the state.

After apply, Terraform records in the state which objects it created; the next plan compares the state with the configuration and the real objects.

The configuration is declarative: it describes the end result, not the steps. Terraform works out the order itself: it builds a dependency graph of the resources and creates or changes independent resources in parallel. Reusable sets of resources are packaged as modules.

How Terraform differs from Ansible

AspectTerraformAnsible
Purposecreates and changes infrastructure: machines, networks, DNS, servicesconfigures systems: installs and updates software, rolls out applications
How it is describeddeclaratively, in HCLYAML playbooks describing the desired state of a system
What it manages throughthe APIs of clouds and services, via providersSSH, with OS credentials
Agent on the target systemnot needednot needed (agentless)
Running it againcompares the configuration with the state and the real objects, and changes only the differencechanges nothing if the system is already in the described state

Choose Terraform to create cloud infrastructure and keep it in line with the code, and Ansible to configure the OS and software on machines that already exist. They are often combined: Terraform creates the machine and passes it cloud-init, which starts the configuration on first boot.

OpenTofu is a fork of Terraform that appeared after HashiCorp moved from an open-source licence to the BUSL (Business Source License), and it was handed over to the Linux Foundation. It is run with the tofu command, works with the same providers through its own registry, and aims for feature parity with Terraform. OpenTofu can read state created by Terraform up to and including version 1.5.x without conversion.

What you need to know first

  • The basics of the cloud you work with: accounts, regions, networks and permissions.
  • The command line and environment variables — see the Bash reference, section “Variables and parameter expansion”.
  • Git: the configuration is kept in a repository and changed through pull requests — see the Git reference.
  • Addresses and subnets — see the TCP/IP and DNS reference, section “IPv4: addresses, masks and subnets”.

Section sources

the section is written from these pages

Cheat sheet

Everyday commands; each is covered in detail in its own section. Run them in the directory with your .tf files, and replace the names from the examples (aws_instance.web, prod.tfvars, lb_address) with your own.

Getting started

TaskCommand
Prepare the directory: providers, modules, backendterraform init
Upgrade providers and modules within version constraintsterraform init -upgrade
Prepare the directory without connecting to the backendterraform init -backend=false
Terraform and provider versionsterraform version
Which providers the configuration needsterraform providers
Record hashes for Linux and macOS in the lock fileterraform providers lock -platform=linux_amd64 -platform=darwin_arm64
Run a command in another directoryterraform -chdir=environments/prod plan
Try out an expression in the consoleterraform console

Plan and apply

TaskCommand
Show the plan of changesterraform plan
Save the plan to a fileterraform plan -out=tfplan
Inspect a saved planterraform show tfplan
Apply a saved plan without promptingterraform apply tfplan
Create a plan and apply it after confirmationterraform apply
Variable values from a fileterraform plan -var-file=prod.tfvars
A single variable on the command lineterraform plan -var='environment=prod'
Exit code 2 if there are changes — for CIterraform plan -detailed-exitcode
Update the state from the real objects without changing themterraform apply -refresh-only
All output valuesterraform output
Output values as JSONterraform output -json
A single value without quotes — for scriptsterraform output -raw lb_address

State

TaskCommand
Resources in the stateterraform state list
Attributes of one resourceterraform state show 'aws_instance.web'
The same as JSON (since 1.16)terraform state show -json 'aws_instance.web'
Find a resource by its cloud IDterraform state list -id=i-abcd1234
List workspacesterraform workspace list
Create a workspace and switch to itterraform workspace new staging
Switch to a workspaceterraform workspace select staging

Checking the code

TaskCommand
Format files to the standard styleterraform fmt
The same in all subdirectoriesterraform fmt -recursive
Check the style without changing anything — for CIterraform fmt -check -recursive
Show what formatting would changeterraform fmt -diff
Check syntax and referencesterraform validate
Run the tests from *.tftest.hcl filesterraform test

Import and refactoring

TaskCommand
Import an object into the state (better: an import block)terraform import aws_instance.web i-abcd1234
Generate resource blocks from import blocksterraform plan -generate-config-out=generated.tf
Rename a resource in the state (better: a moved block)terraform state mv aws_instance.web aws_instance.app
Check what a rename would affectterraform state mv -dry-run aws_instance.web aws_instance.app
Stop managing an object without deleting itterraform state rm 'aws_instance.web'

Destroying

TaskCommand
Plan the deletion of everything, without changing anythingterraform plan -destroy
Delete everything the configuration managesterraform destroy
Delete one resource and everything that depends on itterraform destroy -target=aws_instance.web
Recreate a resourceterraform apply -replace=aws_instance.web
Apply without confirmationterraform apply -auto-approve
Release a stuck lock (the ID is in the error message)terraform force-unlock LOCK_ID

Section sources

the section is written from these pages

Installation and first run

The official way to install is the terraform package from the HashiCorp repository: with apt on Ubuntu and Debian, yum on RHEL, and Homebrew on macOS. Check the result with terraform version.

Linux

On Ubuntu and Debian, add the key and the apt.releases.hashicorp.com repository, then install the package. The key goes into /usr/share/keyrings, and the signed-by option lets the repository use only that key.

bashon the host
# the key that signs the HashiCorp repositoryKEY=/usr/share/keyrings/hashicorp-archive-keyring.gpgwget -O - https://apt.releases.hashicorp.com/gpg \  | sudo gpg --dearmor -o "$KEY"# codename of the Ubuntu or Debian releaseCODENAME=$(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release \    || lsb_release -cs)ARCH=$(dpkg --print-architecture)REPO="https://apt.releases.hashicorp.com $CODENAME main"echo "deb [arch=$ARCH signed-by=$KEY] $REPO" \  | sudo tee /etc/apt/sources.list.d/hashicorp.listsudo apt update && sudo apt install terraform

On RHEL and compatible systems, add the repository with yum-config-manager:

bashon the host
sudo yum install -y yum-utilssudo yum-config-manager --add-repo \  https://rpm.releases.hashicorp.com/RHEL/hashicorp.reposudo yum -y install terraform

macOS and Windows

On macOS, install Terraform from the HashiCorp tap: brew tap hashicorp/tap, then brew install hashicorp/tap/terraform. On Windows, the official method is the ZIP archive with the binary from the installation page, in AMD64, ARM64 and 386 builds.

Checking the installation

bashon the host
terraform version
textexample output
Terraform v1.17.1on linux_amd64

The first line is the Terraform version, the second is the platform. Below that, the command lists the installed providers and tells you if a newer version has been released. With the -json flag the output is machine-readable, for scripts and CI.

Autocompletion and CLI settings

For bash and zsh, Terraform can add command autocompletion to your shell profile itself; restart the shell afterwards.

bashon the host
terraform -install-autocomplete

Settings shared by all directories are kept in ~/.terraformrc (on Windows, terraform.rc in the %APPDATA% directory). The most useful one is the plugin cache: without it, every directory downloads its own copy of a provider, and a provider can weigh hundreds of megabytes. Create the cache directory in advance, because Terraform does not create it.

bashon the host
mkdir -p "$HOME/.terraform.d/plugin-cache"
hcl~/.terraformrc
# each provider is downloaded once for all directoriesplugin_cache_dir = "$HOME/.terraform.d/plugin-cache"

The same cache can be enabled with the TF_PLUGIN_CACHE_DIR environment variable. Concurrent terraform init runs sharing one cache are not guaranteed to be safe: the installer’s behaviour with several init runs is undefined. CHECKPOINT_DISABLE=1 turns off the check for new versions and security bulletins.

OpenTofu

Install OpenTofu separately, following the instructions on its website. It is run with the tofu command and has the same subcommands: tofu init, tofu plan, tofu apply.

Section sources

the section is written from these pages

The HCL language: blocks, variables and expressions

Terraform configuration is written in HCL, a language made of blocks and arguments. Terraform reads all the .tf files in a directory as a single document — a module — so splitting them into main.tf, variables.tf and outputs.tf is only for people.

hclmain.tf
# block type, then labelsresource "aws_instance" "web" {  ami           = var.ami_id  instance_type = "t3.micro"   tags = {    Name = "web"  }}

Here resource is the block type, "aws_instance" and "web" are labels, and inside are arguments of the form name = expression. The block type decides how many labels are needed: resource takes two, variable one, locals none. A comment starts with #; names consist of letters, digits, _ and - and cannot start with a digit.

The terraform block and the Terraform version

hclterraform.tf
terraform {  # 1.17 or later, but below 2.0  required_version = "~> 1.17"}

If the Terraform version does not satisfy required_version, every command fails immediately. The same block declares providers (required_providers) and the backend (backend). Values in it must be known before the plan, so it cannot refer to resources.

Input variables

An input variable is a parameter of a module. The variable block declares it, and expressions refer to it as var.environment. The reference example is the declarations in variables.tf and the values in terraform.tfvars:

hclvariables.tf
variable "environment" {  type        = string  description = "Deployment environment"  default     = "dev"   validation {    condition     = contains(["dev", "staging", "prod"], var.environment)    error_message = "environment must be one of: dev, staging, prod."  }} variable "ami_id" {  type        = string  description = "AMI for the web servers"} variable "instance_count" {  type    = number  default = 1} variable "allowed_cidrs" {  type    = list(string)  default = []} variable "db_password" {  type      = string  sensitive = true}
hclterraform.tfvars
environment    = "prod"ami_id         = "ami-a1b2c3d4"instance_count = 3allowed_cidrs  = ["203.0.113.0/24"]
bashin the configuration directory
# the secret comes from the environment, not from a file in Gitexport TF_VAR_db_password='change-me'terraform plan
ArgumentWhat it setsDefault
typethe type of the valueany — any type
defaultthe default value; without it the variable is requirednone
descriptiona description for whoever calls the modulenone
validationa custom rule: condition and error_messagenone
sensitivehides the value in plan and apply output, but not in the statefalse
nullablewhether null may be passedtrue
ephemeralkeeps the value out of the state and the plan file (since 1.10)false
constthe value is known already at init — needed for the source and version of modules and providersfalse
deprecateda deprecation message for the variable (since 1.15)none

How to set a variable’s value

If a root module variable has no default, Terraform asks for a value before planning. The files terraform.tfvars, terraform.tfvars.json and *.auto.tfvars are picked up automatically; any other file is passed with the -var-file flag. When a value comes from several places, the precedence is as follows, from highest to lowest:

  1. the -var and -var-file flags, in the order given;
  2. *.auto.tfvars and *.auto.tfvars.json files, in alphabetical order;
  3. the terraform.tfvars.json file;
  4. the terraform.tfvars file;
  5. environment variables with the TF_VAR_ prefix, for example TF_VAR_environment;
  6. default in the variable block.

A value for an undeclared variable is an error in the -var flag, a warning in a .tfvars file, and is silently ignored in an environment variable. Write values of complex types in JSON in flags and the environment: -var='allowed_cidrs=["203.0.113.0/24"]'.

Local and output values

A local value gives a name to an expression so you do not repeat it: it is declared in a locals block and read as local.name, only inside its own module. An output value is what a module hands out: a root module prints it after apply and on terraform output, and a child module passes it to the calling module.

hclmain.tf
locals {  name = "web-${var.environment}"  tags = {    Environment = var.environment    ManagedBy   = "terraform"  }} resource "aws_instance" "web" {  count         = var.instance_count  ami           = var.ami_id  instance_type = var.environment == "prod" ? "t3.small" : "t3.micro"   tags = merge(local.tags, {    Name = "${local.name}-${count.index}"  })} output "web_private_ips" {  description = "Private IP addresses of the web servers"  value       = aws_instance.web[*].private_ip}

Expressions

WhatHow to write it
Input variablevar.environment
Local valuelocal.name
Resource attributeaws_instance.web.id
Output value of a child modulemodule.network.subnet_id
Substitution into a string (interpolation)"web-${var.environment}"
Conditionvar.environment == "prod" ? 3 : 1
A new list from an old one[for s in var.names : upper(s)]
A map from a list{ for s in var.names : s => upper(s) }
Attributes of all instances with count (splat)aws_instance.web[*].id
Function calllength(var.allowed_cidrs)

You cannot define your own functions in a configuration, but there are dozens of built-in ones: length, merge, lookup, join, cidrsubnet and others. Providers add their own functions with the provider::name:: prefix, for example provider::terraform::encode_tfvars. It is handy to test an expression in terraform console without touching the infrastructure:

consoleterraform console
> length(["203.0.113.0/24", "198.51.100.0/24"])2> upper("web")"WEB"

Value types

TypeExample valueWhat to note
string"dev"text in double quotes
number3, 0.5integers and fractions
booltruetrue or false
list(string)["a", "b"]order matters, indexes start at 0
set(string)toset(["a", "b"])no order and no duplicates, cannot be accessed by index
map(string){ Environment = "prod" }keys are strings
object({ name = string, port = number }){ name = "web", port = 80 }each attribute has its own type

The special value null means “not set”. Terraform treats it as if the argument were absent: it uses the default value, or reports an error if the argument is required. This is handy in conditions: var.enabled ? "web" : null.

Section sources

the section is written from these pages

Providers and the lock file

A provider is a plugin that Terraform uses to work with the API of a single platform: AWS, Cloudflare, Kubernetes, GitHub. Providers are released separately from Terraform and have their own versions, so you constrain the version of each in required_providers, and the dependency lock file records the version that was selected.

Each provider adds its own resource types and data sources: without a provider, Terraform manages nothing. Public providers are published in the Terraform Registry, where a tier badge shows who maintains them: Official means HashiCorp, Partner means the company that owns the API, and Community means the community.

hclterraform.tf
terraform {  required_version = "~> 1.17"   required_providers {    aws = {      source  = "hashicorp/aws"      version = "~> 6.0"    }    cloudflare = {      source  = "cloudflare/cloudflare"      version = "~> 5.0"    }  }}

The key (aws) is the provider’s local name in the module, and source is its registry address in the form [HOSTNAME/]NAMESPACE/TYPE; the default host is registry.terraform.io. The local name usually matches the type: Terraform finds the provider from the first word of a resource type (aws_instance). Without source, Terraform looks for the provider in the hashicorp namespace.

Version constraints

ConstraintWhat it allows
= 1.2.0 or 1.2.0only this version
>= 1.2.01.2.0 and newer
>= 1.2.0, < 2.0.0from 1.2.0 up to, but not including, 2.0.0
~> 6.0any 6.x: 6.1 and 6.10 match, 7.0 does not
~> 6.0.4patch releases only: 6.0.5 and 6.0.10 match, 6.1.0 does not
!= 1.2.3anything except this version

In a root module, use ~> so that terraform init does not pick an incompatible major version. In a reusable module, specify only a lower bound with >=: leave the upper bound to the root module, otherwise every module has to be updated at once.

The provider block and alias

The provider block configures a provider: region, API endpoint, default settings. Write it in the root module; child modules inherit the configuration from their parent. Use the alias argument to tell several configurations of the same provider apart:

hclproviders.tf
provider "aws" {  region = "eu-central-1"} # a second configuration of the same providerprovider "aws" {  alias  = "us"  region = "us-east-1"} resource "aws_s3_bucket" "logs" {  provider = aws.us  bucket   = "example-logs"}

A resource without a provider argument uses the configuration without an alias. Provider arguments can refer to variables and locals, but not to attributes that become known only after apply, such as the IP address of a machine that has just been created.

The .terraform.lock.hcl lock file

During terraform init, Terraform selects the newest version of each provider that satisfies the constraints and records it in .terraform.lock.hcl together with package checksums. Later runs of init reuse that version even if a newer one has been released. Commit this file: then the whole team and CI use the same providers, and a version change goes through code review.

hcl.terraform.lock.hcl
provider "registry.terraform.io/hashicorp/aws" {  version     = "6.0.0"  constraints = "~> 6.0"  hashes = [    "h1:...",    "zh:...",  ]}

The lock file does not record module versions: for a registry module, Terraform picks the newest matching version every time, so pin third-party modules exactly.

Upgrading a provider

bashin the configuration directory
# newest versions within the constraintsterraform init -upgrade# what changed in the selected versionsgit diff .terraform.lock.hcl

If your team works on several platforms, record the checksums for all of them in advance. Otherwise init on another OS keeps appending to the file, and when installing from a mirror Terraform cannot verify packages for other platforms:

bashin the configuration directory
terraform providers lock \  -platform=linux_amd64 \  -platform=darwin_arm64 \  -platform=windows_amd64

Provider credentials

Do not put access keys in the provider block: .tf files end up in Git. Most providers read credentials from environment variables or their own configuration files; the provider’s documentation in the registry says which. For more on secrets, see the section “Security: secrets and state”.

Section sources

the section is written from these pages

Resources and data sources

A resource is a block that describes one infrastructure object: a network, a virtual machine, a DNS record. Terraform creates, changes and deletes the object so that it matches the block. A data source is a data block: it only reads an object that already exists.

A resource block has two labels: the resource type from the provider and a name under which Terraform tracks the resource in state. Together they form the address, such as aws_instance.web. You set the arguments, while attributes such as id and private_ip are filled in by the provider after creation. A reference to another resource’s attribute is a dependency: Terraform creates that resource first.

The diagram shows the dependency graph of a configuration with a network, a subnet, a security group, a VM and a DNS record. The data source is read during planning, and the network is created first. The subnet and the security group are created after it, in parallel, the VM waits for both, and the DNS record comes last because it needs the VM’s address.

An arrow points from a resource to the one that refers to it; Terraform creates independent resources in parallel.
hclmain.tf
variable "zone_id" {  type = string} data "aws_ami" "app" {  most_recent = true  owners      = ["self"]  tags = {    Name = "app-server"  }} resource "aws_vpc" "main" {  cidr_block = "10.0.0.0/16"} resource "aws_subnet" "app" {  vpc_id     = aws_vpc.main.id  cidr_block = "10.0.1.0/24"} resource "aws_security_group" "web" {  name   = "web"  vpc_id = aws_vpc.main.id} resource "aws_instance" "web" {  ami                    = data.aws_ami.app.id  instance_type          = "t3.micro"  subnet_id              = aws_subnet.app.id  vpc_security_group_ids = [aws_security_group.web.id]} resource "aws_route53_record" "web" {  zone_id = var.zone_id  name    = "web.example.com"  type    = "A"  ttl     = 300  records = [aws_instance.web.private_ip]}

Explicit dependency: depends_on

If a resource depends on another one but does not refer to its attributes, Terraform cannot see the link. State it explicitly, as a list of addresses with no computed expressions:

hclmain.tf
resource "aws_instance" "app" {  ami           = data.aws_ami.app.id  instance_type = "t3.micro"   # the application on the VM needs S3 access at startup  depends_on = [aws_iam_role_policy.s3_access]}

Multiple instances: count and for_each

The meta-arguments count and for_each create several instances from a single block. Their values must be known before apply: you cannot rely on an ID that the cloud issues only at creation.

Featurecountfor_each
Valuean integera map or a set of strings
Instance addressaws_instance.web[0]aws_instance.web["api"]
Inside the blockcount.indexeach.key and each.value
When to usethe instances are almost identicaleach instance has its own values that cannot be derived from an index
hclmain.tf
resource "aws_instance" "web" {  for_each = toset(["api", "worker"])   ami           = data.aws_ami.app.id  instance_type = "t3.micro"  tags = {    Name = "web-${each.key}"  }}

for_each does not accept a list: wrap it in toset(). To create a resource conditionally, use count = var.enabled ? 1 : 0, and refer to such a resource by index: aws_instance.web[0].

Lifecycle rules

The lifecycle block inside a resource changes how Terraform creates, updates and deletes it. Arbitrary expressions are not allowed in it: Terraform needs the rules before it evaluates expressions.

RuleWhat it does
create_before_destroy = trueon replacement, creates the new object first and then deletes the old one
prevent_destroy = truerejects any plan that would delete the object
ignore_changes = [tags]does not revert changes to these attributes made outside Terraform
replace_triggered_by = [aws_ecs_service.svc.id]recreates the resource when the referenced resource or attribute changes
precondition, postconditionchecks before and after the resource is created, each with its own error message

Data sources

A data block asks the provider for an existing object, such as a VM image, a DNS zone or another team’s network, and creates nothing. Read its attributes as data.aws_ami.app.id. Data is normally read during planning. If the arguments of a data block depend on a resource that changes in the same plan, the read is deferred until apply, and those values are unknown in the plan.

Renaming: the moved block

By default, Terraform treats a new resource address as “delete the old object and create a new one”. This happens when you rename a resource, move it into a module, or switch from count to for_each. A moved block says it is the same object. For a simple rename, from = aws_instance.server and to = aws_instance.web are enough; a switch to for_each is described per instance:

hclmain.tf
# was count, now for_eachmoved {  from = aws_instance.web[0]  to   = aws_instance.web["api"]} moved {  from = aws_instance.web[1]  to   = aws_instance.web["worker"]}

Do not remove a moved block until every copy of the configuration has applied the change: for a module, removing it is a breaking change. To bring an object created by hand under Terraform, use an import block, described in the section “State and backends”.

Section sources

the section is written from these pages

State and backends

State is a file in which Terraform records how the resources in your configuration map to real objects: the address aws_instance.web is the VM i-abcd1234. Terraform uses it to decide what to create, change and delete. In a team, keep state in a remote backend with state locking.

By default, state lives in the working directory in terraform.tfstate, with a copy of the previous version next to it in terraform.tfstate.backup. It is JSON, but do not edit it by hand: the terraform state commands exist for changes. Before each operation, Terraform refreshes state from the real objects.

Remote backend

A local file gets in the way of teamwork: everyone needs a fresh copy, and two people must not run Terraform at the same time. A backend keeps state in a shared place, such as an S3 bucket, and locks it for the duration of operations. While one run holds the lock, another waits or fails immediately.

The lock is a .tflock file next to the state; use_lockfile = true enables it.
hclbackend.tf
terraform {  backend "s3" {    bucket       = "example-terraform-state"    key          = "prod/terraform.tfstate"    region       = "eu-central-1"    encrypt      = true    use_lockfile = true  }}

use_lockfile = true enables locking with a .tflock file next to the state; it is off by default, and locking through DynamoDB is deprecated. Enable bucket versioning so that you can recover state after a mistake. Do not put access keys in the backend block: the backend takes them from environment variables or AWS files.

A backend block cannot refer to variables or locals. Values that differ between environments are passed at initialisation; this is called partial configuration:

hclprod.s3.tfbackend
bucket = "example-terraform-state"key    = "prod/terraform.tfstate"region = "eu-central-1"
bashin the configuration directory
# backend.tf keeps only backend "s3" {}terraform init -backend-config=prod.s3.tfbackend

After you change the backend, run terraform init again: Terraform offers to migrate the state to the new location. Save a copy of terraform.tfstate before the migration.

Locking and force-unlock

Terraform acquires the lock itself before any operation that may write state, and releases it afterwards. To make a second run wait instead of failing at once, add -lock-timeout=5m. If a run is interrupted, for example because the runner crashed or a laptop was closed, the lock may stay behind, and you release it manually using the ID from the error message.

bashin the configuration directory
# the lock ID is in the error messageterraform force-unlock LOCK_ID

The terraform state commands

CommandWhat it does
terraform state listlists the resources in state
terraform state show 'aws_instance.web'shows the attributes of one resource; with -json, as JSON (since 1.16)
terraform state list -id=i-abcd1234finds a resource address by the object’s ID in the cloud
terraform state mv aws_instance.a aws_instance.bbinds the object to a new address without recreating it
terraform state rm 'aws_instance.web'forgets the object: it stays in the cloud, but Terraform no longer manages it

Commands that modify state always write a backup, and the -dry-run flag of state mv and state rm shows what would be affected without changing anything. Prefer moved and removed blocks to these commands: they are visible in code review and go through the normal plan. After state rm, the next plan proposes creating the object again, so remove its resource block too.

Importing existing objects

An object created by hand or by another tool is brought under management with an import block: to is the resource address and id is the object’s ID at the provider. The import runs during terraform apply, and the plan shows in advance what will be imported.

hclimports.tf
import {  to = aws_s3_bucket.logs  id = "example-logs"} resource "aws_s3_bucket" "logs" {  bucket = "example-logs"}

You do not have to write the resource block by hand: terraform plan -generate-config-out=generated.tf generates it from the real object (this flag is experimental). Import each object into only one address, otherwise Terraform behaves unpredictably. The terraform import command does the same directly in state, without a plan.

Workspaces

A workspace is another state for the same configuration in the same backend: terraform workspace new staging creates one, terraform workspace select switches, and terraform workspace list shows them all. It suits a temporary copy of the infrastructure, for example to test a branch. Dev, staging and production usually need different permissions and credentials, while workspaces share a backend. So keep environments in separate directories, each with its own backend, and move shared code into modules. From the repository root, point to such a directory with a global flag: terraform -chdir=environments/prod plan.

Terraform notices changes made by hand in the cloud console at the next refresh, and the plan proposes bringing the object back to the configuration. This mismatch is called drift. To accept the changes into state without changing anything in the cloud, use -refresh-only mode, described in the section “Workflow: init, plan, apply”.

Section sources

the section is written from these pages

Modules

A module is a directory of .tf files that Terraform manages together. The directory where you run Terraform is the root module: it calls child modules with module blocks, passes them input variables and receives their output values.

Move a repeating set of resources into a module: an identical network for dev and production, a standard service. A module that merely wraps a single resource is not needed: if you cannot find a better name for the module than the name of the resource inside, use the resource directly.

A module’s resources are not visible from outside, only its output values. So modules exchange data through the root module: it takes the output of one module and passes it to the input of another.

In code, this is the line subnet_id = module.network.subnet_id in the module "app" block.
hclenvironments/prod/main.tf
module "network" {  source = "./modules/network"  cidr   = "10.0.0.0/16"} module "app" {  source    = "./modules/app"  subnet_id = module.network.subnet_id  env       = "prod"}
hclmodules/network/outputs.tf
output "subnet_id" {  description = "ID of the application subnet"  value       = aws_subnet.app.id}
hclmodules/app/variables.tf
variable "subnet_id" {  type        = string  description = "Subnet for the web server"}

Where to get a module from

SourceExample source
Local directory: a path starting with ./ or ../"./modules/network"
Terraform Registry"terraform-aws-modules/vpc/aws"
GitHub repository"github.com/example/terraform-modules"
Any Git repository, with a tag in ref"git::https://example.com/vpc.git?ref=v1.2.0"
Subdirectory of a repository, after //"git::https://example.com/infra.git//modules/vpc?ref=v1.2.0"

source and version are evaluated during terraform init, so only literals, locals and variables with const = true are allowed in them. After changing source or version, run terraform init again; to upgrade an already installed module, run terraform init -upgrade.

Module version

hclmain.tf
module "vpc" {  source  = "terraform-aws-modules/vpc/aws"  # patch releases of the 6.7 series only  version = "~> 6.7.0"}

The version argument works only for registry modules; for a Git module, set the version with a tag or commit hash in ?ref=. The lock file does not record module versions, so pin a third-party module exactly or to a minor version, as in the example.

Module structure

textdirectory tree
modules/network/├── README.md├── main.tf├── variables.tf└── outputs.tf

main.tf holds the resources, variables.tf the inputs, outputs.tf the outputs, and README.md explains what the module does and how to call it. Give every variable and every output a description. Put nested modules in modules/ and usage examples in examples/.

Providers in modules

Write the provider block only in the root module: a child module receives the provider configuration from its parent, but declares required_providers with the source and version itself. Pass a configuration with an alias explicitly, using the providers argument:

hclmain.tf
module "app_us" {  source    = "./modules/app"  subnet_id = module.network.subnet_id  env       = "prod"   # the module’s aws provider gets the aws.us configuration  providers = {    aws = aws.us  }}

Multiple instances of a module

count and for_each also work in a module block. Instances get addresses such as module.bucket[0] or module.bucket["assets"]:

hclmain.tf
module "bucket" {  for_each = toset(["assets", "media"])  source   = "./modules/bucket"  name     = "example-${each.key}"}

Module tests

Module checks are written in *.tftest.hcl files, usually in a tests directory, and run with terraform test. By default, a run block performs a real apply and destroys what it created after the test; with command = plan, the test checks the logic without creating anything.

hcltests/bucket.tftest.hcl
variables {  name = "example-test"} run "bucket_name" {  command = plan   assert {    condition     = aws_s3_bucket.this.bucket == var.name    error_message = "bucket name does not match var.name"  }}

Section sources

the section is written from these pages

Workflow: init, plan, apply

The Terraform workflow is a loop: write the configuration, run terraform init, run terraform plan, read the plan, run terraform apply. Reading the plan is the key step: it shows what will be created, changed and destroyed before it happens.

init prepares the directory, plan compares the configuration with the state and the real objects and proposes actions, and apply carries them out and records the result in the state. If the plan destroys something you did not expect, stop and fix the code.

In a pipeline, plan and apply are separate steps, and a person reads the plan between them.
  1. Write or change the .tf files and format them: terraform fmt.
  2. terraform init downloads providers and modules and configures the backend. It is safe to run repeatedly, and you must run it again after changing providers, modules or the backend.
  3. terraform plan -out=tfplan produces a plan and saves it to a file.
  4. Read the plan: the summary of creations, changes and deletions, and every # forces replacement marker.
  5. terraform apply tfplan carries out exactly that plan, without asking for confirmation.
  6. Terraform records the result in the state; commit the configuration changes.

How to read a plan

SymbolAction
+create an object
~change an object in place
-/+destroy and recreate (replacement)
-destroy an object
textexample output
  # aws_instance.web must be replaced-/+ resource "aws_instance" "web" {      ~ ami = "ami-a1b2c3d4" -> "ami-e5f6a7b8" # forces replacement        ...    } Plan: 1 to add, 0 to change, 1 to destroy.

The Plan: line is the summary: how many objects will be created, changed and destroyed; a replacement counts as both a creation and a destruction. The # forces replacement marker shows an argument the API cannot change in place, so the object is recreated. If the summary includes deletions, find each one in the plan and make sure it is expected.

Saved plans in a pipeline

terraform apply without a plan file creates a new plan and asks for confirmation. With a plan file it runs the saved plan immediately: passing the file is the confirmation, and planning flags are not accepted. This is how CI works: the plan on one step, a review, then apply tfplan on another. The -auto-approve flag removes the prompt from a plain apply too. Nobody reads the plan then, so use it only if nothing changes the infrastructure behind Terraform’s back.

bashin a CI pipeline
terraform init -input=falseterraform plan -input=false -out=tfplan# the plan as text, for reviewterraform show -no-color tfplan > plan.txtterraform apply -input=false tfplan

plan and apply flags

FlagWhat it does
-var-file=prod.tfvarsreads variable values from a file
-var='environment=prod'sets one variable; can be repeated
-out=tfplansaves the plan to a file (plan only)
-replace=aws_instance.webrecreates the resource even if it has not changed
-target=aws_instance.webplans only this resource and what it depends on; for emergencies only
-refresh-onlyonly updates the state and output values from the real objects
-refresh=falsedoes not query the cloud before planning: faster, but external changes are not visible
-minimal-refreshqueries the cloud only for resources the plan changes (since 1.17)
-destroyplans the destruction of all objects in the configuration
-lock-timeout=5mwaits for the state lock instead of failing immediately
-parallelism=5how many operations to run at once; 10 by default
-detailed-exitcodeexit code 2 if there are changes (plan only)

Drift and -refresh-only

Drift is a divergence between the real objects and the configuration, for example after a manual edit in the cloud console. A normal plan proposes returning the object to the configuration. To see only the external changes first, run terraform plan -refresh-only; terraform apply -refresh-only records them in the state without changing anything in the cloud. Then move the change you want into the code, or the next normal apply will revert it.

Destroying: destroy

terraform destroy removes everything the configuration manages and is equivalent to terraform apply -destroy. First see what will be destroyed: terraform plan -destroy. To remove a single resource, delete its block and the references to it from the configuration (terraform validate finds any that remain) and run terraform apply.

Working in a team

Every change is a branch and a pull request. Attach a plan to the pull request, produced by the author or automatically by CI, and reviewers check that the plan does exactly what was intended. After the merge, create the plan again from the main branch and the fresh state, since it may differ, and apply only that one.

Before committing, run terraform fmt -check -recursive and terraform validate. The first returns a non-zero exit code if files are not formatted, which is handy for CI; terraform fmt -diff shows exactly what would change. How to set up such a pipeline and where to keep its secrets is covered in the CI/CD reference, in the sections “Secrets, variables and OIDC” and “Environments and deployment”.

Section sources

the section is written from these pages

Security: secrets and state

The main threats are secrets in the state, in a saved plan and in Git, and access keys in code. Protect the state as a secret, do not write passwords in .tf files, and pass them in a way that stops Terraform storing them: through ephemeral values and write-only arguments.

The state and the plan file contain resource attributes, and these can include initial database passwords, tokens and private keys. In local use, the state is an ordinary text file on disk.

  • Store the state remotely and enable storage encryption: for the s3 backend this is encrypt = true; HCP Terraform encrypts the state itself.
  • Limit who can read the state storage and enable an access log for it.
  • Pass provider credentials through the providers’ environment variables, and in CI use short-lived credentials instead of permanent keys.
  • Do not insert unvalidated values into local-exec and remote-exec provisioner commands: Terraform does not escape them.

sensitive hides a value but does not remove it

sensitive = true on a variable or output value hides the value in plan and apply output, where you see (sensitive value). Expressions that use such a variable become sensitive too. But the value stays in the state and the plan file, and terraform output -json and terraform output -raw print it in plain text.

textexample output
  + resource "aws_db_instance" "main" {      + password = (sensitive value)      + username = "admin"    }

Ephemeral values and write-only arguments

An ephemeral value is available during an operation but does not reach the state or the plan file. Ephemeral values come from a variable or a child module output with ephemeral = true (since 1.10) and from the ephemeral block, a temporary resource such as a random password. The third way is a resource’s write-only argument (since 1.11): the provider uses the value and immediately forgets it.

Write-only arguments usually end in _wo, and the paired _wo_version argument is stored in the state and tells Terraform when to send a new value. Terraform does not compare write-only argument values between runs, so a changed value shows up in the plan only through _wo_version. The provider documentation says whether a resource has such arguments.

hclwrong
variable "db_password" {  type    = string  default = "change-me"} resource "aws_db_instance" "main" {  engine   = "postgres"  username = "admin"  password = var.db_password}
hclcorrect
# the password exists only during the operationephemeral "random_password" "db" {  length = 20} resource "aws_db_instance" "main" {  instance_class      = "db.t3.micro"  allocated_storage   = 20  engine              = "postgres"  username            = "admin"  skip_final_snapshot = true  password_wo         = ephemeral.random_password.db.result  password_wo_version = 1}

In the first example the password sits in Git and in the state. In the second, Terraform stores it nowhere, so put the password in a secrets manager: the AWS provider has the write-only argument secret_string_wo on aws_secretsmanager_secret_version. A complete example (generate, write to a secret, pass to the database) is in the write-only arguments documentation. To rotate the password, increase password_wo_version.

Provider and backend credentials

Do not write access keys in provider and backend blocks. Terraform saves values passed through -backend-config in plain text in the .terraform directory and in plan files. Pass credentials through the provider’s environment variables, and in CI obtain temporary keys through OIDC, as described in the CI/CD reference, in the section “Secrets, variables and OIDC”.

What not to commit

text.gitignore
# state and its backups*.tfstate*.tfstate.*.terraform.tfstate.lock.info# providers, modules and backend settings.terraform/# saved planstfplan# variable values with secretssecret.tfvars

Commit all .tf files, .terraform.lock.hcl, .gitignore and README.md. Pin versions: providers in required_providers, modules in version, Terraform itself in required_version. Then a provider or module update goes through code review instead of happening by itself on the next init.

State encryption in OpenTofu

OpenTofu can encrypt the state and plan files itself, using an encryption block inside terraform or the TF_ENCRYPTION environment variable. Without the key such a state cannot be read, so before enabling it make backups of the key and of the unencrypted state.

Section sources

the section is written from these pages

Common errors and troubleshooting

Start with terraform validate: it finds syntax and reference errors without contacting the cloud. Then look at terraform plan, and if the cause is still not visible, enable detailed logging with the TF_LOG=DEBUG variable.

Order of checks

  1. terraform validate checks syntax, argument names and references. It needs a directory after terraform init; if you cannot reach the backend, terraform init -backend=false is enough. After fixing errors, run validate again: it may show the next ones only then.
  2. terraform plan shows what Terraform intends to do and why: which resources are replaced and because of which argument.
  3. The log: TF_LOG with the level TRACE, DEBUG, INFO, WARN or ERROR, and the file in TF_LOG_PATH. For only the core or only the providers, use TF_LOG_CORE and TF_LOG_PROVIDER.
bashin the configuration directory
# the detailed log is appended to a fileTF_LOG=DEBUG TF_LOG_PATH=terraform.log terraform plan# provider messages onlyTF_LOG_PROVIDER=TRACE terraform apply

Error: Cycle: aws_security_group.sg_ping, aws_security_group.sg_8080

Cause: resources refer to each other in a loop, and Terraform cannot decide which to create first. A typical case is two security groups that allow traffic from each other in nested rules.

bashin the configuration directory
terraform validate

Break the loop: remove the nested rules from the groups and describe them as separate aws_security_group_rule resources. Then both groups are created first, and the rules between them after.

hclmain.tf
resource "aws_security_group_rule" "ping_from_web" {  type                     = "ingress"  from_port                = -1  to_port                  = -1  protocol                 = "icmp"  security_group_id        = aws_security_group.sg_ping.id  source_security_group_id = aws_security_group.sg_8080.id}

Error: Missing resource instance key

Cause: the resource has count or for_each, but its attribute is used without an index, as in aws_instance.web.id. Specify the instance (aws_instance.web["api"].id) or collect the attribute of all instances:

hcloutputs.tf
output "instance_ids" {  # for_each: all instances of the resource  value = [for instance in aws_instance.web : instance.id]}

Error: Invalid "each" attribute

Cause: the each object has only each.key and each.value, and no each.id or similar. If for_each is given a map of IDs, the ID you need is each.value; if it is a map of objects, it is each.value.id.

hclmain.tf
locals {  security_groups = {    ping = aws_security_group.sg_ping.id    web  = aws_security_group.sg_8080.id  }} resource "aws_instance" "web" {  for_each               = local.security_groups  ami                    = data.aws_ami.app.id  instance_type          = "t3.micro"  vpc_security_group_ids = [each.value]}

State is locked by another run

Cause: another plan or apply holds the state lock, or a previous run was interrupted and did not release it. By default Terraform does not wait for the lock and stops immediately.

  • Find out who is working with this state right now, a colleague or a CI job, and wait for them to finish. To wait automatically, add -lock-timeout=5m.
  • If the process has definitely finished, release the lock with terraform force-unlock and the ID from the error message. This command does not change the infrastructure.
bashin the configuration directory
terraform plan -lock-timeout=5m# only if the other run has definitely finishedterraform force-unlock LOCK_ID

Error: Failed to install provider

Cause: the downloaded provider package matched none of the hashes in .terraform.lock.hcl. This happens if the provider is installed from a mirror or on a platform that has no hashes in the file.

bashin the configuration directory
# official hashes for all of the team’s platformsterraform providers lock \  -platform=linux_amd64 \  -platform=darwin_arm64

Locked version does not satisfy the constraints

Cause: version in required_providers was changed, but .terraform.lock.hcl holds the previous version, which does not fit the new constraint. A plain terraform init does not change the choice from the lock file.

bashin the configuration directory
terraform init -upgradegit add .terraform.lock.hcl

Provider not found or no matching version

Cause: a typo in source, a provider that is not in the hashicorp namespace but has no source specified, or no released version matches the version constraint. See which providers the configuration expects and from where, and check the address against the registry:

bashin the configuration directory
terraform providers

# forces replacement in the plan

Cause: an argument changed that the API cannot change in place, so Terraform will destroy the object and create a new one. The other common case is a changed resource address: a new name, a move into a module, a switch to for_each.

  • If you do not need to change the argument, restore the previous value or add it to ignore_changes in the lifecycle block.
  • If you need the new object without downtime, enable create_before_destroy = true.
  • If only the address changed, add a moved block with the old and new address.

The plan reverts manual changes

Cause: someone changed the object by hand in the cloud console, and it diverged from the configuration (drift). A normal apply returns the object to what the code says.

bashin the configuration directory
# only the changes made outside Terraformterraform plan -refresh-only

Move the change you want into the .tf files, and the plan becomes empty. Undo the unwanted one with a normal terraform apply.

Section sources

the section is written from these pages

Versions and what’s new

This reference describes Terraform 1.17. The latest release is 1.17.1, from 28 October 2026. A new minor branch comes out every few months. Under HashiCorp’s compatibility promises, a configuration written for 1.0 keeps working in all 1.x releases without changes.

BranchStatusFirst releaseLatest release
1.17current, described here1.17.0 — 21 October 20261.17.1 — 28 October 2026
1.16receives patches1.16.0 — 26 August 20261.16.7 — 22 October 2026
1.15no patches since August 20261.15.0 — 29 April 20261.15.9 — 19 August 2026

HashiCorp does not publish branch support periods in its documentation. The releases show that the 1.15 branch received no patches after 1.16.0 came out, and that 1.16.7 was released the day after 1.17.0 with the same security fix. Move to the current branch.

What changed in 1.17

  • Providers and the lock file: required_providers can now use variables and locals. The variable is declared with const = true, so its value is known at terraform init.
  • Workflow: init, plan, apply: the -minimal-refresh flag queries the cloud only for resources the plan changes. External changes to other resources are not visible then.
  • Workflow: init, plan, apply: Terraform Policy is no longer experimental. The -policies flag of plan, apply and query works in regular builds, without -allow-experimental-features.
  • Installation and first run: terraform version -json prints a new format_version field. Scripts that parse this JSON must skip unknown fields.
  • HCL: blocks, variables and expressions: the log and pow functions return an error, instead of crashing, when the result is infinity or not a number.
  • Modules: terraform test gained mock_provider for ephemeral resources.
  • Workflow: init, plan, apply: if terraform fmt could not write a file, the original contents are preserved (since 1.17.1).

Deprecated and removed

  • State locking in the s3 backend through DynamoDB (dynamodb_table) is deprecated and will be removed in a future minor version; enable use_lockfile = true.
  • The version argument in the provider block is deprecated; set the version in required_providers.
  • The terraform refresh command is deprecated; use terraform apply -refresh-only, which shows the changes first.
  • The -provider flag of terraform import is deprecated.
  • The old splat form var.list.*.id is supported for compatibility, but in new code write var.list[*].id.
  • OpenTofu 1.13 removed the winrm connection type for provisioners; 1.13 is the last OpenTofu branch with official builds for 32-bit processors.

Security updates

IdentifierWhat is affectedFixed in
CVE-2026-111943trust in certificates issued through compromised eMudhra intermediate authorities; Terraform is built with Go 1.26.101.17.0, 1.16.7
CVE-2026-78669HTTP/2 resource exhaustion; the attack requires a compromised provider or module registry1.16.6
CVE-2026-14978because of Unicode normalisation, files excluded in .terraformignore could be uploaded to HCP Terraform and Terraform Enterprise1.15.9

How to move to a new branch

  1. Read the NOTES and UPGRADE NOTES sections of the CHANGELOG for the new branch and all those in between.
  2. Update required_version and install the new version on all machines and in CI at once: a state written by a newer version may not be readable by an older one.
  3. Run terraform init and terraform plan: if you did not change the configuration, the plan should be empty.
  4. Run terraform fmt -recursive: formatting rules can change between versions.

OpenTofu

OpenTofu is released separately: the current branch is 1.13, the latest release is 1.13.9, from 5 November 2026, and the branch is supported until August 2027. Version 1.13.2 fixed trust in compromised intermediate certificates and excessive CPU load during tofu init with a spoofed HTTP/2 server.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Terraform” topic
13 sections
Another reference · DevOps & cloud

Docker

Verified 31 Oct
All references · 61