Skip to content

Terraform and OpenTofu

Terraform 1.17 / OpenTofu 1.13

State is Terraform’s record of which real object each resource address owns; your code is the desired state; a plan is the diff between the two after refreshing state from the cloud. Change any of the three outside the workflow — a console edit, two people applying at once, a renamed resource — and the plan stops meaning what you think it means. Most incidents are state problems, not HCL problems. Everything below applies to both terraform and tofu unless the last section says otherwise.

BlockPurpose
terraform { required_providers }Pin provider source and version
provider "aws" { … }Configure a provider
resource "TYPE" "NAME"An object Terraform manages
data "TYPE" "NAME"Read an object it does not manage

A resource’s address is TYPE.NAME (aws_s3_bucket.logs); state maps that address to a real ID. Data sources are read at plan time and never created or destroyed. terraform init downloads providers and records exact versions and checksums in .terraform.lock.hcl.

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" { region = "eu-west-1" }
resource "aws_s3_bucket" "logs" {
bucket = "acme-checkout-logs"
}

Tip: Commit .terraform.lock.hcl. Without it, two machines can resolve different provider versions from the same ~> constraint.

BlockRoleReference
variableInput to a modulevar.env
localsNamed expressionlocal.prefix
outputValue a module exposesmodule.x.out

Set variables with -var, a *.tfvars file, or TF_VAR_name environment variables. Give each one a type and, where a bad value would be expensive, a validation block.

variable "env" {
type = string
validation {
condition = contains(
["dev", "prod"], var.env)
error_message = "env must be dev or prod."
}
}
locals { prefix = "checkout-${var.env}" }
output "bucket" { value = aws_s3_bucket.logs.id }
CommandDoes
initProviders, modules, backend
fmt -check / validateStyle and static checks
plan -out=tfplanDiff, saved to a file
apply tfplanApply exactly that diff
plan -detailed-exitcodeExit 2 when changes exist

In CI, plan on the pull request, review the plan output, then apply the saved plan file after merge — never a fresh, unreviewed plan. A scheduled plan -detailed-exitcode doubles as drift detection: exit code 2 means reality no longer matches the code.

Terminal window
terraform init -input=false
terraform fmt -check
terraform validate
terraform plan -input=false -out=tfplan
terraform apply -input=false tfplan

Warning: A saved plan file contains variable values and resource attributes, including sensitive ones. Treat it as a secret and keep it out of public CI artifacts.

ConcernAnswer
Where state livesA backend: s3, gcs, azurerm, …
Concurrent appliesLocking; S3 uses use_lockfile
DynamoDB lockingDeprecated in Terraform’s S3 backend
Many environmentsSeparate state per env
terraform.workspaceSame code, several states

Local state on a laptop cannot be shared or locked, so every team uses a remote backend. The S3 backend locks with a lock object next to the state when use_lockfile = true (it defaults to false). Workspaces reuse one backend and one set of credentials, which is why both tools say they are unfit for isolating environments that need separate access.

terraform {
backend "s3" {
bucket = "acme-tf-state"
key = "checkout/prod.tfstate"
region = "eu-west-1"
use_lockfile = true
}
}

Gotcha: In Terraform, a backend block cannot reference variables or locals — use -backend-config at init. OpenTofu allows variables and locals there, so code written for it may not run on Terraform.

ToolUse when
count = nN near-identical copies
for_each = map/setCopies keyed by a stable name
module "x" { source }Reusable group of resources
dynamic blockRepeated nested blocks

count instances are addressed by index ([0]), for_each instances by key (["eu"]). The keys must be known at plan time, so they cannot come from an attribute the cloud assigns on create. A module is any directory of .tf files; call it with inputs, read its outputs.

variable "buckets" {
type = map(string) # name => region tag
}
resource "aws_s3_bucket" "this" {
for_each = var.buckets
bucket = "acme-${each.key}"
tags = { region = each.value }
}

Gotcha: Removing an item from the middle of a count list shifts every later index, so the plan replaces resources you did not touch. Use for_each for anything that has a natural name.

BlockEffect on next apply
import { to, id }Adopt an existing object
moved { from, to }Rename an address, keep the object
removed { from }Forget it; destroy = false keeps it

These blocks make refactoring reviewable: they appear in the plan, not in someone’s shell history. plan -generate-config-out=FILE writes starter HCL for imported resources. Delete moved blocks only once every state that used the old address has applied them.

import {
to = aws_s3_bucket.logs
id = "acme-checkout-logs"
}
moved {
from = aws_s3_bucket.this["eu"]
to = aws_s3_bucket.eu
}
removed {
from = aws_s3_bucket.legacy
lifecycle { destroy = false }
}
MarkerWritten to state and plan?
sensitive = trueYes, only redacted in output
ephemeral = true (variable, output)No
ephemeral "TYPE" "NAME" blockNo
write-only argument (*_wo)No

sensitive only redacts CLI output; the value is still written in plaintext to state and plan files. Ephemeral values exist for one run and may only flow into ephemeral contexts: provider blocks, other ephemeral values, and write-only arguments. Bump the *_wo_version argument to make the provider send a new value.

ephemeral "random_password" "db" {
length = 24
}
resource "aws_db_instance" "main" {
# ... engine, size, username
password_wo = (
ephemeral.random_password.db.result
)
password_wo_version = 1
}

Warning: Anyone who can read the state bucket can read every sensitive value in it. Lock down the bucket as tightly as the secrets themselves.

FeatureTerraform 1.17OpenTofu 1.13
State and plan encryptionNo (protect the backend)Built in
Variables in backendNoYes
lifecycle { enabled }NoYes
StacksYes, in HCP TerraformNo
Native policy (-policies)YesNo
.tofu override filesNoYes

Both share HCL, ephemeral values, write-only arguments and the refactoring blocks above. OpenTofu pulls providers from registry.opentofu.org, Terraform from registry.terraform.io. A .tofu file beats a .tf file of the same name, so one repo can carry OpenTofu-only code.

terraform {
encryption { # OpenTofu only
key_provider "aws_kms" "main" {
kms_key_id = var.state_key_id
region = "eu-west-1"
key_spec = "AES_256"
}
method "aes_gcm" "main" {
keys = key_provider.aws_kms.main
}
state { method = method.aes_gcm.main }
}
}

Gotcha: Once state encryption is on, OpenTofu cannot read the state without the key. Back up the unencrypted state and the key material before you enable it.