Terraform Functions
Terraform includes a rich set of built‑in functions that help you transform and combine values. Functions are used in expressions to manipulate strings, numbers, lists, maps, and more.
Common String Functions
- format:
format("Hello %s", name) - lower / upper:
lower("HELLO")→ "hello" - join:
join(",", ["a","b","c"])→ "a,b,c" - split:
split(",", "a,b,c")→ ["a","b","c"] - replace:
replace("foo", "f", "b")→ "boo"
Collection Functions
- length: number of items in a list or map.
- element: get element at index (with wrap).
- lookup: get map value with default.
- keys / values: returns list of keys or values from a map.
- merge: merges multiple maps.
locals {
merged = merge({ a = 1 }, { b = 2 }) # { a = 1, b = 2 }
}Numeric Functions
- max / min: returns largest/smallest number.
- ceil / floor: rounding up/down.
- pow:
pow(2, 3)→ 8.
Encoding and File Functions
- file: reads file contents as string.
- templatefile: renders a template file with variables.
- base64encode / base64decode.
Type Conversion Functions
- tostring, tonumber, tobool.
Example: Dynamic Tags with Functions
locals {
common_tags = {
Environment = var.env
Project = "demo"
}
name_prefix = "${lower(var.env)}-app"
instance_ids = [for i in range(3) : "${local.name_prefix}-${i}"]
}
output "name_prefix" {
value = local.name_prefix
}Two Minute Drill
- Terraform has built‑in functions for strings, collections, numbers, files, and encoding.
- Use
format,join,split,replacefor strings. - Use
length,element,lookup,mergefor collections. - Functions can be nested and used in any expression.
Need more clarification?
Drop us an email at career@quipoinfotech.com
