HCL: the Terraform language
Read and write HCL with confidence: blocks, arguments and references, the value types, and expressions such as conditionals, for loops and functions, tried live in terraform console.
By the end of this lesson you'll be able to
0 of 4 completeVerified lab: every terraform console expression and the apply order shown. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: none.
Cloud lab: none; nothing here needs a cloud account.
Every Terraform file is written in HCL, the HashiCorp Configuration Language. It's
deliberately small: a few kinds of blocks, values and expressions. Once you can read it, every
Terraform project in the world looks familiar. This lesson covers the grammar; you'll test
expressions live in terraform console.
Syntax
A Terraform project is a folder of files ending in .tf. Terraform reads all of them
together, in no particular order, so splitting code into main.tf, variables.tf and
outputs.tf is purely for people. A few rules cover almost everything:
- Blocks hold configuration:
resource "..." "..." { ... }. - Arguments set a value inside a block:
filename = "out.txt". - Comments use
#(preferred),//, or/* ... */for several lines. - Strings go in double quotes, and
${...}inside a string inserts a value:"web-${var.env}". - Multi-line strings use a heredoc:
<<-EOT ... EOT(the-strips leading indentation). - Order doesn't matter. Terraform works out what to do first from references, not from the order you wrote things.
Blocks and arguments
This is the configuration used through the course:
# main.tf resource "random_pet" "server" { length = 2 } resource "local_file" "inventory" { filename = "${path.module}/out/inventory.txt" content = "server: ${random_pet.server.id}\n" }
Read the second block part by part:
resourceis the block type. Others you'll meet:terraform,provider,variable,output,locals,dataandmodule."local_file"is the resource type. The part before the underscore names the provider (local), the rest names the thing (file)."inventory"is your local name. Together they form the addresslocal_file.inventory, unique within the folder.filename = ...andcontent = ...are arguments. Which arguments exist, and which are required, is defined by the provider; its page on the Terraform Registry lists them.path.moduleis a built-in value: the folder this file is in.
References build the order
content uses random_pet.server.id, an attribute of another resource. That one reference tells
Terraform two things: it needs the pet name to write the file, so it must create random_pet.server
first. The apply output from the lab shows exactly that order:
random_pet.server: Creating... random_pet.server: Creation complete after 0s [id=model-kiwi] local_file.inventory: Creating... local_file.inventory: Creation complete after 0s [id=e041d7cb3c1d1c469796feb23dcb0459b375560d]
Anything you can read on a resource after it's created, such as an id, an IP address or an ARN,
is an attribute, and the provider docs list them under "Attribute Reference".
Types and expressions
Value types
| Type | Example | Use for |
|---|---|---|
string | "ap-south-1" | Names, IDs, regions |
number | 8080, 0.5 | Ports, counts, sizes |
bool | true | Feature switches |
list(...) | ["web", "api"] | Ordered values |
map(...) | { dev = "t3.micro", prod = "t3.large" } | Lookups by key |
set(...) | toset(["a", "b"]) | Unique, unordered values (used by for_each) |
object({...}) | { name = "web", port = 8080 } | A record with named, typed fields |
null means "leave this argument unset", as if you hadn't written it.
terraform console
terraform console evaluates expressions interactively, using your project's variables and state.
It's the fastest way to learn HCL. Everything below ran on Terraform 1.17.1:
> 1 + 2 * 3 7 > "web-${1 + 1}" "web-2" > upper("ap-south-1") "AP-SOUTH-1" > length(["web", "api", "db"]) 3 > type({ name = "web", port = 8080 }) object({ name: string, port: number, })
Terraform worked out the type of that object literal itself: an object with a string and a number.
Conditionals
> true ? "yes" : "no" "yes" > contains(["t3.micro", "t3.small"], "t3.large") false
The form is condition ? value_if_true : value_if_false, for example
instance_type = var.env == "prod" ? "t3.large" : "t3.micro". Both results must have the same type.
for expressions
A for expression transforms a collection. Square brackets build a list, curly braces build a map:
> [for s in ["web", "api", "db"] : "${s}-prod"] [ "web-prod", "api-prod", "db-prod", ] > { for s in ["web", "api"] : s => length(s) } { "api" = 3 "web" = 3 }
Add if to filter: [for s in var.names : s if s != "test"].
Functions
Terraform has over a hundred built-in functions, and you can't write your own. The ones you'll use weekly:
> merge({ team = "shop" }, { env = "prod" }) { "env" = "prod" "team" = "shop" } > lookup({ dev = "t3.micro", prod = "t3.large" }, "prod", "t3.nano") "t3.large" > cidrsubnet("10.0.0.0/16", 8, 2) "10.0.2.0/24" > join(",", ["10.0.1.0/24", "10.0.2.0/24"]) "10.0.1.0/24,10.0.2.0/24" > jsonencode({ port = 8080, tls = true }) "{\"port\":8080,\"tls\":true}"
cidrsubnet("10.0.0.0/16", 8, 2) means "add 8 bits to the prefix (so /24) and take subnet number
2", which is how VPC modules carve subnets without hand-typed CIDRs. merge is the usual way to
combine a set of common tags with resource-specific ones.
A splat aws_instance.web[*].id collects one attribute from every instance of a resource made
with count. A dynamic block generates repeated nested blocks (such as many ingress rules)
from a list. Use dynamic blocks sparingly: they make code harder to read.
Answer five questions with terraform console
In any initialised folder, use terraform console to work out: the region name in upper case, a list of prod server names from ['web', 'api', 'db'], a map of each name to its length, the fourth /24 subnet of 10.0.0.0/16, and the instance type for prod from a map with a default. Save each expression and its answer.
~/hcl-answers.txtReveal one safe solution
$ for e in 'upper("ap-south-1")' '[for s in ["web","api","db"] : "${s}-prod"]' \ '{ for s in ["web","api","db"] : s => length(s) }' 'cidrsubnet("10.0.0.0/16", 8, 3)' \ 'lookup({ dev = "t3.micro", prod = "t3.large" }, "prod", "t3.nano")'; do echo "> $e"; echo "$e" | terraform console; done > ~/hcl-answers.txt $ cat ~/hcl-answers.txt
for e in 'upper("ap-south-1")' '[for s in ["web","api","db"] : "${s}-prod"]' \forloop over a list
cat ~/hcl-answers.txtcatprint a file
The subnet answer should be "10.0.3.0/24" (subnet numbers start at 0). If console complains about
a missing provider, run terraform init in that folder first.
Try it yourself
0 of 5 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
In resource "local_file" "inventory" { ... }, what is "inventory"?
Official reading for this lesson
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.