You closed module 1 with an EcoMarket project that worked end to end: init, plan, apply, destroy. But what you wrote there was the bare minimum needed to make the machine do something. From here on you have to master the language infrastructure is written in. This lesson is the complete grammar of HCL2 (HashiCorp Configuration Language, version 2): how a block is built, what data types exist, how expressions combine, how collections are traversed, and how all of it is written in the canonical style any reviewer expects. It is the densest lesson in the module and the one that holds up all the others: without it, count, for_each, dynamic or the module 6 functions are magic; with it, they are natural consequences of the language.
- What HCL2 is and why it is not JSON
HCL is a configuration language created by HashiCorp with one very specific goal: to be readable and writable by people, yet processable by machines. It is not a general-purpose programming language: it has no while loops, no user-defined functions and no mutable variables. It is a declarative language for describing data structures, with expressions rich enough that you are never forced to repeat yourself.
The version Terraform has used since 0.12 is HCL2, which added three decisive things to HCL1:
- A real type system (previously almost everything was a string).
- A complete expression language (conditionals,
for, splat, nested functions). - First-class interpolation: expressions are written directly, without always wrapping them in quotes.
Why not use JSON or YAML directly? Compare the same fragment:
# HCL: comments, expressions and native references
resource "local_file" "inventory" {
filename = "${path.module}/${local.prefix}-inventory.json" # computed path
content = jsonencode(local.inventory_data)
}{
"resource": {
"local_file": {
"inventory": {
"filename": "${path.module}/${local.prefix}-inventory.json",
"content": "${jsonencode(local.inventory_data)}"
}
}
}
}Differences that matter day to day:
| Aspect | HCL | JSON | YAML |
|---|---|---|---|
| Comments | Yes (#, //, /* */) |
Do not exist | Yes (#) |
| Expressions and functions | Native | Only inside "${...}" strings |
Only through external templates |
| Trailing commas required | No | Yes, and the last one is forbidden | No |
| Block nesting | Natural and flat | Deep, with chained braces | Indentation-sensitive |
| Typical errors | Few, with clear messages | One comma too many or too few | Spaces and tabs |
| Audience | Human | Machine | Mixed |
The practical rule: HCL for what people write, JSON for what programs generate.
- The alternative JSON syntax:
.tf.json
.tf.jsonTerraform accepts exactly the same semantics in files with the .tf.json extension. They are loaded alongside the .tf files in the same directory and take part in the same graph. The equivalence is mechanical:
- Each block type becomes a key of the root object.
- Each label adds one nesting level.
- The body is the object at the deepest level.
- Expressions travel as strings containing
${...}.
A complete example with two EcoMarket resources:
{
"locals": {
"prefix": "${var.project}-${var.environment}"
},
"resource": {
"random_pet": {
"suffix": {
"length": 2,
"separator": "-"
}
},
"local_file": {
"inventory": {
"filename": "${path.module}/${local.prefix}-inventory.json",
"content": "${jsonencode({ environment = var.environment })}"
}
}
}
}When to use .tf.json:
- When the configuration is generated by a program (a script that reads a service catalogue and emits resources).
- In third-party tools that produce Terraform and do not want to implement an HCL serialiser.
- For auto-generated fragments that live next to hand-written HCL.
When not to use it: for code a person will maintain. You lose comments, readability and terraform fmt (which does not format JSON). In EcoMarket the whole ecomarket-infra repository is HCL; only the day a script generates the list of environments from an internal catalogue will emitting a .tf.json be worth considering.
- The formal anatomy of a block
Every .tf file is a sequence of blocks and, occasionally, loose arguments. A block has this shape:
block_type "label1" "label2" {
argument = expression
nested_block {
another_argument = expression
}
}Broken down over a real resource:
# ┌── block type
# │ ┌── label 1: resource type (defined by the provider)
# │ │ ┌── label 2: local name (you choose it)
# ▼ ▼ ▼
resource "local_file" "inventory" {
# ── arguments: name = expression pairs
filename = "${path.module}/ecomarket-dev-inventory.json"
file_permission = "0644"
# ── nested block: no "=", and its schema is defined by the provider
lifecycle {
create_before_destroy = true
}
}The formal points you need to internalise:
- The number of labels is fixed by the block type, not by you.
resourcetakes two,variableone,terraformnone,localsnone. - Argument =
name = expression. Always with=. - Nested block =
name { ... }. Never with=(a classic mistake is writinglifecycle = { ... }, which Terraform rejects). - The braces delimit the body. The opening one goes on the same line as the header.
- There are no commas between arguments. A line break is enough.
How many labels each top-level block takes:
| Block | Labels | Example |
|---|---|---|
terraform |
0 | terraform { ... } |
locals |
0 | locals { ... } |
provider |
1 (provider name) | provider "aws" { ... } |
variable |
1 (name) | variable "environment" { ... } |
output |
1 (name) | output "web_url" { ... } |
module |
1 (name) | module "network" { ... } |
resource |
2 (type, name) | resource "aws_s3_bucket" "images" { ... } |
data |
2 (type, name) | data "aws_ami" "ubuntu" { ... } |
moved / import / check |
0 / 0 / 1 | covered in modules 3 and 6 |
One detail that confuses people at first: a block can contain several nested blocks of the same type, and that is not an error, it is how lists of sub-objects are expressed:
# ILLUSTRATIVE AWS example (we will actually deploy it in module 5).
resource "aws_security_group" "ecomarket_web" {
name = "ecomarket-dev-web-sg"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}Two ingress blocks = two rules. When that list becomes dynamic you will need dynamic, covered in Dynamic Blocks.
- Identifiers and naming conventions
A valid HCL identifier starts with a letter or _ and continues with letters, digits, _ or -. It accepts Unicode characters, but do not use them: variable "región" is legal and a bad idea, because it complicates grep, paths and integration with tooling.
Rules and conventions accepted by the community, with what EcoMarket applies:
| Element | Convention | EcoMarket example |
|---|---|---|
| Resource name | snake_case, descriptive, without repeating the type |
resource "aws_s3_bucket" "images" (not "images_bucket") |
| Only resource of its kind | this or main |
resource "aws_vpc" "this" |
| Variable | snake_case, a noun |
var.environment, var.db_config |
| Output | snake_case, describes the value |
output "web_url" |
| Local | snake_case |
local.prefix, local.common_tags |
| Module | snake_case, the role it plays |
module "network", module "database" |
| Cloud tag values | The provider's style (PascalCase in AWS) |
Project, Environment, ManagedBy |
Notice the project's deliberate asymmetry: HCL identifiers use snake_case and the project's own vocabulary (prefix, common_tags), while the cloud's tag keys follow the provider's convention (Project, Environment). They are two separate namespaces and should not be mixed.
A frequent mistake:
# BAD: the type already says it is a bucket and that it belongs to AWS.
resource "aws_s3_bucket" "aws_s3_bucket_images_ecomarket" {}
# It would be referenced as aws_s3_bucket.aws_s3_bucket_images_ecomarket.id
# GOOD
resource "aws_s3_bucket" "images" {}
# It is referenced as aws_s3_bucket.images.id
- Comments
HCL accepts three forms:
# Line comment. This is the PREFERRED style and the one terraform fmt enforces:
# if you write //, fmt turns it into #.
// Alternative line comment, inherited from C.
/*
Block comment, multi-line.
Handy for temporarily disabling a fragment
or for section headers.
*/
locals {
prefix = "${var.project}-${var.environment}" # end-of-line comment
}Practical details:
terraform fmtrewrites//as#when the comment takes up the whole line. Write#from the start and save yourself noise in the diffs.- Block comments
/* */do not nest. - A widely used pattern for separating sections in
main.tf, which you already saw in module 1:
# ---------------------------------------------------------------------------
# Product image storage
# ---------------------------------------------------------------------------- Comments never reach the state or the plan. They document the code, not the infrastructure; that is what
descriptionon variables and outputs, and resource tags, are for.
- The type system
This is the conceptual heart of HCL2. Terraform classifies every value into one of these types:
flowchart TD
T["HCL2 types"] --> P["Primitives"]
T --> C["Collections<br/>(elements of the SAME type)"]
T --> E["Structural<br/>(elements of DIFFERENT types)"]
T --> N["null<br/>(absence of a value)"]
P --> P1["string"]
P --> P2["number"]
P --> P3["bool"]
C --> C1["list(T)<br/>ordered, allows duplicates"]
C --> C2["set(T)<br/>unordered, no duplicates"]
C --> C3["map(T)<br/>string keys → T"]
E --> E1["object({...})<br/>named, typed attributes"]
E --> E2["tuple([...])<br/>fixed type per position"]
The reference table:
| Type | Declaration | Literal | Notes |
|---|---|---|---|
string |
string |
"ecomarket" |
Always in double quotes |
number |
number |
3, 3.5, -2 |
Does not distinguish integer from decimal |
bool |
bool |
true, false |
No quotes |
list(T) |
list(string) |
["dev", "staging", "prod"] |
Ordered, index from 0, allows duplicates |
set(T) |
set(string) |
toset(["dev", "prod"]) |
Unordered, no duplicates, not indexable |
map(T) |
map(number) |
{ dev = 1, prod = 3 } |
Keys are always string |
object({...}) |
object({ name = string, port = number }) |
{ name = "web", port = 8080 } |
Fixed, typed attributes |
tuple([...]) |
tuple([string, number, bool]) |
["web", 8080, true] |
Fixed length and type per position |
any |
any |
— | "whatever"; Terraform infers it |
null |
— | null |
Absence of a value, not "empty" |
The three distinctions that cause the most mistakes:
list versus set. A list has order and positions; a set does not. This is not an academic subtlety: with count the order of a list determines the indices in the state, and deleting the first element shifts all the rest. With for_each over a set, each element is identified by its value. You will see the plan output that proves it in Resource and Data Blocks.
locals {
environment_list = ["dev", "staging", "prod", "dev"] # 4 elements, "dev" twice
environment_set = toset(local.environment_list) # 3 elements, order not guaranteed
first_environment = local.environment_list[0] # "dev" — valid
# local.environment_set[0] # ERROR: a set is not indexed by number
}map versus object. A map(string) has arbitrary keys and all its values share one type. An object has a fixed, known set of attributes, each with its own type.
locals {
# map(string): any key, all values are strings.
common_tags = {
Project = "ecomarket"
Environment = "dev"
ManagedBy = "terraform"
}
# object: specific attributes of different types.
# Its real type is object({ engine = string, version = string,
# port = number, multi_az = bool })
db_config = {
engine = "postgres"
version = "16.3"
port = 5432
multi_az = false
}
}Even though they are written the same way ({ ... }), Terraform infers map when every value shares a type and object when they do not. When declaring variables you will have to choose explicitly, and that is the subject of the next lesson.
null versus the empty string. null means "this argument is not set, use the provider's default". "" is a value: the empty string.
locals {
# If var.description is empty, we let the provider decide.
effective_description = var.description != "" ? var.description : null
}Accessing elements, with both notations:
locals {
environments = ["dev", "staging", "prod"]
config = {
engine = "postgres"
port = 5432
}
# Lists and tuples: numeric index from 0.
second = local.environments[1] # "staging"
# Maps and objects: dot or bracket notation.
engine_a = local.config.engine # "postgres" — only if the key is a valid identifier
engine_b = local.config["engine"] # "postgres" — always works
engine_c = local.config[var.key] # computed key: brackets are mandatory
}
- Implicit type conversion
Terraform converts automatically between types when the conversion is unambiguous:
| From | To | Automatic? | Example |
|---|---|---|---|
number |
string |
Yes | 5432 → "5432" |
bool |
string |
Yes | true → "true" |
string |
number |
Yes, if it is numeric | "5432" → 5432; "web" → error |
string |
bool |
Yes, only "true"/"false" |
"yes" → error |
list |
set |
Yes (loses order and duplicates) | ["a","a"] → {"a"} |
set |
list |
Yes (lexicographic order) | — |
tuple |
list |
Yes, if the types can be unified | — |
object |
map |
Yes, if every attribute shares a type | — |
map |
object |
Yes, if every required attribute is present | — |
null |
anything | Yes | — |
In practice this means you can write port = "5432" where a number is expected and it will work. Do not do it: declare the right types and let Terraform validate. Implicit conversion is a safety net, not a style.
When the conversion is not automatic there are explicit functions — tostring(), tonumber(), tobool(), tolist(), toset(), tomap() — plus the encoding ones such as jsonencode()/jsondecode(). The full function catalogue is the subject of Terraform Functions; here all that matters is that the type system exists and when it saves you.
An example of a real error the type system produces:
$ terraform plan
╷
│ Error: Invalid value for input variable
│
│ on terraform.tfvars line 4:
│ 4: db_port = "five thousand"
│
│ The given value is not suitable for var.db_port declared at
│ variables.tf:12,1-20: a number is required.
╵That error happens before anything is touched. Without types, the failure would have arrived while trying to create the database.
- Strings: literals, interpolation, escapes and heredocs
HCL strings use double quotes. There are no single quotes.
locals {
simple = "ecomarket"
# Interpolation: ${ expression } inside a string.
prefix = "${var.project}-${var.environment}"
# Interpolation with a richer expression inside.
db_name = "${local.prefix}-db-${substr(var.region, 0, 8)}"
# WATCH OUT: UNNECESSARY interpolation. fmt does not remove it, but the linter warns.
wrong = "${var.environment}" # equivalent to...
right = var.environment # ...this, which is the correct form.
}Golden rule: use ${...} only when the expression sits inside a larger piece of text. If the string is exactly one expression, write the bare expression.
Escape sequences:
| Sequence | Meaning |
|---|---|
\n |
Line break |
\r |
Carriage return |
\t |
Tab |
\" |
Literal double quote |
\\ |
Literal backslash |
\uNNNN |
Unicode character (4 hex digits) |
$${ |
A literal ${, without interpolating |
%%{ |
A literal %{, without interpreting the directive |
The last two are essential when you generate content that itself uses ${...}, such as a docker-compose.yml, a systemd unit template or a start-up script:
locals {
# We want the file to contain literally ${HOSTNAME}, not the value.
script_fragment = "echo \"Starting on $${HOSTNAME} for ${var.environment}\""
# Result: echo "Starting on ${HOSTNAME} for dev"
}Heredocs for multi-line text. There are two variants and the difference matters:
locals {
# <<EOT : keeps the indentation EXACTLY as it is in the .tf file.
unindented = <<EOT
Project: ${var.project}
Environment: ${var.environment}
EOT
# <<-EOT : strips the indentation common to every line.
# It lets you indent the heredoc with the rest of the code without dirtying the output.
indented = <<-EOT
Project: ${var.project}
Environment: ${var.environment}
Contact: [email protected]
EOT
}The content of indented is exactly:
Project: ecomarket Environment: dev Contact: [email protected]
Three heredoc rules that break configurations:
- The closing marker (
EOT) must sit on its own line. With<<-it may be indented; with<<it must be in column 0. - The marker can be called whatever you like (
EOT,EOF,SCRIPT,JSON), but the opening and closing ones must match. - Interpolation does happen inside a heredoc. If you want a literal
${}, write$${}.
A heredoc almost always ends with a trailing newline. If that bothers you:
- String directives:
%{ if } and %{ for }
%{ if } and %{ for }Inside a string, besides ${...} for values, there are control directives written with %{...}. They are especially useful in heredocs that generate configuration files.
locals {
environments = ["dev", "staging", "prod"]
notice = <<-EOT
Environment: ${var.environment}
%{ if var.environment == "prod" ~}
WARNING: this is the PRODUCTION environment. Review the plan twice.
%{ else ~}
Non-production environment: you can experiment safely.
%{ endif ~}
Managed environments:
%{ for e in local.environments ~}
- ${var.project}-${e}
%{ endfor ~}
EOT
}With var.environment = "dev" the result is:
Environment: dev Non-production environment: you can experiment safely. Managed environments: - ecomarket-dev - ecomarket-staging - ecomarket-prod
The key is the tilde ~: %{ ... ~} strips the whitespace (including the line break) that follows the directive, and %{~ ... } the whitespace that precedes it. Without the tildes you would get one blank line per directive, which is the number one reason generated files look odd.
- Operators and precedence
HCL2 has the usual set of operators:
| Category | Operators | Example |
|---|---|---|
| Arithmetic | +, -, *, /, % |
var.instances * 2 |
| Unary | - (negation), ! (logical not) |
!var.multi_az |
| Comparison | ==, !=, <, <=, >, >= |
var.environment == "prod" |
| Logical | &&, ||, ! |
var.is_prod && var.backups_enabled |
Precedence, from highest to lowest (whatever is evaluated first is at the top):
| Level | Operators |
|---|---|
| 1 | !, - (unary) |
| 2 | *, /, % |
| 3 | +, - |
| 4 | >, >=, <, <= |
| 5 | ==, != |
| 6 | && |
| 7 | || |
| 8 | ? : (conditional) |
Annotated examples based on EcoMarket's sizing:
locals {
base_instances = 2
prod_factor = 3
# 1. Arithmetic: * before + → 2 + (2*3) = 8
total_a = local.base_instances + local.base_instances * local.prod_factor
# 2. With parentheses, explicit → (2+2)*3 = 12
total_b = (local.base_instances + local.base_instances) * local.prod_factor
# 3. && before ||. This means: (is_prod && multi_az) || force
# It is NOT: is_prod && (multi_az || force)
requires_replica = var.is_prod && var.multi_az || var.force_replica
# 4. The same thing, but readable. ALWAYS write it like this.
requires_replica_clear = (var.is_prod && var.multi_az) || var.force_replica
# 5. The modulo (%) gives the remainder: handy for spreading across availability zones.
zone_index = 5 % 3 # 2
}Two important warnings about the operators:
/is real division, not integer division.7 / 2gives3.5. For the integer part usefloor(7 / 2).==compares by value and by type after implicit conversion."5" == 5istruebecause the string is converted to a number;"dev" == 5is a type error, notfalse.&&and||do not short-circuit reliably where errors are concerned: if the right-hand side contains an invalid expression (an out-of-range index, for instance), Terraform may evaluate it anyway. That is whatcan()is for, and you will see it in the next lesson.
- Conditional expressions
? :
? :The syntax is condition ? value_if_true : value_if_false, and the condition must be a bool.
locals {
is_production = var.environment == "prod"
# Sizing per environment.
instance_count = local.is_production ? 3 : 1
# Instance class (ILLUSTRATIVE AWS example, module 5).
db_class = local.is_production ? "db.t3.medium" : "db.t3.micro"
# Backup retention, in days.
retention_days = local.is_production ? 30 : 7
# Nested: three cases. Readable only up to two levels.
maintenance_window = (
var.environment == "prod" ? "sun:03:00-sun:04:00" :
var.environment == "staging" ? "sat:02:00-sat:03:00" :
"mon:01:00-mon:02:00"
)
}Both branches must be convertible to a common type. If one returns string and the other number, Terraform unifies to string; if one returns a list and the other an object, it fails.
For more than two or three cases, a nested conditional becomes unreadable. The idiomatic pattern is a lookup map:
locals {
# Sizing table per environment: far more readable and easier to extend.
sizing = {
dev = { instances = 1, class = "db.t3.micro", retention = 7 }
staging = { instances = 2, class = "db.t3.small", retention = 14 }
prod = { instances = 3, class = "db.t3.medium", retention = 30 }
}
# lookup(map, key, default) avoids an error if the environment does not exist.
current = lookup(local.sizing, var.environment, local.sizing["dev"])
instances = local.current.instances
db_class = local.current.class
}This is the pattern EcoMarket will use across its three environments, and it comes back in the next lesson turned into a variable of type map(object(...)).
for expressions and the splat operator
for expressions and the splat operatorfor expressions transform one collection into another. They are the tool that saves you from copying and pasting.
12.1. A for that produces a list or tuple
It is written in square brackets:
locals {
environments = ["dev", "staging", "prod"]
# [for ELEMENT in COLLECTION : EXPRESSION]
web_names = [for e in local.environments : "${var.project}-${e}-web"]
# ["ecomarket-dev-web", "ecomarket-staging-web", "ecomarket-prod-web"]
# With an "if" filter: only the non-production environments.
ephemeral_environments = [for e in local.environments : e if e != "prod"]
# ["dev", "staging"]
# Iterating a map: you get TWO variables, key and value.
tags_text = [for k, v in local.common_tags : "${k}=${v}"]
# ["Project=ecomarket", "Environment=dev", "ManagedBy=terraform"]
# Iterating a list with an index: the first name is the index.
numbered = [for i, e in local.environments : "${i}: ${e}"]
# ["0: dev", "1: staging", "2: prod"]
}12.2. A for that produces a map or object
It is written in braces and uses => between key and value:
locals {
# {for ELEMENT in COLLECTION : KEY => VALUE}
buckets_by_environment = {
for e in local.environments : e => "${var.project}-${e}-images"
}
# {
# dev = "ecomarket-dev-images"
# staging = "ecomarket-staging-images"
# prod = "ecomarket-prod-images"
# }
# Inverting a map: the values become keys.
inverted_tags = {
for k, v in local.common_tags : v => k
}
# Normalising keys and filtering at the same time.
normalised_config = {
for k, v in var.db_params : lower(k) => v
if v != null && v != ""
}
}A map's keys must be unique. If two elements produce the same key, Terraform fails with Duplicate object key. To group values under the same key there is grouping mode, written with ... after the value:
locals {
services = [
{ name = "web", environment = "dev" },
{ name = "api", environment = "dev" },
{ name = "batch", environment = "prod" },
]
# Without "...": an error, because "dev" appears twice.
# With "...": each key collects a LIST of values.
by_environment = {
for s in local.services : s.environment => s.name...
}
# {
# dev = ["web", "api"]
# prod = ["batch"]
# }
}12.3. The splat operator [*]
Splat is syntactic sugar for the most common case of for: extracting one attribute from every element of a list.
locals {
# These two expressions are EQUIVALENT:
with_for = [for f in local_file.inventories : f.filename]
with_splat = local_file.inventories[*].filename
}Three splat behaviours worth knowing:
locals {
# 1. Splat over a resource with count: returns the list of every index.
# (ILLUSTRATIVE AWS example, module 5)
# instance_ids = aws_instance.web[*].id
# 2. Splat over a value that is NOT a list: wraps it in a list of 1.
# That is what makes splat useful with resources that may have 0 or 1 copies.
# name = aws_s3_bucket.images[*].bucket # ["ecomarket-dev-images"]
# 3. Splat over null: returns an empty list [].
# That is why the one(aws_x.y[*].id) pattern is so common: "0 or 1 element".
}There is also the old form resource.*.attribute (legacy splat), which only works over lists and has odd corner cases. Always use [*].
One important detail: splat does not work over maps or over resources with for_each, because those produce a map, not a list. For those, use a for expression or the values() function:
locals {
# With for_each the resource is a MAP: splat does not apply.
# paths = local_file.by_environment[*].filename # ERROR
paths = [for f in local_file.by_environment : f.filename] # correct
paths_2 = values(local_file.by_environment)[*].filename # also correct
}In Dynamic Blocks we will pick up for expressions again, applied to generating nested blocks; here you already have the complete language.
- Local values (
locals) in depth
locals) in depthA local value is a name for an expression inside a module. It is declared in one or more locals blocks and referenced in the singular:
# You can have several locals blocks in the same module, even in
# different files. Terraform merges them.
locals {
prefix = "${var.project}-${var.environment}"
common_tags = {
Project = var.project
Environment = var.environment
ManagedBy = "terraform"
}
}
locals {
# A local CAN reference another local, as long as there are no cycles.
db_name = "${local.prefix}-db"
bucket_name = "${local.prefix}-images"
lb_name = "${local.prefix}-lb"
# Composing maps with merge(): the right-hand keys win.
db_tags = merge(local.common_tags, {
Component = "database"
Backup = var.environment == "prod" ? "daily" : "weekly"
})
}When to use locals:
| Situation | locals? |
Reason |
|---|---|---|
| An expression is repeated in 3+ places | Yes | A single point of change |
| A complex calculation with conditionals | Yes | You give the intent a name |
| Composing common tags | Yes | It is the canonical case |
| A value that must be changeable from outside | No | That is a variable |
| A trivial value used only once | No | Adds indirection with no gain |
| Chaining 6 locals that are only used by each other | No | Unreadable; extract a module or simplify |
Differences from variable, worth committing to memory:
variable |
locals |
|
|---|---|---|
| Who gives it a value | The caller (CLI, .tfvars, environment, parent module) |
The configuration itself |
| Can it be overridden? | Yes | No |
Accepts type, validation, sensitive? |
Yes | No (sensitive only propagates) |
| Can it reference resources? | No | Yes |
| Scope | The module where it is declared | The module where it is declared |
| Reference | var.name |
local.name |
A local can indeed reference resource attributes, and that makes it part of the dependency graph:
locals {
# This local depends on random_id.suffix_hex: Terraform will resolve it
# after creating that resource, and it will show up as (known after apply)
# in the plan of everything that uses it.
global_bucket_name = "${local.prefix}-images-${random_id.suffix_hex.hex}"
}What a local cannot do: reference itself, directly or indirectly. Terraform detects the cycle:
- The
terraform block and its arguments
terraform block and its argumentsYou already used it in module 1 with required_version and required_providers. These are all of its arguments:
terraform {
# Terraform BINARY version required.
required_version = ">= 1.5.0, < 2.0.0"
# Required providers, with their source and version constraint.
# Studied in depth in 02-04.
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.5"
}
random = {
source = "hashicorp/random"
version = "~> 3.6"
}
}
# Where the state is kept. A NESTED block with a single label.
# It is the subject of module 3.
# backend "s3" {
# bucket = "ecomarket-tfstate"
# key = "dev/terraform.tfstate"
# region = "eu-west-1"
# }
# Alternative to the backend: integration with HCP Terraform (module 8).
# cloud {
# organization = "ecomarket"
# workspaces { name = "infra-dev" }
# }
# Experimental features. Avoid them in production.
# experiments = []
}Very important constraints on this block:
- It accepts no expressions and no variables.
required_version = var.versionis illegal. Terraform reads this block before evaluating anything, so it only accepts literals. - There can only be one
backendor onecloud, never both. required_versionis not inherited from parent module to child: each module declares its own, and Terraform requires all of them to be satisfied.- The
terraformblock may be repeated across several files; Terraform merges them, although the convention is to keep a single one inversions.tf.
- References and addresses
Every reference in HCL starts with a prefix that says where the value comes from:
| Prefix | What it references | Example |
|---|---|---|
var.<name> |
Input variable | var.environment |
local.<name> |
Local value | local.prefix |
<type>.<name>.<attribute> |
Managed resource | random_pet.suffix.id |
data.<type>.<name>.<attribute> |
Data source | data.local_file.template.content |
module.<name>.<output> |
A module's output | module.network.vpc_id |
each.key / each.value |
Current element in for_each |
each.value.class |
count.index |
Current index in count |
count.index |
path.module |
Path of the current module | "${path.module}/templates" |
path.root |
Path of the root module | — |
path.cwd |
Current working directory | — |
terraform.workspace |
Name of the workspace | terraform.workspace |
self.<attribute> |
The resource itself (only in provisioners and connection) |
self.private_ip |
About the three path.*, which are constantly confused:
# Suppose you run from ~/projects/ecomarket-infra/infra/dev
# and that there you call a local module in ../../modules/storage.
#
# Inside that MODULE:
# path.module = "../../modules/storage" (path of the module)
# path.root = "." (root of the configuration)
# path.cwd = "/home/dev/projects/ecomarket-infra/infra/dev"
#
# Use path.module to read files that live NEXT TO the module's code.
# It is the right choice in 95 % of cases.terraform.workspace returns the name of the active workspace (default if you have not created any). We mention it here because it is part of the language, but its use as a mechanism for separating environments is studied in Terraform Workspaces.
And a rule about resource addresses that you already saw in module 1 and that is now completed: when a resource uses count its address carries a numeric index, and when it uses for_each it carries a key in quotes.
local_file.inventory # simple resource local_file.inventory[0] # with count local_file.inventory["dev"] # with for_each module.network.aws_subnet.public[1] # inside a module, with count
terraform console: the language workbench
terraform console: the language workbenchNone of the above is learnt by reading: it is learnt by trying. terraform console opens an interactive interpreter with access to your variables, locals, functions and — if it exists — the state.
A sample session with the EcoMarket project:
# Primitive types and arithmetic
> 7 / 2
3.5
> floor(7 / 2)
3
# Variables and locals loaded from the configuration
> var.environment
"dev"
> local.prefix
"ecomarket-dev"
> local.common_tags
{
"Environment" = "dev"
"ManagedBy" = "terraform"
"Project" = "ecomarket"
}
# Checking the TYPE of a value: essential for debugging
> type(local.common_tags)
map(string)
> type(["dev", 1, true])
tuple([string, number, bool])
> type(toset(["dev", "prod"]))
set(string)
# for expressions and splat
> [for e in ["dev", "staging", "prod"] : "${var.project}-${e}-web"]
[
"ecomarket-dev-web",
"ecomarket-staging-web",
"ecomarket-prod-web",
]
> {for e in ["dev", "prod"] : e => "${var.project}-${e}-images"}
{
"dev" = "ecomarket-dev-images"
"prod" = "ecomarket-prod-images"
}
# Conditionals
> var.environment == "prod" ? 3 : 1
1
# Access to the state, if you have already applied
> random_pet.suffix.id
"cheerful-mammoth"
# Exit
> exitTricks that save a lot of time:
# Evaluate an expression without an interactive session (handy in scripts and CI).
$ echo 'local.prefix' | terraform console
"ecomarket-dev"
# Try the language out in an EMPTY directory: functions and types are still there.
$ mkdir -p /tmp/hcl-tests && cd /tmp/hcl-tests && terraform console
> merge({a = 1}, {b = 2})
{
"a" = 1
"b" = 2
}terraform console modifies nothing: it is read-only. Use it without fear every time you are unsure how an expression behaves.
terraform fmt and the canonical style
terraform fmt and the canonical styleHCL has a canonical format and a tool that enforces it. This is not a matter of taste: it removes arguments from reviews and reduces diffs to real changes.
The rules terraform fmt applies:
- Two-space indentation per level. Never tabs.
- Alignment of the
=signs within each consecutive group of arguments. - A blank line separates groups of arguments and nested blocks.
- Whole-line comments written with
//are turned into#. - Trailing whitespace at the end of lines is removed.
Before and after:
# BEFORE: legal, but untidy.
resource "local_file" "inventory" {
filename="${path.module}/${local.prefix}-inventory.json"
file_permission = "0644"
content=jsonencode({
environment=var.environment
prefix = local.prefix
})
}# AFTER terraform fmt
resource "local_file" "inventory" {
filename = "${path.module}/${local.prefix}-inventory.json"
file_permission = "0644"
content = jsonencode({
environment = var.environment
prefix = local.prefix
})
}Notice one subtle detail: filename and file_permission end up aligned with each other, but content is not aligned with them because its value is multi-line and breaks the group. fmt aligns groups of consecutive single-line arguments.
The flags you need:
# Format the current directory and print the files it changed.
$ terraform fmt
main.tf
variables.tf
# Recursive: includes subdirectories (local modules).
$ terraform fmt -recursive
# Check mode for CI: changes nothing and returns a code != 0
# if anything would need formatting. With -diff it shows what would change.
$ terraform fmt -check -recursive -diff
main.tf
--- old/main.tf
+++ new/main.tf
@@ -2,3 +2,3 @@
-filename="x"
+ filename = "x"
$ echo $?
3What terraform fmt does not do, and it is worth knowing:
- It does not reorder arguments or blocks. The order is up to you.
- It does not format
.tf.jsonfiles. - It does not detect semantic errors:
terraform validateis for that. - It does not enforce naming conventions or remove unnecessary interpolations.
tflintexists for that, and we will see it in Testing Terraform Code.
Extra style conventions that fmt does not enforce but the community does expect:
- Meta-arguments (
count,for_each,provider) go first in the resource body, separated by a blank line. lifecycleanddepends_ongo last.- One resource per "thing"; group related resources in the same file.
resource "local_file" "inventory" {
for_each = local.environments_map # 1. meta-arguments
filename = "${path.module}/${var.project}-${each.key}.json" # 2. arguments
content = jsonencode(each.value)
lifecycle { # 3. behaviour blocks
create_before_destroy = true
}
}Common Mistakes and Tips
- Writing
lifecycle = { ... }instead oflifecycle { ... }. Nested blocks do not take=. The error saysUnsupported argumentorBlock type not expected, and it is thoroughly misleading. - Unnecessary interpolation:
"${var.environment}". It works, but it is noise. Writevar.environment. It is the most frequenttflintwarning. - Confusing
listwithset. Indexing asetby number is an error;toset()discards order and duplicates. Choose the type by how you are going to use it, not by how you write it. - Confusing
nullwith""or with[].nullis "there is no value";""and[]are values. Passing""where the provider expects a name usually produces API errors atapplytime, not atplantime. - A badly closed heredoc marker. With
<<EOT, the finalEOTmust be in column 0. If you indent it, Terraform keeps reading to the end of the file and gives a cryptic error. Use<<-EOTalmost always. - Forgetting
$${}when generating files that use${}. Start-up scripts, Nginx templates anddocker-compose.ymlare the usual victims: Terraform tries to interpolate variables that do not exist. - Duplicate keys in a map
for. The error isDuplicate object key. If you need to group, use...mode. - Relying on the precedence of
&&over||. It is correct, but nobody remembers it during a review. Add parentheses. - Nested conditionals more than two levels deep. Replace them with a lookup map and
lookup(). It reads better and extends without touching the logic. - Tip: keep
terraform consoleopen in a second terminal while you write complex configurations. Checkingtype(...)of a value settles most doubts in seconds. - Tip: turn on format-on-save in your editor (you configured it in Installing Terraform) and add
terraform fmt -check -recursiveto your pipeline from day one. - Tip: when an expression does not fit comfortably on one line, give it a name with a
local. The code then reads like prose and the plan stays identical.
Exercises
Exercise 1: types and expressions in terraform console
Open terraform console in the EcoMarket directory and work these out, noting the result and the type of each expression:
- What type does
["dev", "staging", 3]have? Andtoset(["dev", "dev", "prod"])? - Build a list with the bucket names of the three environments in the format
ecomarket-<environment>-images. - Turn that list into a map whose key is the environment and whose value is the bucket name.
- Given the map from point 3, obtain a list containing only the names of the non-production environments.
- What is the value of
2 + 2 * 3 > 7 && false || true? Reason it out by precedence before running it.
Exercise 2: the deployment configuration file
Extend the EcoMarket configuration from module 1 with a local_file called deployment_config that generates ecomarket-<environment>-deploy.conf with exactly this content when environment = "dev":
# Deployment configuration for ecomarket-dev project=ecomarket environment=dev region=eu-west-1 instances=1 retention_days=7 production=false [email protected] # Planned resources resource=ecomarket-dev-web resource=ecomarket-dev-lb resource=ecomarket-dev-db resource=ecomarket-dev-images
Requirements:
- Use an indented heredoc and a
%{ for }directive for the resource list. - The instance count and the retention days must come from a sizing map per environment, not from nested conditionals.
- The value of
productionmust be computed with a conditional or comparison expression. - Check with
terraform applythat the generated file has no extra blank lines.
Exercise 3: from the nested conditional to the lookup map
A colleague has written this in locals.tf:
locals {
class = var.environment == "prod" ? "db.t3.medium" : var.environment == "staging" ? "db.t3.small" : var.environment == "dev" ? "db.t3.micro" : "db.t3.micro"
retention = var.environment == "prod" ? 30 : var.environment == "staging" ? 14 : 7
multi_az = var.environment == "prod" ? true : false
name = "${var.project}" + "-" + "${var.environment}" + "-db"
}- Identify three distinct problems in this fragment (one of them stops the configuration from being valid).
- Rewrite it using a sizing map and the language's idiomatic constructs.
- Explain why the new version is easier to extend when EcoMarket adds a fourth environment called
sandbox.
Solutions
Solution 1:
It is a tuple, not a list, because its elements have different types. A list requires every element to share one type.
> type(toset(["dev", "dev", "prod"]))
set(string)
> toset(["dev", "dev", "prod"])
toset([
"dev",
"prod",
])The duplicate disappears and the result is shown in lexicographic order.
# 2
> [for e in ["dev", "staging", "prod"] : "ecomarket-${e}-images"]
[
"ecomarket-dev-images",
"ecomarket-staging-images",
"ecomarket-prod-images",
]
# 3
> {for e in ["dev", "staging", "prod"] : e => "ecomarket-${e}-images"}
{
"dev" = "ecomarket-dev-images"
"prod" = "ecomarket-prod-images"
"staging" = "ecomarket-staging-images"
}
# 4
> [for k, v in {dev = "a", staging = "b", prod = "c"} : k if k != "prod"]
[
"dev",
"staging",
]For point 5, by precedence: * before + gives 2 + 6 = 8; then > gives 8 > 7 = true; then && gives true && false = false; finally || gives false || true = **true**.
Solution 2:
In locals.tf (or inside main.tf):
locals {
# Sizing map: one row per environment, extensible without touching any logic.
sizing = {
dev = { instances = 1, retention = 7 }
staging = { instances = 2, retention = 14 }
prod = { instances = 3, retention = 30 }
}
# lookup with a default value: if an unknown environment turns up,
# it behaves like dev instead of blowing up.
current = lookup(local.sizing, var.environment, local.sizing["dev"])
is_production = var.environment == "prod"
planned_resources = [
"${local.prefix}-web",
"${local.prefix}-lb",
"${local.prefix}-db",
"${local.prefix}-images",
]
}In main.tf:
resource "local_file" "deployment_config" {
filename = "${path.module}/${local.prefix}-deploy.conf"
# <<-EOT strips the common indentation; the ~ tildes on the directives
# stop each %{ ... } from leaving a blank line in the result.
content = <<-EOT
# Deployment configuration for ${local.prefix}
project=${var.project}
environment=${var.environment}
region=${var.region}
instances=${local.current.instances}
retention_days=${local.current.retention}
production=${local.is_production}
[email protected]
# Planned resources
%{ for r in local.planned_resources ~}
resource=${r}
%{ endfor ~}
EOT
file_permission = "0644"
}Verification:
$ terraform fmt && terraform validate
Success! The configuration is valid.
$ terraform apply -auto-approve
local_file.deployment_config: Creating...
local_file.deployment_config: Creation complete after 0s [id=...]
$ cat ecomarket-dev-deploy.conf
# Deployment configuration for ecomarket-dev
project=ecomarket
environment=dev
region=eu-west-1
instances=1
retention_days=7
production=false
[email protected]
# Planned resources
resource=ecomarket-dev-web
resource=ecomarket-dev-lb
resource=ecomarket-dev-db
resource=ecomarket-dev-imagesNotice that production=false works because the bool is implicitly converted to string inside the interpolation. If you removed the ~ tildes from %{ for } and %{ endfor }, two blank lines would appear around the resource block.
Solution 3:
-
The three problems:
- The last line is invalid.
+in HCL is arithmetic addition, not string concatenation."${var.project}" + "-"tries to add two non-numeric strings and fails withInvalid operand: unsuitable value for left operand: a number is required. Concatenation is done with interpolation or withjoin(). - Unreadable nested conditionals, with a redundant final branch:
var.environment == "dev" ? "db.t3.micro" : "db.t3.micro"returns the same thing either way. var.environment == "prod" ? true : falseis tautological. The comparison already returns abool; the conditional is superfluous. On top of that there is the unnecessary interpolation"${var.project}".
- The last line is invalid.
-
Rewritten version:
locals {
# A single table with all the sizing per environment.
sizing = {
dev = {
class = "db.t3.micro"
retention = 7
multi_az = false
}
staging = {
class = "db.t3.small"
retention = 14
multi_az = false
}
prod = {
class = "db.t3.medium"
retention = 30
multi_az = true
}
}
db = lookup(local.sizing, var.environment, local.sizing["dev"])
class = local.db.class
retention = local.db.retention
multi_az = local.db.multi_az
# Correct concatenation: interpolation inside a single string.
name = "${var.project}-${var.environment}-db"
# Equivalent alternative:
# name = join("-", [var.project, var.environment, "db"])
}- Adding
sandboxin the original version forces you to modify three chains of nested conditionals in three different places, with the risk of forgetting one and having that environment silently inheritdev's values. In the map version it is enough to add one row:
The logic is untouched, the review diff is four lines long, and it is impossible to leave an attribute half-set, because the object's type forces you to fill in all three. In the next lesson we will turn precisely this map into a typed variable with map(object(...)), so that environments can be defined from outside the code.
Conclusion
You now command the complete grammar of HCL2:
- HCL2 is declarative and typed, designed for people; its
.tf.jsonequivalent exists for machine-generated code. - A block has a type, labels and a body; arguments take
=and nested blocks do not. - The type system distinguishes primitives, collections (
list,set,map) and structural types (object,tuple), plusnull; choosing well betweenlistandset, or betweenmapandobject, determines how your infrastructure behaves when it changes. - Strings support
${}interpolation, escapes ($${}for a literal${) and heredocs, with<<-EOTas the preferred form; the directives%{ if }and%{ for }generate conditional text, and the~tilde controls whitespace. - Operators have a defined precedence that is best made explicit with parentheses;
? :conditionals handle two cases and lookup maps handle the rest elegantly. forexpressions transform collections into lists or maps, with aniffilter and...grouping mode; the splat[*]is their shortcut for extracting attributes from lists.localsgive names to repeated or complex expressions and can depend on resources, but they are not configurable from outside.- The
terraformblock configures Terraform itself and accepts no expressions. terraform consoleis the laboratory where you verify all of the above, andterraform fmtenforces the canonical style without argument.
The language holds no more secrets, but a configuration that only uses locals is still rigid: for EcoMarket to deploy dev, staging and prod from the same code it needs a clear interface of inputs and outputs. In the next lesson, Variables and Outputs, we will take the variable block all the way — complex types such as map(object(...)), optional() attributes, validation rules with can() and regex(), sensitive values — and we will see the six ways of assigning values with their exact precedence order, plus the complete output block and how its values are consumed from outside Terraform.
