Terraform Built-in Functions
Terraform functions perform specific tasks on the data within the configuration files. OpenTofu has the same functions and a few more (see the OpenTofu functions). Try them with terraform console or tofu console, as shown in Terraform Tools. The functions list and map of older Terraform versions were removed: use tolist and tomap, or the literal syntax [ ] and { }.
Numeric Functions #
Perform mathematical operations like calculations, comparisons, and conversions on numbers.
- abs: Calculate absolute value.
- ceil: Round up to the nearest integer.
- floor: Round down to the nearest integer.
- log: Compute the logarithm of a number in a given base.
- max: Return the largest of the given numbers (use
...to expand a list). - min: Return the smallest of the given numbers (use
...to expand a list). - parseint: Parse a string as an integer in a given base.
- pow: Raise a number to a power.
- signum: Determine the sign of a number (-1, 0, or 1).
String Functions #
Manipulate text data, including formatting, searching, and transformations.
- chomp: Remove trailing newline characters.
- endswith: Check if a string ends with a specific substring.
- format: Apply formatting placeholders to a string.
- formatlist: Produce a list of strings by formatting each element of the given lists.
- indent: Add whitespace indentation to a string.
- join: Combine strings into a single string with a separator.
- lower: Convert all characters to lowercase.
- regex: Perform regular expression matching and extraction.
- regexall: Find all occurrences of a regular expression pattern.
- replace: Substitute one substring with another within a string.
- split: Divide a string into a list of substrings based on a delimiter.
- startswith: Check if a string starts with a specific substring.
- strcontains: Check if a substring is present within a string.
- strrev: Reverse the order of characters in a string.
- substr: Extract a specific substring from a string.
- title: Capitalize the first letter of each word in a string.
- trim: Remove the specified characters from the start and the end of a string.
- trimprefix: Remove a specific prefix from a string.
- trimsuffix: Remove a specific suffix from a string.
- trimspace: Remove leading and trailing whitespace from a string.
- upper: Convert all characters to uppercase.
Collection Functions #
Work with lists and maps, performing tasks like filtering, sorting, and aggregation.
- alltrue: Check if all elements in a list are true.
- anytrue: Check if any element in a list is true.
- chunklist: Divide a list into sublists of a specified size.
- coalesce: Return the first argument that is neither null nor an empty string.
- coalescelist: Return the first list that is not empty.
- compact: Remove empty strings from a list of strings.
- concat: Combine two or more lists into a single list (use
mergefor maps). - contains: Check if a list contains a specific element.
- distinct: Remove duplicate elements from a list.
- element: Access a specific element within a list by index.
- flatten: Merge sublists within a list into a single, flat list.
- index: Find the position of an element within a list.
- keys: Extract the keys from a map.
- length: Get the number of elements in a list, map or set, or the length of a string.
- lookup: Access a specific value within a map by key.
- matchkeys: Select the values of a list by matching a second list of keys against a list of allowed keys.
- merge: Combine multiple maps into a single map, overriding conflicting keys.
- one: Extract the only element from a list, ensuring its length is 1.
- range: Generate a list of numbers in a specified range.
- reverse: Reverse the order of elements in a list.
- setintersection: Find the common elements between multiple sets.
- setproduct: Combine multiple sets by Cartesian product.
- setsubtract: Remove elements from one set that are present in another.
- setunion: Combine multiple sets into a single set, removing duplicates.
- slice: Extract a sublist from a list based on specific indices.
- sort: Sort a list of strings in lexicographical order.
- sum: Calculate the sum of all numeric elements in a list.
- transpose: Swap the keys and the values of a map of lists of strings.
- values: Extract the values from a map.
- zipmap: Combine two lists into a map, pairing elements at corresponding indices.
Encoding Functions #
Encode and decode data in different formats like base64, JSON, and YAML.
- base64decode: Decode base64-encoded data.
- base64encode: Encode data in base64 format.
- base64gzip: Compress and encode data with base64.
- csvdecode: Decode comma-separated values (CSV) data into a list of maps.
- jsondecode: Decode a JSON string into a value (object, list or primitive).
- jsonencode: Encode any value as a JSON string.
- textdecodebase64: Decode base64-encoded text data.
- textencodebase64: Encode text data in base64 format.
- urlencode: Encode a string for safe inclusion in URLs.
- yamldecode: Decode a YAML string into a value.
- yamlencode: Encode any value as a YAML string.
File System Functions #
Interact with files and directories, reading contents, checking existence, and manipulating paths.
- abspath: Get the absolute path of a file based on the current working directory.
- dirname: Extract the directory part of a file path.
- pathexpand: Expand a leading tilde (~) in a file path to the home directory of the current user.
- basename: Extract the last element of a file path (the file name, including its extension).
- file: Read the contents of a file as a string.
- fileexists: Check if a file exists at a specific path.
- fileset: Enumerate files within a directory based on patterns and glob.
- filebase64: Encode the contents of a file in base64 format.
- templatefile: Render a template file with embedded variables and interpolation.
Date and Time Functions #
Work with timestamps and dates, formatting them, adding durations, and comparing them.
- formatdate: Convert a timestamp to a string in a specific format.
- plantimestamp: Get the timestamp of the current Terraform plan execution.
- timeadd: Add a duration to a timestamp or time string.
- timecmp: Compare two timestamps or time strings for chronological order.
- timestamp: Return the current UTC date and time in RFC 3339 format.
Hash and Crypto Functions #
Generate secure hashes and cryptographic operations for data security.
- base64sha256: Generate a base64-encoded SHA-256 hash of data.
- base64sha512: Generate a base64-encoded SHA-512 hash of data.
- bcrypt: Generate a password hash using bcrypt algorithm.
- filebase64sha256: Calculate the base64-encoded SHA-256 hash of a file’s contents.
- filebase64sha512: Calculate the base64-encoded SHA-512 hash of a file’s contents.
- filemd5: Generate an MD5 hash of a file’s contents.
- filesha1: Generate an SHA-1 hash of a file’s contents.
- filesha256: Generate an SHA-256 hash of a file’s contents.
- filesha512: Generate an SHA-512 hash of a file’s contents.
- md5: Generate an MD5 hash of data.
- rsadecrypt: Decrypt data using RSA private key.
- sha1: Generate an SHA-1 hash of data.
- sha256: Generate an SHA-256 hash of data.
- sha512: Generate an SHA-512 hash of data.
- uuid: Generate a universally unique identifier (UUID).
- uuidv5: Generate a UUID based on a namespace and name.
IP Network Functions #
Work with CIDR blocks, extracting addresses, netmasks, and generating subnets.
- cidrhost: Calculate a full host IP address for a given host number within a CIDR block.
- cidrnetmask: Extract the netmask from a CIDR block.
- cidrsubnet: Divide a CIDR block into multiple subnets of a specified size.
- cidrsubnets: Calculate a sequence of consecutive subnets within a CIDR block.
Type Conversion #
Convert values between different data types like strings, numbers, and maps.
- can: Evaluate an expression and return true if it produces no error.
- nonsensitive: Remove the sensitive mark from a value, so it can be shown in the output.
- sensitive: Mark a value as sensitive, so it is hidden in the plan and in the output.
- tobool: Convert a value to a boolean (true or false).
- tolist: Convert a value to a list.
- tomap: Convert a value to a map.
- tonumber: Convert a value to a number.
- toset: Convert a value to a set.
- tostring: Convert a value to a string.
- try: Evaluate the expressions in order and return the result of the first one that does not produce an error.
- type: Return the type of a value (only available in
terraform console).