
Function categories and syntax
Terraform functions follow a consistent, predictable syntax: function_name(argument1, argument2, …) They accept one or more arguments and return a computed value. In practice you will usually pass variables, locals, or data source attributes into functions instead of hard-coded literals. Examples:
Numeric functions
Numeric helpers are useful for resource sizing, capacity planning, and simple arithmetic without hard-coding values. Common functions:- max(…) — returns the largest numeric argument
- min(…) — returns the smallest numeric argument
- floor(…) — round down to nearest integer
- ceil(…) — round up to nearest integer
String functions
String manipulation is essential for building resource names, templating startup scripts, or encoding user data consistently. Common string functions:- join(separator, list) — concatenates a list of strings
- split(separator, string) — splits a string into a list
- upper(string) / lower(string) — change case
- replace(string, search, replace) — substitute substrings
- base64encode(string) — encode a string to Base64 (useful for user data)
Network functions (CIDR helpers)
Terraform includes CIDR helpers so you can programmatically calculate subnets and host IPs instead of performing error-prone manual math. Key functions:- cidrsubnet(prefix, newbits, netnum) — extend prefix length by newbits, then select netnum-th subnet
- cidrhost(prefix, hostnum) — return a single host IP within the given CIDR
cidrhost() similarly to derive a specific host address inside a CIDR block.
Type conversion and collection helpers
Conversion functions ensure data structures are in the correct format for iteration, lookups, and uniqueness rules. Common conversions:- tolist(…) — convert to list
- toset(…) — convert to set (enforces uniqueness)
- tomap(…) — convert to map
- tostring(…) — convert to string
- distinct(list) — remove duplicates while preserving first-seen order
- tonumber(string) — convert string to number
- ensures uniqueness via
distinct() - preserves predictable ordering
- exposes an index (converted back to a number with
tonumber(each.key)) for use withcidrsubnet
Tip: Prefer
distinct() when you need to remove duplicate values but keep the original ordering. Use toset() when order doesn’t matter and you only care about uniqueness.Watch out for type mismatches (e.g., passing a list where a map is expected). Use
tolist(), tomap(), or tostring() explicitly to avoid errors in expressions and for_each.Summary
Built-in Terraform functions let you:- Reduce repetition and enforce consistent naming, tagging, and sizing
- Convert safely between collection types (lists, sets, maps) for predictable iteration
- Avoid manual network math with CIDR helpers like
cidrsubnet()andcidrhost() - Encode and transform strings (e.g.,
base64encode()) for user data and configuration