DEV Community

Cover image for AWS Terraform Functions – Part 2
Adarsh Gupta
Adarsh Gupta

Posted on

AWS Terraform Functions – Part 2

 In this Part-2 guide on AWS Terraform Functions, we explore a set of practical and commonly used Terraform functions applied in real automation scenarios. These examples are based on a working Terraform configuration that demonstrates validation, file handling, list operations, cost calculation, and timestamp formatting.

The goal of this blog is to help you understand not just the functions, but also how they fit naturally inside real Terraform workflows.


1. Instance Validation Using Terraform Functions

Validating inputs at the variable level helps prevent mistakes before infrastructure is created. Terraform provides several helpful validation functions such as length(), can(), and regex().

Below is a real example that validates an EC2 instance type:

Validate instance type length

variable "instance_type" {
  default = "t2.micro"

  validation {
    condition     = length(var.instance_type) >= 2 && length(var.instance_type) <= 20
    error_message = "Instance type must be 2 and 20 characters."
  }
Enter fullscreen mode Exit fullscreen mode

Validate instance type pattern using regex

  validation {
    condition     = can(regex("^t[2-3]\\.", var.instance_type))
    error_message = "Instance type must start with t2. or t3."
  }
}
Enter fullscreen mode Exit fullscreen mode

This ensures that the instance type is not only of valid length but also begins with either t2. or t3..


2. Backup Configuration and Sensitive Handling

Backup naming conventions and secure values are important for safe automation. Terraform offers functions like endswith() and the sensitive attribute.

Ensuring backup name format

variable "backup_name" {
  default = "daily_backup"

  validation {
    condition     = endswith(var.backup_name, "_backup")
    error_message = "Backup name must end with '_backup'"
  }
}
Enter fullscreen mode Exit fullscreen mode

Marking credentials as sensitive

variable "credentials" {
  default   = "xyzabc123"
  sensitive = true
}
Enter fullscreen mode Exit fullscreen mode

Terraform will hide the value anywhere it appears in logs or CLI output, improving security.


3. Location Management with Lists and Sets

Managing user locations, default locations, and ensuring uniqueness is a common scenario in multi-region AWS deployments. Terraform simplifies this using concat() and toset().

Merging and deduplicating locations

variable "user_locations" {
  default = ["us-west-1", "us-east-1", "eu-central-1", "ap-south-1"]
}

variable "default_location" {
  default = ["ap-south-1"]
}

locals {
  all_locations     = concat(var.user_locations, var.default_location)
  unique_locations  = toset(local.all_locations)
}
Enter fullscreen mode Exit fullscreen mode

Here, concat() merges the lists, and toset() removes duplicates automatically.


4. Cost Calculation and Value Processing

Terraform’s numeric functions make it easy to compute totals, calculate averages, or normalize values.

Example cost dataset

variable "monthly_costs" {
  default = [-50, 100, 150, 200, 250] # negative value indicates refunds
}
Enter fullscreen mode Exit fullscreen mode

Processing the costs

locals {
  positive_cost = [for cost in var.monthly_costs : abs(cost)]
  max_cost      = max(local.positive_cost...)
  min_cost      = min(local.positive_cost...)
  total_cost    = sum(local.positive_cost)
  avg_cost      = local.total_cost / length(local.positive_cost)
}
Enter fullscreen mode Exit fullscreen mode

This configuration uses:

  • abs() to convert negative values into positive
  • max() and min() to identify the cost range
  • sum() to compute total expenditure
  • A manual calculation for average cost

5. Timestamp and Date Formatting

Terraform provides built-in timestamp utilities that are extremely helpful for naming, versioning, or logging.

Generating formatted timestamps

locals {
  current_timestamp = timestamp()
  format1           = formatdate("DD-MM-YYYY", local.current_timestamp)
  format2           = formatdate("YYYY/MM/DD HH:MM:SS", local.current_timestamp)
  timestamp_name    = "backup-${local.format1}"
}
Enter fullscreen mode Exit fullscreen mode

This enables time-based resource naming such as:

backup-05-12-2025
Enter fullscreen mode Exit fullscreen mode

6. File Path Processing and JSON Handling

Terraform can work directly with files on disk. This is particularly useful for loading configuration files or template data.

Extracting directory name and checking if a file exists

locals {
  dir_name            = dirname("./config.json")
  config_file_exists  = fileexists("${local.dir_name}/config.json")
}
Enter fullscreen mode Exit fullscreen mode

Conditionally loading JSON file content

locals {
  config_file_data = local.config_file_exists ? jsondecode(file("./config.json")) : null
}
Enter fullscreen mode Exit fullscreen mode

Here, the workflow is:

  1. Extract the directory name using dirname()
  2. Check if the configuration file exists using fileexists()
  3. If it exists, load the content using file()
  4. Convert JSON to an object using jsondecode()

This approach is extremely useful in modular Terraform setups where external JSON files drive configuration.


Conclusion

The examples in this blog highlight how Terraform's built-in functions make configurations smarter, safer, and more flexible. Whether you're validating user input, processing files, managing regions, computing costs, or formatting timestamps, these functions help you build reliable and automated AWS infrastructure.

Understanding these helper functions is essential for writing reusable and production-grade Terraform modules.


Video Walkthrough – Terraform Functions Part 2


@piyushsachdeva


Top comments (0)