HCL Syntax: Blocks, Arguments & Expressions
HCL is a small configuration language: less than a programming language (no loops you write by hand, no I/O), more than YAML (references, expressions, functions, types). Everything in a .tf file is one of three things: blocks, arguments and expressions.
# a block: a type, zero or more labels, a body in braces
resource "local_file" "motd" { # type "resource", labels "local_file" and "motd"
filename = "motd.txt" # an argument: name = expression
content = "Hi ${var.team}!\n" # string template with interpolation
lifecycle { # a nested block (no "=")
prevent_destroy = true
}
}| Element | Rule |
|---|---|
| Block | type "label" "label" { … }. The number of labels is fixed per block type: resource has two, variable one, terraform none |
| Argument | name = value, at most once per body |
| Nested block | name { … }, no =, may repeat (e.g. several ingress { } in a security group) |
| Comments | # and // for lines, /* … */ for blocks (fmt prefers #) |
| Identifiers | letters, digits, _ and -; must not start with a digit |
| Files | .tf (HCL) and .tf.json (the same structure in JSON, for generated code) |
The top-level block types you'll use:
| Block | Purpose | Lesson |
|---|---|---|
terraform { } |
CLI version, required providers, backend | Providers |
provider "aws" { } |
configure a provider (region, credentials) | Providers |
resource "type" "name" { } |
an object to create and manage | Resources |
data "type" "name" { } |
read an existing object | Data Sources |
variable "name" { } |
an input | Variables |
output "name" { }, locals { } |
results and named values | Outputs & Locals |
module "name" { } |
call another folder of .tf files |
Modules |
import, moved, removed, check |
state refactoring and checks | State |
Values and types
| Type | Literal |
|---|---|
string |
"linkly", or a heredoc <<-EOT … EOT |
number |
3, 0.5 (one type for integers and floats) |
bool |
true, false |
list(…) / tuple |
["a", "b"] |
map(…) / object |
{ team = "platform", env = "dev" } |
null |
"not set": an argument set to null behaves as if omitted |
References connect blocks: var.name, local.name, resource_type.name.attribute (e.g. aws_vpc.main.id), data.type.name.attribute, module.name.output, and the special path.module, terraform.workspace. A reference is also a dependency: the CLI orders the work by them (The Dependency Graph).
Trying expressions in the console
tofu console evaluates expressions against the current configuration and state; it is the fastest way to learn HCL. Here it reads locals from main.tf, with the expressions piped in:
mkdir c && cd c
cat > main.tf <<'HCL'
locals {
name = "linkly"
ports = [80, 443]
tags = { team = "platform", env = "dev" }
}
HCL
tofu console <<'EXPR'
local.name
"${local.name}-api"
local.ports[1]
local.tags["env"]
local.tags.team
upper(local.name)
length(local.ports)
1 + 2 * 3
local.ports[0] == 80 ? "http first" : "https first"
EXPR"linkly"
"linkly-api"
443
"dev"
"platform"
"LINKLY"
2
7
"http first"
Strings print with their quotes because the console shows HCL values, not text. Indexing works with [ ] for lists and maps, and .key for object/map keys that are valid identifiers.
Formatting is not optional
fmt rewrites files into the canonical style: two-space indentation and aligned = signs in a group of arguments. Teams run fmt -check in CI so a review never argues about whitespace:
mkdir f && cd f
cat > main.tf <<'HCL'
resource "terraform_data" "x" {
input = "a"
triggers_replace = [1,2]
}
HCL
tofu fmt -check; echo "exit=$?"
tofu fmt -diff
tofu fmt -check; echo "exit=$?"main.tf
exit=3
main.tf
--- old/main.tf
+++ new/main.tf
@@ -1,4 +1,4 @@
resource "terraform_data" "x" {
-input = "a"
- triggers_replace = [1,2]
- }
+ input = "a"
+ triggers_replace = [1, 2]
+}
exit=0
-check prints the files that need formatting and exits non-zero; plain fmt fixes them in place and lists them; -diff shows the change; -recursive descends into subfolders (modules). Exit status 0 on the second check is what a pipeline wants.
Test yourself
How many labels does a resource block take?
- None
- One: the name
- Two: the type and the local name
- Any number
What does setting an argument to null do?
- Sets it to an empty string
- Behaves as if the argument were omitted
- Deletes the resource
- Causes a validation error
Which command fails in CI when files are not canonically formatted?
tofu validatetofu fmt -checktofu plan -linttofu fmt -diffwithout-checkalways fails