Skip to main content

Command Palette

Search for a command to run...

Terraform Functions – Part 2

Published
3 min read
Terraform Functions – Part 2

Every day I explore Terraform, I feel one step closer to writing clean, production-ready Infrastructure as Code.

But today was special.

I deep-dived into Terraform Functions – Part 2, and this is where Terraform truly starts feeling powerful and intelligent.
Validation functions, file functions, and collection utilities helped me understand how Terraform ensures correctness before deployment.

Here’s everything I learned today 👇


1. Validation Functions

These functions help Terraform validate inputs BEFORE running any deployment, preventing costly mistakes.


i) can()

Checks whether an expression can be evaluated without throwing an error.

Example

variable "port" {
  default = "8080"
}

output "is_number" {
  value = can(tonumber(var.port))
}

🔍 Explanation:
can() returns true because "8080" can be safely converted into a number.


ii) regex()

Checks if a string matches a regular expression.

Example

output "is_valid_email" {
  value = regex("^.+@.+\\..+$", "test@example.com")
}

💡 Output: ["test@example.com"] → Means the string matched.


iii) contains()

Example

locals {
  colors = ["red", "blue", "green"]
}

output "has_red" {
  value = contains(local.colors, "red")
}

iv) startswith()

Ensures inputs follow a proper prefix.


v) endswith()

Validates filename extensions.

My Practical Use

variable "regions" {
  default = ["us-east-1", "us-west-2", "us-east-2"]
}
variable "region_with_validation" {
  default = "ue-east-1"

  validation {
    condition     = can(regex("^us\\-(east|west)\\-\\d+$", var.region_with_validation))
    error_message = "The region must be in the format 'us-east-1' or 'us-west-2'."
  }
  validation {
    condition = contains(var.regions, var.region_with_validation)
    error_message = "The region must be one of the allowed regions: us-east-1, us-east-2, us-west-1, us-west-2."
  }
   validation {
    condition     = length(var.region_with_validation) >= 2 && length(var.region_with_validation) <= 15
    error_message = "The region must be 2 and 15 character ."
  }

  validation {
    condition = startswith(var.region_with_validation, "us-")
    error_message = "The region must start with 'us-'."
  }
}

2. File Functions

These functions help Terraform read, validate, and work with files dynamically.


i) fileexists()

Checks if a file exists.

My practical use

locals {
  config_file_exist = fileexists("config.json") #Return true if file exist else false
}
output "name_of_config_file_exist" {
  value = local.config_file_exist
}

ii) file() + jsondecode()

Reads file content and converts JSON → Terraform map.

Output examples

locals {
  config_file_content = local.config_file_exist ? jsondecode(file("config.json")) : {}
}
output "config_file_content" {
  value = local.config_file_content
}

⛅Smart approach:
If the JSON file doesn’t exist → return {} (empty object).

iii) dirname()

Returns the directory path.

Example

output "dir_name" {
  value = dirname("/home/user/data/file.txt")
}

Output: /home/user/data


iv) basename()

Returns the filename from a path.

Example

output "file_name" {
  value = basename("/home/user/data/file.txt")
}

Output: file.txt


3. Collection Functions

These functions make list/set/map manipulation easy.


1. concat()

Combine multiple lists.

My example

variable "user_locations" {
  default = ["us-east-1", "us-west-2", "us-east-1"]  # Has duplicate
}

variable "default_locations" {
  default = ["us-west-1"]
}

locals { 
  all_locations = concat(var.user_locations, var.default_locations)
}

2. toset()

Remove duplicates from a list.

My example

locals {
  unique_locations = toset(local.all_locations)
}

Outputs I generated

output "names_of_all_locations" {
  value = local.all_locations
}
#names_of_all_locations = [
# "us-east-1",
#  "us-west-2",
#  "us-east-1",
#  "us-west-1",
#]

output "unique_locations" {
  value = local.unique_locations
}

#unique_locations = toset([
 # "us-east-1",
 # "us-west-1",
 # "us-west-2",
# ])

Result:

  • All locations including duplicates → all_locations

  • Only unique values → unique_locations

📺 Video That Helped Me Understand this concept:


Conclusion — Part 2 Made My Terraform Code Safer and Smarter

Today’s exploration made me realize:

Terraform Functions aren’t optional — they are essential for writing clean, validated, production-ready IaC.

Validation Functions → Catch mistakes before deployment
File Functions → Automate reading configs/scripts
Collection Functions → Make data handling easy

More from this blog

B

Build With Rajesh

31 posts