Table of Contents

Terraform Built-in Functions Reference

Terraform includes dozens of built-in functions. Here are the most commonly used ones with practical examples.

String Functions

upper("hello")                    # "HELLO"
lower("HELLO")                    # "hello"
title("hello world")              # "Hello World"
trimspace("  hello  ")            # "hello"
replace("hello", "l", "r")       # "herro"
substr("hello", 0, 3)            # "hel"
join(", ", ["a", "b", "c"])       # "a, b, c"
split(",", "a,b,c")              # ["a", "b", "c"]
format("Hello, %s! You are %d.", "World", 42)  # "Hello, World! You are 42."
regex("(\\d+)", "port-8080")     # "8080"
startswith("hello", "he")        # true
endswith("hello.tf", ".tf")      # true

Numeric Functions

min(1, 2, 3)        # 1
max(1, 2, 3)        # 3
ceil(4.2)            # 5
floor(4.8)           # 4
abs(-5)              # 5
pow(2, 8)            # 256
parseint("FF", 16)   # 255

Collection Functions

length(["a", "b", "c"])                  # 3
contains(["a", "b"], "a")                # true
concat(["a"], ["b"], ["c"])              # ["a", "b", "c"]
flatten([["a", "b"], ["c"]])             # ["a", "b", "c"]
distinct(["a", "b", "a"])                # ["a", "b"]
sort(["c", "a", "b"])                    # ["a", "b", "c"]
reverse(["a", "b", "c"])                 # ["c", "b", "a"]
element(["a", "b", "c"], 1)              # "b"
index(["a", "b", "c"], "b")              # 1
lookup({a = 1, b = 2}, "a", 0)           # 1
merge({a = 1}, {b = 2})                  # {a = 1, b = 2}
keys({a = 1, b = 2})                     # ["a", "b"]
values({a = 1, b = 2})                   # [1, 2]
zipmap(["a", "b"], [1, 2])               # {a = 1, b = 2}

Type Conversion

tostring(42)          # "42"
tonumber("42")        # 42
tobool("true")        # true
tolist(toset(["a"]))  # ["a"]
toset(["a", "a"])     # ["a"]
tomap({a = 1})        # {a = 1}

Encoding Functions

jsonencode({name = "test"})       # '{"name":"test"}'
jsondecode("{\"name\":\"test\"}")  # {name = "test"}
yamlencode({name = "test"})       # "name: test\n"
base64encode("hello")             # "aGVsbG8="
base64decode("aGVsbG8=")          # "hello"
urlencode("hello world")          # "hello+world"

Filesystem Functions

file("${path.module}/script.sh")             # Read file contents
fileexists("${path.module}/config.json")     # true/false
templatefile("${path.module}/user-data.tftpl", { name = "web" })
filebase64("${path.module}/binary.zip")      # Base64-encoded file

IP Network Functions

cidrhost("10.0.0.0/24", 5)           # "10.0.0.5"
cidrnetmask("10.0.0.0/24")           # "255.255.255.0"
cidrsubnet("10.0.0.0/16", 8, 1)      # "10.0.1.0/24"
cidrsubnets("10.0.0.0/16", 8, 8, 8)  # ["10.0.0.0/24", "10.0.1.0/24", "10.0.2.0/24"]

Date and Time

timestamp()                          # "2025-01-15T12:00:00Z"
timeadd(timestamp(), "24h")          # 24 hours from now
formatdate("YYYY-MM-DD", timestamp()) # "2025-01-15"

Learn More