What are Functions?

Built-in functions to transform and combine values inside expressions.

# Syntax
function_name(argument1, argument2, ...)

# Example
max(5, 12, 9)  # Returns 12

String Functions

locals {
  name = "Hello World"
  str  = "  hello  "
}

lower(local.name)                   # "hello world"     - all lowercase
upper(local.name)                   # "HELLO WORLD"     - all uppercase
startswith(local.name, "Hello")     # true              - starts with "Hello"?
trimspace(local.str)                # "hello"           - removes spaces
split("-", "a-b-c")                 # ["a", "b", "c"]  - string to list
join("-", ["a", "b", "c"])          # "a-b-c"           - list to string

List Functions

variable "my_list" {
  default = ["a", "b", "c", "a"]
}

length(var.my_list)             # 4        - count of items
contains(var.my_list, "b")      # true     - does list have "b"?
toset(var.my_list)              # {"a","b","c"}  - removes duplicates
tolist(toset(var.my_list))      # ["a","b","c"]  - set back to list

Map Functions

variable "map1" { default = { a = 1 } }
variable "map2" { default = { b = 2 } }

merge(var.map1, var.map2)       # { a = 1, b = 2 }  - combine maps

Number Functions

max(1, 2, 3)       # 3   - highest value
min(1, 2, 3)       # 1   - lowest value
abs(-5)            # 5   - absolute value (remove negative)

Real Usage Example

locals {
  raw_name   = "  MY SERVER  "
  tags_list  = ["dev", "web", "prod", "dev"]  # has duplicate

  # Clean up name
  clean_name = lower(trimspace(local.raw_name))   # "my server"

  # Remove duplicate tags
  unique_tags = toset(local.tags_list)            # {"dev","web","prod"}

  # Join list into a string
  tag_string  = join(", ", tolist(local.unique_tags))  # "dev, prod, web"
}

Quick Reference