Terraform Tutorial · Terraform Language · Lesson 12 of 25
Terraform Functions
Terraform's built-in functions for strings, numbers, collections, encoding, files, dates and IP networks, with examples you can try in terraform console.
Calling functions
Terraform has no user-defined functions; it has a large built-in library (and, since 1.8, functions from
providers). Try them in terraform console:
upper("terraform")
format("%s-%03d", "web", 7)
join(", ", ["a", "b", "c"])
split(",", "x,y,z")
replace("hello world", "world", "camel")
Output
> upper("terraform")
"TERRAFORM"
> format("%s-%03d", "web", 7)
"web-007"
> join(", ", ["a", "b", "c"])
"a, b, c"
> split(",", "x,y,z")
tolist([
"x",
"y",
"z",
])
> replace("hello world", "world", "camel")
"hello camel"Run this on your computer — see “Get Started” for setup.
Collections
length(["a", "b", "c"])
merge({ a = 1 }, { b = 2, a = 9 })
lookup({ small = "t3.micro" }, "large", "t3.small")
flatten([["a"], ["b", "c"]])
distinct(["x", "y", "x"])
Output
> length(["a", "b", "c"])
3
> merge({ a = 1 }, { b = 2, a = 9 })
{
"a" = 9
"b" = 2
}
> lookup({ small = "t3.micro" }, "large", "t3.small")
"t3.small"
> flatten([["a"], ["b", "c"]])
[
"a",
"b",
"c",
]
> distinct(["x", "y", "x"])
tolist([
"x",
"y",
])Run this on your computer — see “Get Started” for setup.
Networking
cidrsubnet() carves subnets out of a network range, which is how most VPC modules compute subnet CIDRs:
cidrsubnet("10.0.0.0/16", 8, 0)
cidrsubnet("10.0.0.0/16", 8, 1)
cidrhost("10.0.1.0/24", 10)
[for i in range(3) : cidrsubnet("10.0.0.0/16", 8, i)]
Output
> cidrsubnet("10.0.0.0/16", 8, 0)
"10.0.0.0/24"
> cidrsubnet("10.0.0.0/16", 8, 1)
"10.0.1.0/24"
> cidrhost("10.0.1.0/24", 10)
"10.0.1.10"
> [for i in range(3) : cidrsubnet("10.0.0.0/16", 8, i)]
[
"10.0.0.0/24",
"10.0.1.0/24",
"10.0.2.0/24",
]Run this on your computer — see “Get Started” for setup.
Most used functions
| Category | Functions |
|---|---|
| Strings | format, join, split, replace, lower, upper, trimspace, substr |
| Collections | length, concat, merge, lookup, contains, flatten, distinct, keys, values, zipmap |
| Encoding | jsonencode, jsondecode, yamlencode, base64encode |
| Files | file, templatefile, fileexists |
| Network | cidrsubnet, cidrhost, cidrnetmask |
| Type conversion | tostring, tonumber, toset, tolist, try, can |
Test yourself
Which function combines two maps, with later keys winning?
concatmergeflattenzipmap
Show answer
Answer: merge