Master Terraform Functions, Expressions, and Meta-Arguments for Powerful IaC
This guide walks through Terraform's built‑in functions for strings, numbers, lists, and maps, explains conditional expressions, string interpolation, template rendering, and demonstrates how to use the count and for_each meta‑arguments to create flexible, reusable infrastructure configurations.
Built-in Functions
String Functions
lower(string)– converts a string to lowercase. upper(string) – converts a string to uppercase. trimspace(string) – removes leading and trailing whitespace. split(separator, string) – splits a string into a list using the given separator. join(separator, list) – joins a list of strings into a single string with the separator. replace(string, substring, replacement) – replaces occurrences of a substring with another string. substr(string, offset, length) – extracts a substring. format(format, args...) – formats a string according to a format pattern. startswith(string, prefix) – returns true if the string starts with the given prefix. endswith(string, suffix) – returns true if the string ends with the given suffix. contains(string, substring) – returns true if the string contains the substring.
Numeric Functions
min(num1, num2, ...)– returns the smallest value. max(num1, num2, ...) – returns the largest value. ceil(num) – rounds a number up. floor(num) – rounds a number down. round(num) – rounds a number to the nearest integer. abs(num) – returns the absolute value. parseint(string, base) – parses a string as an integer of the given base.
List Functions
length(list)– returns the length of a list. element(list, index) – returns the element at the given index. slice(list, start, end) – returns a sub‑list from start to end (exclusive). concat(list1, list2, ...) – concatenates multiple lists. contains(list, element) – checks whether a list contains an element. distinct(list) – returns a list of unique values while preserving order. index(list, element) – returns the index of an element or -1 if not found. reverse(list) – returns a list with elements in reverse order. sort(list) – returns a sorted copy of the list.
Map Functions
length(map)– returns the number of key‑value pairs. keys(map) – returns a list of all keys. values(map) – returns a list of all values. merge(map1, map2, ...) – merges maps; later maps overwrite earlier keys. lookup(map, key, default) – returns the value for a key or the default if the key is missing.
Other Common Functions
file(path)– reads the contents of a file. timestamp() – returns the current timestamp. uuid() – generates a UUID. jsonencode(value) – encodes a value as a JSON string. jsondecode(string) – decodes a JSON string into a Terraform value. base64encode(string) – encodes a string in Base64. base64decode(string) – decodes a Base64‑encoded string. cidrhost(prefix, hostnum) – calculates an IP address from a CIDR prefix. coalesce(arg1, arg2, ...) – returns the first non‑null argument.
Function call example:
output "example" {
value = {
lower_string = lower("HELLO") # "hello"
upper_string = upper("world") # "WORLD"
joined_string = join("-", ["a", "b", "c"]) # "a-b-c"
file_content = file("${path.module}/example.txt")
current_time = timestamp()
instance_count = length(var.instance_ids)
subnet_ip = cidrhost("10.0.0.0/16", 4) # "10.0.0.4"
}
}Conditional Expressions
Terraform supports the ternary syntax condition ? true_val : false_val. If condition evaluates to true, the expression yields true_val; otherwise it yields false_val.
Example:
variable "environment" {
type = string
default = "dev"
}
resource "aws_instance" "example" {
ami = "ami-0c55b31ad2299a796"
instance_type = var.environment == "prod" ? "t3.medium" : "t2.micro"
tags = {
Name = "example-${var.environment}"
}
}String Interpolation and Templates
Interpolation uses ${...} inside strings to reference variables, functions, or expressions.
Interpolation example:
variable "region" {
type = string
default = "ap-southeast-1"
}
output "message" {
value = "The current region is ${var.region}"
}
output "example" {
value = "The instance count is ${length(aws_instance.example)}, and the first instance ID is ${element(aws_instance.example.*.id, 0)}"
}The templatefile function renders an external file with interpolation and control structures ( %{if}, %{for}, etc.).
Templatefile example:
# user_data.tpl
#!/bin/bash
echo "Hello, ${username}!"
echo "The current time is ${timestamp}"
# main.tf
resource "aws_instance" "example" {
ami = "ami-0c55b31ad2299a796"
instance_type = "t2.micro"
user_data = templatefile("${path.module}/user_data.tpl", {
username = "World"
timestamp = timestamp()
})
}count and for_each Meta‑Arguments
count
counttakes an integer and creates that many resource instances. Each instance can be referenced via count.index.
Example – creating three EC2 instances:
resource "aws_instance" "example" {
count = 3
ami = "ami-0c55b31ad2299a796"
instance_type = "t2.micro"
tags = {
Name = "example-${count.index}"
}
}for_each
for_eachaccepts a map or a set. Terraform creates one resource instance per element, accessible via each.key and each.value.
Example – creating instances from a map:
resource "aws_instance" "example" {
for_each = {
instance1 = "t2.micro"
instance2 = "t3.small"
instance3 = "t3.medium"
}
ami = "ami-0c55b31ad2299a796"
instance_type = each.value
tags = {
Name = each.key
}
}Example – creating security‑group rules from a set:
resource "aws_security_group_rule" "allow_ssh" {
type = "ingress"
from_port = 22
to_port = 22
protocol = "tcp"
security_group_id = aws_security_group.example.id
for_each = toset(["10.0.0.0/32", "192.168.0.0/16"])
cidr_blocks = [each.value]
}Exercises
Use the file function to read a file and supply its content as user_data for an EC2 instance.
Use the format function to build a string that includes the current time and the instance ID.
Use count or for_each to create multiple resource instances.
Combine terraform.workspace with conditional expressions to set different variable values per workspace.
Summary
This article covered Terraform's built‑in functions (string, numeric, list, map, and utility functions), conditional (ternary) expressions, string interpolation, the templatefile function, and the count and for_each meta‑arguments. Mastering these features enables more flexible, reusable, and automated Terraform configurations.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
