← Full reference

terraform

Infrastructure as code — init/plan/apply/destroy, providers, resources, variables, outputs and state

Terraform describes infrastructure in .tf files written in HCL and brings the real world in line with the description: it creates, changes and deletes resources through providers (clouds, DNS, Kubernetes, local files). Terraform remembers what has already been created in a state file — terraform.tfstate.

The sandbox has no internet access. The hashicorp/local provider (version 2.5.1) is preloaded into a local mirror, so terraform init works with it offline. The built-in terraform_data resource needs no provider at all. Other providers (random, aws, etc.) can't be downloaded.

Syntax

terraform [-chdir=directory] <command> [options]

Terraform reads all .tf files in the current directory as one configuration; the order of files and blocks doesn't matter.

Commands

The main cycle

CommandWhat it does
initdownload providers and modules, create .terraform/ and .terraform.lock.hcl; -upgrade — update versions
validatecheck the configuration (needs init)
fmtfix formatting; -check — only check (code 3 if something needs fixing), -diff, -recursive
planshow what will be created (+), changed (~), replaced (-/+), deleted (-)
plan -out=tf.plansave the plan; apply tf.plan applies exactly that, with no questions
applyshow the plan and apply it after you answer yes; -auto-approve — without asking
destroydelete everything the configuration manages (plan -destroy — preview it first)

plan / apply flags

FlagWhat it does
-var 'name=value'a variable value
-var-file=file.tfvarsvalues from a file
-target=addresswork with just one resource (for exceptional cases)
-replace=addressrecreate a resource even if it hasn't changed
-refresh-onlyonly update state from the real world, changing nothing
-no-colorno colors — for logs and scripts

State and output

CommandWhat it does
output / output nameall outputs / one; -raw — without quotes, -json — as JSON
showthe current state (or a saved plan: show tf.plan)
state listresources in state
state show addressattributes of one resource
state rm addressforget a resource without deleting it in reality
state mv old newrename a resource in state (after renaming it in code)
import address idbring an existing object under management
consoleevaluate expressions interactively: echo 'upper("x")' | terraform console
providerswhich providers the configuration needs
workspace list/new/selectseveral independent states for one configuration
graphthe dependency graph in DOT format

HCL blocks

BlockWhat it's for
terraform { required_providers { … } }which providers and versions are needed; also required_version and backend (where to store state)
provider "name" { … }provider settings (region, tokens)
resource "type" "name" { … }an object Terraform manages; address — type.name
data "type" "name" { … }read an existing object without managing it; address — data.type.name
variable "name" { … }an input parameter: type, default, description, sensitive, validation
output "name" { value = … }a value printed after apply and available via terraform output
locals { name = … }computed values inside the configuration: local.name
module "name" { source = "./path" }include a set of .tf files as a module

Resource meta-arguments

ArgumentWhat it does
count = 3several instances; index — count.index, address — type.name[0]
for_each = map or setan instance per element; each.key, each.value, address — type.name["key"]
depends_on = [resource]an explicit dependency when it isn't visible from references
lifecycle { … }create_before_destroy, prevent_destroy, ignore_changes

Expressions

SyntaxMeaning
var.name, local.namea variable, a local value
type.name.attributean attribute of another resource — also creates a dependency
"${var.env}-app"string interpolation
path.modulethe current configuration's directory
[for x in list : upper(x)]list transformation
condition ? a : bchoosing a value
upper(), lower(), join(), split(), format(), length(), contains(), lookup(), file(), templatefile()built-in functions

Variable types: string, number, bool, list(string), map(string), set(string), object({…}).

Where variable values come from (weakest to strongest): default → environment variables TF_VAR_name → terraform.tfvars → *.auto.tfvars → -var and -var-file on the command line.

Examples

main.tf with the local provider:

terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }
  }
}

variable "greeting" {
  type        = string
  default     = "hello"
  description = "Text for the file"
}

variable "files" {
  type    = map(string)
  default = { a = "alpha", b = "beta" }
}

resource "local_file" "note" {
  filename        = "${path.module}/out/note.txt"
  content         = "${var.greeting}\n"
  file_permission = "0644"
}

resource "local_file" "many" {
  for_each = var.files
  filename = "${path.module}/out/${each.key}.txt"
  content  = upper(each.value)
}

output "note_path" {
  value = local_file.note.filename
}
# prepare the directory: the provider comes from the local mirror
terraform init

# check and format
terraform validate
terraform fmt

# view the plan, save it and apply exactly that
terraform plan -out=tf.plan
terraform apply tf.plan

# what Terraform currently knows about resources
terraform state list
terraform state show 'local_file.many["a"]'
terraform output -raw note_path

# change a variable — the plan shows the file being replaced
terraform plan -var 'greeting=hi'

# values from a file
echo 'greeting = "from file"' > terraform.tfvars
terraform apply -auto-approve

# evaluate an expression
echo 'upper(var.greeting)' | terraform console

# remove everything that was created
terraform destroy -auto-approve

Pitfalls

  • Nothing works without init. plan/apply/validate in a fresh directory fail with an error about the lock file or uninstalled providers. After editing required_providers or modules, run init again.
  • State is Terraform's source of truth. If you delete a resource by hand, plan will offer to create it again. If you delete terraform.tfstate, Terraform "forgets" everything it created and tries to create it again.
  • Don't edit state by hand. There's state mv for renames and state rm for "forget".
  • Many changes mean replacement. For local_file, changing content or filename gives -/+ must be replaced: the old object is deleted. Look for forces replacement in the plan.
  • sensitive = true hides the value only in plan/apply output. terraform output name shows it, and in terraform.tfstate it's stored in plain text.
  • terraform.tfvars beats TF_VAR_…. An environment variable won't take effect if the same name is set in tfvars.
  • count addresses by index. Removing an element from the middle of a list shifts the indexes and recreates "other" resources. For named sets use for_each.
  • apply without -auto-approve waits for a yes. Any other answer cancels, and in a script without input apply fails with error asking for approval. If there are no changes, there's no question.
  • Don't commit .terraform/ and terraform.tfstate: the first is downloaded by init, the second may contain secrets. Do commit .terraform.lock.hcl.

See also

ansible · kubectl · jq · gitlab-ci