HCL (HashiCorp Configuration Language) is a toolkit for building configuration languages. The Terraform language is one language built on it. Terragrunt, Packer, Nomad, Vault policies and Terraform's own test files (.tftest.hcl) are others. They share syntax but not vocabulary, so locals means the same thing everywhere, while a resource block only exists in Terraform.
This section covers the Terraform language. Everything here applies to OpenTofu too unless a page says otherwise.
Pages in this section¶
| Page | What it covers |
|---|---|
| Types and values | Primitive, collection and structural types, null, any, optional(), type conversion |
| Variables, outputs and locals | Module inputs and outputs, validation, sensitive, ephemeral, deprecated, precedence |
| Expressions | References, operators, string templates, heredocs, splat, directives |
| Conditionals and the ternary operator | cond ? a : b in depth, conditional resources, conditional blocks and arguments |
Loops: for, count, for_each, dynamic |
Every way to iterate, and the patterns that make them readable |
| Functions | Every built-in function, grouped, with examples and gotchas |
| Meta-arguments and lifecycle | count, for_each, depends_on, provider, lifecycle, conditions |
| Dependencies | The dependency graph, implicit dependencies, and why to avoid depends_on |
Syntax building blocks¶
The language has two constructs: arguments (also called attributes) and blocks.
# A block: type, zero or more labels, then a body in braces.
resource "azurerm_resource_group" "app" { # type = resource, labels = type + name
name = "rg-app-dev-cc" # argument: identifier = expression
location = "canadacentral"
tags = { # an argument whose value is a map
env = "dev"
}
lifecycle { # a nested block (no "=")
prevent_destroy = true
}
}
The difference between tags = { ... } and lifecycle { ... } matters. The first is an argument holding a map value, so you can build it with expressions. The second is a block, so you can't assign it from a variable. To generate blocks you need dynamic.
Identifiers¶
Identifiers (argument names, block types, resource names, variable names) may contain letters, digits, underscores and hyphens, and must not start with a digit. Hyphens are legal but awkward: local.my-value parses as local.my - value in some contexts, so use snake_case for everything you name. See hygiene.
Comments¶
# Single line (preferred, and what terraform fmt keeps)
// Single line, C style
/* Multi
line */
Top-level block types¶
| Block | Purpose |
|---|---|
terraform |
Settings: required_version, required_providers, backend, cloud, experiments |
provider |
Configures a provider plugin (credentials, region, subscription, features) |
resource |
A managed infrastructure object Terraform creates, updates and destroys |
data |
A data source: reads something that already exists |
ephemeral |
An ephemeral resource: opened per run, never stored in state (Terraform 1.10+, OpenTofu 1.11+) |
variable |
An input variable |
output |
An output value |
locals |
Named local values |
module |
A call to a child module |
moved, import, removed |
Refactoring and adoption instructions (state refactoring) |
check |
Continuous assertions that warn but don't block (policy) |
action |
Provider-defined imperative operations (Terraform 1.14+, advanced) |
list |
List resources in .tfquery.hcl files (Terraform 1.14+, advanced) |
Files and directories¶
Terraform loads every .tf and .tf.json file in one directory as a single module. File names have no meaning to Terraform, only to humans; the order of blocks across files doesn't matter either. Subdirectories are not loaded; they're only used if called as modules.
| Extension | Meaning |
|---|---|
*.tf / *.tf.json |
Configuration (native / JSON syntax) |
*_override.tf, override.tf |
Override files, merged on top of the rest (advanced) |
*.tfvars / *.tfvars.json |
Variable values. terraform.tfvars and *.auto.tfvars load automatically |
*.tftest.hcl |
terraform test files (testing) |
*.tfmock.hcl |
Shared mock data for tests |
*.tfquery.hcl |
List resources for terraform query (1.14+) |
*.tfcomponent.hcl, *.tfdeploy.hcl |
HCP Terraform Stacks configuration |
.terraform.lock.hcl |
Dependency lock file. Commit it |
.terraform/ |
Working directory cache. Never commit it |
The conventional file layout for a module is in hygiene.
How Terraform evaluates configuration¶
Terraform's language is declarative: you describe the desired end state and Terraform works out the steps. Order in the files is irrelevant. What matters is the dependency graph built from references between objects.
- Parse every file in the directory into one module.
- Build the graph. Every expression that references another object (
azurerm_subnet.app.id,var.x,module.net.vnet_id) becomes an edge. See dependencies. - Evaluate expressions as their inputs become available. Some values are known at plan time (literals, variables, most data sources). Others are unknown until apply (an ID a cloud API assigns).
- Walk the graph, in parallel where there are no edges (default parallelism is 10).
Two consequences show up constantly:
- Things that shape the graph must be known at plan time.
count,for_eachkeys, and modulesourcecan't depend on values that only exist after apply. The errorThe "for_each" map includes keys derived from resource attributes that cannot be determined until applyis this rule. - Unknown values propagate. If any input to an expression is unknown, the result is unknown and shows as
(known after apply)in the plan.
The JSON syntax¶
Every .tf construct has a JSON equivalent in .tf.json. Nobody should hand-write it. It exists so programs can generate configuration.
{
"resource": {
"azurerm_resource_group": {
"app": {
"name": "rg-app-dev-cc",
"location": "canadacentral"
}
}
}
}
In JSON, strings are interpreted as templates, so "${var.env}" still interpolates. Comments go in a "//" property. If you're generating configuration from code (your Rust tools, for example), emitting .tf.json avoids writing an HCL serializer.
Related¶
- Terraform fundamentals: providers, resources, data sources and the plan/apply lifecycle
- HCL development hygiene
- Advanced concepts