Understanding Terraform Functions
Terraform functions help us transform values, validate inputs, handle conditions, and build dynamic configurations without writing external scripts.This shows how these functions improve code efficiency, reduce errors, and enforce best practices in AWS infrastructure provisioning.
In Day 11 and Day 12, we focus on built-in Terraform functions such as; string, numeric, collection, type conversion, date/time, lookup, and validation functions, demonstrating their practical usage inside the Terraform console and within Terraform configuration files.
This post covers:
- What Terraform functions are
- Where to use them
- Practical examples mapped directly to my Terraform code
What Terraform Functions are
Terraform Functions is a powerful tool that enable efficient infrastructure as code (IaC) by simplifying repetitive tasks through reusable operations.
They are commonly used in:
- locals
- variable validation
- resource arguments
- outputs
🔥 Terraform does not support custom functions, only in-built functions can be used.
🧑💻 Functions enable code reuse and efficiency, crucial in IaC to avoid repetitive declarations.
1. String Formatting & Transformation
🔤 String functions like upper, lower, trim, replace, substring help manipulate text values in Terraform
# variables.tf
variable "project_name" {
default = "DAY 11 12 OF 30 DAYS OF TERRAFORM"
}
# main.tf
locals {
formated_project_name = replace(lower(var.project_name), " ", "-")
}
# outputs.tf
output "formated_project_name" {
value = local.formated_project_name
}
Input:
DAY 11 12 OF 30 DAYS OF TERRAFORM
Output:
day-11-12-of-30-days-of-terraform
S3 Bucket Name Formatting
# variables.tf
variable "bucket_name" {
default = "dayjkadjioruejfiajfiafjoidskjfidsahfiuahdfamkfkldajfuidhkksjdfiuhjdfaj;aiueifja;d;!!!"
}
# main.tf
bucket = lower(substr(
replace(replace(var.bucket_name, "!", ""), ";", ""),
0,
63
))
Removes invalid characters
Converts to lowercase
Limits length to 63 characters
2. Tag Management (merge())
Used to combine multiple tag maps cleanly.
# variabls.tf
variable "standard_tags" {
default = {
owner = "shivam"
series = "30daysofterraform"
}
}
variable "project_tags" {
default = {
day = "Day11-12"
topic = "terraform-functions"
}
}
# main.tf
locals {
merge_tags = merge(var.standard_tags, var.project_tags)
}
📌 Used for: Cost tracking, governance, auditing
3. Input Validation (length(), regex(), can())
Used to catch invalid inputs before deployment.
variable "instance_type" {
default = "t3.micro"
validation {
condition = length(var.instance_type) >= 2 && length(var.instance_type) <= 10
error_message = "instance type must be between 2 and 10 characters"
}
validation {
condition = can(regex("^t[2-3]\\.", var.instance_type))
error_message = "instance type must start with t2 or t3"
}
}
Fails early
Prevents bad infrastructure configs
4. List Processing & Loops (split(), for)
Converting a comma-separated string into structured rules.
#variables.tf
variable "allowed_ports" {
default = "80,443,8080,3306"
}
# main.tf
locals {
port_list = split(",", var.allowed_ports)
sg_rules = [for port in local.port_list :
{
name = "port-${port}"
port = port
description = "Allow traffic on port ${port}"
}
}
📌 Used for: Security groups, firewall rules
5. Environment-Based Lookup (lookup())
Select instance size dynamically by environment.
# variables.tf
variable "instance_size" {
default = {
dev = "t3.micro"
staging = "t3.small"
prod = "t3.large"
}
}
# main.tf
locals {
instance_type = lookup(var.instance_size, var.Environment)
}
📌 Used for: EC2, RDS, autoscaling
6. Location Management (concat(), toset())
Combine and deduplicate locations.
# variables.tf
variable "user_locations" {
default = ["us-east-1", "us-west-1", "us-east-1"]
}
variable "default_location" {
default = ["us-west-1"]
}
# main.tf
locals {
all_locations = concat(var.default_location, var.user_locations)
unique_locations = toset(var.default_location)
}
Prevents duplicates
Useful for regions, AZs, feature flags
7. Protecting Sensitive Data
Secrets must never appear in logs.
locals {
api_key = sensitive("super-secret-key")
}
# variables.tf
variable "creds" {
default = "fdjfuiaj"
sensitive = true
}
# outputs.tf
output "creds" {
value = var.creds
sensitive = true
}
📌 Used for: Passwords, tokens, credentials
7. Cost Calculations (abs(), sum(), max(), min())
Processing costs and credits.
# variables.tf
variable "monthly_cost" {
default = [-50, 100, 466, 21]
}
# main.tf
locals {
positive_cost = [for cost in var.monthly_cost : abs(cost)]
max_cost = max(local.positive_cost...)
min_cost = min(local.positive_cost...)
total_cost = sum(local.positive_cost)
average_cost = local.total_cost / length(local.positive_cost)
}
Handles negative credits
Useful for reports and budgeting logic
📌 Used for: Cost controls, automation logic
8. Timestamp & Date Formatting (timestamp(), formatdate())
# main.tf
locals {
current_timestamp = timestamp()
formated_date = formatdate("yyyyMMdd", local.current_timestamp)
}
# outputs.tf
output "current_time" {
value = local.current_timestamp
}
📌 Used for: Resource tags, audits
9. File Handling & Conditional Logic
(fileexists(), file(), jsondecode())
Safely load config files only if they exist.
Terraform safely reads, decodes, and protects the data.
# main.tf
locals {
config_file_exists = fileexists("./config.json")
config_data = local.config_file_exists
? jsondecode(file("./config.json"))
: []
}
# outputs.tf
output "config_data" {
value = local.config_data
}
- Avoids runtime errors
- Supports optional config files
Video WalkThrough
Top comments (0)