Expressions & Built-in Functions
HCL has no user-defined functions in plain .tf files and no statements, only expressions. Yet with conditionals, for expressions, splats and about a hundred built-in functions you can reshape almost any data. Everything in this lesson runs in tofu console.
Conditionals, for expressions and splats
mkdir x && cd x
cat > main.tf <<'HCL'
locals {
env = "prod"
azs = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
users = {
ada = { team = "platform", admin = true }
grace = { team = "data", admin = false }
linus = { team = "platform", admin = false }
}
servers = [
{ name = "web-1", ip = "10.0.1.10" },
{ name = "web-2", ip = "10.0.1.11" },
]
}
HCL
tofu console <<'EXPR'
local.env == "prod" ? 3 : 1
[for az in local.azs : upper(az)]
[for i, az in local.azs : "${i}:${az}"]
{for name, u in local.users : name => u.team}
[for name, u in local.users : name if u.admin]
{for name, u in local.users : u.team => name...}
local.servers[*].ip
EXPR3
[
"EU-WEST-1A",
"EU-WEST-1B",
"EU-WEST-1C",
]
[
"0:eu-west-1a",
"1:eu-west-1b",
"2:eu-west-1c",
]
{
"ada" = "platform"
"grace" = "data"
"linus" = "platform"
}
[
"ada",
]
{
"data" = [
"grace",
]
"platform" = [
"ada",
"linus",
]
}
[
"10.0.1.10",
"10.0.1.11",
]
cond ? a : b: both branches must have compatible types.[for … : …]builds a list,{for … : k => v}a map;iffilters; with a list, two symbols give index and value....after the value groups duplicates: one team, many names. Without it, a duplicate key is an error.x[*].attr(splat) is shorthand for[for o in x : o.attr], and the usual way to collect ids fromcountinstances:aws_subnet.private[*].id.
Functions you'll use every day
mkdir f && cd f
cat > main.tf <<'HCL'
locals {
vpc_cidr = "10.20.0.0/16"
base = { Project = "linkly", ManagedBy = "opentofu" }
}
HCL
tofu console <<'EXPR'
cidrsubnet(local.vpc_cidr, 8, 0)
[for i in range(3) : cidrsubnet(local.vpc_cidr, 8, i + 10)]
cidrhost("10.20.1.0/24", 5)
merge(local.base, { Environment = "dev" })
lookup({ dev = "t3.micro", prod = "m7g.large" }, "staging", "t3.small")
try(local.base.Owner, "unknown")
coalesce("", "fallback")
format("%s-%03d", "web", 7)
join(",", ["a", "b", "c"])
zipmap(["a", "b"], [1, 2])
flatten([["x"], ["y", "z"]])
jsonencode({ port = 8080, tls = true })
yamldecode("replicas: 3\nimage: linkly:1.4.0")
EXPR"10.20.0.0/24"
[
"10.20.10.0/24",
"10.20.11.0/24",
"10.20.12.0/24",
]
"10.20.1.5"
{
"Environment" = "dev"
"ManagedBy" = "opentofu"
"Project" = "linkly"
}
"t3.small"
"unknown"
"fallback"
"web-007"
"a,b,c"
{
"a" = 1
"b" = 2
}
[
"x",
"y",
"z",
]
"{\"port\":8080,\"tls\":true}"
{
"image" = "linkly:1.4.0"
"replicas" = 3
}
| Group | Functions |
|---|---|
| Network | cidrsubnet, cidrsubnets, cidrhost, cidrnetmask |
| Collections | merge, lookup, concat, flatten, distinct, keys, values, zipmap, setproduct, contains, length, slice |
| Strings | format, join, split, replace, regex, lower/upper, trimspace, startswith |
| Encoding | jsonencode/jsondecode, yamlencode/yamldecode, base64encode, templatefile |
| Errors | try, can, coalesce |
| Files | file, fileset, templatefile, filebase64sha256 (paths relative to path.module) |
cidrsubnet(prefix, newbits, netnum) deserves a closer look: it adds newbits bits to the prefix (/16 + 8 = /24) and picks subnet number netnum. It is how the VPC lesson carves subnets without a spreadsheet.
Templates
templatefile(path, vars) renders a file with ${…} interpolation and %{ for }/%{ if } directives: user data scripts, config files, policies.
mkdir t && cd t
cat > nginx.conf.tftpl <<'TPL'
upstream app {
%{ for ip in backends ~}
server ${ip}:8080;
%{ endfor ~}
}
TPL
cat > main.tf <<'HCL'
resource "local_file" "nginx" {
filename = "nginx.conf"
content = templatefile("${path.module}/nginx.conf.tftpl", { backends = ["10.0.1.10", "10.0.1.11"] })
}
HCL
tofu init >/dev/null && tofu apply -auto-approve >/dev/null
cat nginx.confupstream app {
server 10.0.1.10:8080;
server 10.0.1.11:8080;
}
The ~ strips the whitespace and newline next to a directive, so the loop leaves no blank lines. The .tftpl extension is a convention editors recognise.
Note: OpenTofu 1.7+ can also call functions from providers (
provider::<name>::<function>(…)), as can Terraform 1.8+. For example, the AWS provider shipsprovider::aws::arn_parse.
Test yourself
What is cidrsubnet("10.0.0.0/16", 8, 3)?
- 10.0.3.0/24
- 10.0.0.3/16
- 10.3.0.0/16
- 10.0.0.0/19
Which expression builds a map from team to the list of user names in that team?
{for n, u in local.users : u.team => n}{for n, u in local.users : u.team => n...}[for n, u in local.users : u.team]local.users[*].team
try(local.base.Owner, "unknown") returns what when Owner doesn't exist?
- An error
- null
- "unknown"
- An empty string