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
| Command | What it does |
|---|---|
init | download providers and modules, create .terraform/ and .terraform.lock.hcl; -upgrade — update versions |
validate | check the configuration (needs init) |
fmt | fix formatting; -check — only check (code 3 if something needs fixing), -diff, -recursive |
plan | show what will be created (+), changed (~), replaced (-/+), deleted (-) |
plan -out=tf.plan | save the plan; apply tf.plan applies exactly that, with no questions |
apply | show the plan and apply it after you answer yes; -auto-approve — without asking |
destroy | delete everything the configuration manages (plan -destroy — preview it first) |
plan / apply flags
| Flag | What it does |
|---|---|
-var 'name=value' | a variable value |
-var-file=file.tfvars | values from a file |
-target=address | work with just one resource (for exceptional cases) |
-replace=address | recreate a resource even if it hasn't changed |
-refresh-only | only update state from the real world, changing nothing |
-no-color | no colors — for logs and scripts |
State and output
| Command | What it does |
|---|---|
output / output name | all outputs / one; -raw — without quotes, -json — as JSON |
show | the current state (or a saved plan: show tf.plan) |
state list | resources in state |
state show address | attributes of one resource |
state rm address | forget a resource without deleting it in reality |
state mv old new | rename a resource in state (after renaming it in code) |
import address id | bring an existing object under management |
console | evaluate expressions interactively: echo 'upper("x")' | terraform console |
providers | which providers the configuration needs |
workspace list/new/select | several independent states for one configuration |
graph | the dependency graph in DOT format |
HCL blocks
| Block | What 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
| Argument | What it does |
|---|---|
count = 3 | several instances; index — count.index, address — type.name[0] |
for_each = map or set | an 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
| Syntax | Meaning |
|---|---|
var.name, local.name | a variable, a local value |
type.name.attribute | an attribute of another resource — also creates a dependency |
"${var.env}-app" | string interpolation |
path.module | the current configuration's directory |
[for x in list : upper(x)] | list transformation |
condition ? a : b | choosing 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/validatein a fresh directory fail with an error about the lock file or uninstalled providers. After editingrequired_providersor modules, runinitagain. - State is Terraform's source of truth. If you delete a resource by hand,
planwill offer to create it again. If you deleteterraform.tfstate, Terraform "forgets" everything it created and tries to create it again. - Don't edit state by hand. There's
state mvfor renames andstate rmfor "forget". - Many changes mean replacement. For
local_file, changingcontentorfilenamegives-/+ must be replaced: the old object is deleted. Look forforces replacementin the plan. sensitive = truehides the value only inplan/applyoutput.terraform output nameshows it, and interraform.tfstateit's stored in plain text.terraform.tfvarsbeatsTF_VAR_…. An environment variable won't take effect if the same name is set in tfvars.countaddresses by index. Removing an element from the middle of a list shifts the indexes and recreates "other" resources. For named sets usefor_each.applywithout-auto-approvewaits for ayes. Any other answer cancels, and in a script without inputapplyfails witherror asking for approval. If there are no changes, there's no question.- Don't commit
.terraform/andterraform.tfstate: the first is downloaded byinit, the second may contain secrets. Do commit.terraform.lock.hcl.