Terraform Built-in Functions

Terraform functions perform specific tasks on the data within the configuration files:

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.
  • max: Return the largest value in a list.
  • min: Return the smallest value in a list.
  • parseInt: Convert a string to an integer.
  • 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: Format a list of values into a single string.
  • 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 leading and trailing whitespace from a string.
  • trimprefix: Remove a specific prefix from a string.
  • trimsuffix: Remove a specific suffix from a string.
  • trimspace: Remove all internal 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 non-null value in a list.
  • coalescelist: Combine multiple lists, ignoring empty ones.
  • compact: Remove all null values from a list.
  • concat: Combine multiple lists or maps into a single list or map.
  • 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 or map.
  • list: Convert a single value or map into a list.
  • lookup: Access a specific value within a map by key.
  • map: Convert a list of key-value pairs into a map.
  • matchkeys: Find keys in a map that match a specific pattern.
  • 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 based on a specified criteria.
  • sum: Calculate the sum of all numeric elements in a list.
  • transpose: Swap the rows and columns of a matrix.
  • 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 JSON-encoded data into a map.
  • jsonencode: Encode a map or list into JSON format.
  • textdecodebase64: Decode base64-encoded text data.
  • textencodebase64: Encode text data in base64 format.
  • urlencode: Encode a string for safe inclusion in URLs.
  • yamldecode: Decode YAML-encoded data into a map.
  • yamlencode: Encode a map or list into YAML format.

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 environment variables and tilde (~) within a file path.
  • basename: Extract the filename part of a file path without the 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: Generate a timestamp based on the current time or a specific date and time.

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: Extract the network address from a CIDR block.
  • cidrnetmask: Extract the netmask from a CIDR block.
  • cidrsubnet: Divide a CIDR block into multiple subnets of a specified size.
  • cidrsubnets: Generate a list of subnets within a CIDR block.

Type Conversion

Convert values between different data types like strings, numbers, and maps.

  • can: Check if a specific conversion function is available for a given type.
  • insensitive: Perform case-insensitive comparisons and string operations.
  • sensitive: Perform case-sensitive comparisons and string operations.
  • 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: Attempt a conversion and return null if it fails.
  • type: Get the type of a value (string, number, etc.).

Leave a Reply

Your email address will not be published. Required fields are marked *


Related Cloud Tutorials

Securing your Infrastructure: Encrypting Terraform State Files with OpenTofu
Using the Terraform aws_route53_delegation_set, aws_route53_zone, and aws_route53_record resource blocks to configure DNS in AWS.
Using the Terraform aws_db_instance resource block to configure, launch, and secure RDS instances.
How to use the Terraform aws_instance resource block to configure, launch, and secure EC2 instances.
How to configure and use the Terraform aws_ami data source block to find and use AWS AMIs as templates (root volume snapshot with operating system and applications) for EC2 instances.
Javier Ruiz Cloud and SaaS Expert

Javier Ruiz

IT Wonder Lab tutorials are based on the diverse experience of Javier Ruiz, who founded and bootstrapped a SaaS company in the energy sector. His company, later acquired by a NASDAQ traded company, managed over €2 billion per year of electricity for prominent energy producers across Europe and America. Javier has over 25 years of experience in building and managing IT companies, developing cloud infrastructure, leading cross-functional teams, and transitioning his own company from on-premises, consulting, and custom software development to a successful SaaS model that scaled globally.

Are you looking for cloud automation best practices tailored to your company?

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram