Built in Functions

Terraform provides many built in functions. These functions can be called by functionname() inside ${}. For example, ${file(config.txt)} will read the content of the file.

A list of commonly used functions,

Function

Description

Example

basename(path)

Returns filename of the a path

basename("/home/isuru/file.txt") returns file.txt

coalesce(string1, string2, ...)

Returns the first non empty value

coalsec("", "", "hello")

coalescelist(list1, list2, ...)

Returns the first non empty list

"

element(list, index)

Returns a single element from a list at the given index

element(module.vpc.public_subnet, count.index)

format(format, args, ...)

Formats a string/list according to the given format

format("server-%03d, count.index + 1) returns server-001, server-002

index(list, elem)

Finds the index of a given element in a list

index(aws_instance.foo.*.tags.Env, "prod")

join(delim, list)

Joins a list together with a delimiter

join(",", var.AMIS) returns "ami-123, ami-456, ami-789"

list(item1, item2, ...)

create a new list

join(":", list("a", "b", "c")) returns a:b:c

lookup(map, key, [default])

Perform a lookup on a map, using "key". Returns value representing "key" in the map(lookup("k", "v"), "k", "not found") returns "v"

lower(string)

returns lowercase value of "string"

lower("Hello") returns hello

map(key, value)

returns a new map using key:value

map("k", "v", "k2", "v2") returns: {"k" = "v", "k2" = "v2"}

merge(map1, map2, ...)

Merge maps(union)

merge(map("k", "v"), map("k2", "v2")) returns: {"k" = "v", "k2" = "v2"}

replace(string, search, replace)

Returns a search and replace on string

replace("aaab", "a", "b") returns bbbb

split(delim, string)

splits a string into a list

split(",", "a,b,c,d") returns ["a", "b", "c", "d"]

substr(string, offset, length)

Extract substring from string

substr("abcd", -3, 3)returns cde

timestamp()

returns RFC 3339 timestamp

"Server started at ${timestamp()}" Server started at 2021-05-27T10:42:46Z

uppser(string)

Returns uppsecased string

upper('string') returns STRING

uuid()

Returns a UUID string in RFC 4122 v4 format

uuid() returns: c5f44842-beaa-11eb-8529-0242ac130003

values(map)

returns values of a map

values(map("k", "v", "k2", "v2")) returns["v", "v2"]

Last updated