Skip to main content

Command Palette

Search for a command to run...

Day11-12: Terraform Built-in Functions Explained with Real-World Examples

Published
4 min read
P
Welcome! I’m Prajwal P. I stand at the intersection of technology and efficiency, exploring the dynamic world of DevOps ⚙️. From mastering Cloud infrastructure to orchestrating containers, I am passionate about automating the complex to create the simple. Join me as I document my learning curve, share technical insights, and navigate the ever-evolving landscape of software deployment.

Terraform is not just about creating cloud resources.
Its real power comes from built-in functions that allow you to transform data, validate inputs, read files, handle secrets, manage timestamps, and apply business logic to infrastructure.

In this post, we’ll explore the most commonly used Terraform functions with real-world examples that you’ll see in production DevOps projects.


Why Terraform Functions Matter

In real infrastructure:

  • Input values are messy

  • Naming must follow cloud rules

  • Secrets must be protected

  • Configurations come from files

  • Environments behave differently

Terraform functions help solve all of this before resources are created.


1. String Transformation and Naming Standards

Cloud providers enforce strict naming rules.
Terraform helps normalize names automatically.

Example: Normalize a project name

locals {
  project_name = replace(lower("Project ALPHA Resource"), " ", "-")
}

Output

project-alpha-resource

Functions used

  • lower() → converts text to lowercase

  • replace() → replaces characters

📌 Used for: S3 buckets, IAM roles, Kubernetes resources


2. Tag Management Using Maps

Organizations usually apply:

  • Global tags (Owner, Team)

  • Environment tags (dev, prod)

Terraform makes this easy.

locals {
  tags = merge(
    { Owner = "DevOps", Team = "Platform" },
    { Environment = "prod" }
  )
}

Output

{
  Owner = "DevOps"
  Team  = "Platform"
  Environment = "prod"
}

📌 Used for: Cost tracking, governance, auditing


3. Sanitizing AWS Resource Names

AWS services like S3 have strict rules:

  • Lowercase only

  • No special characters

  • Max length limits

Terraform can sanitize inputs automatically.

locals {
  bucket_name = substr(
    replace(
      replace(
        replace(lower("My_S3.Bucket@2026"), "_", "-"),
        ".", "-"
      ),
      "@", "-"
    ),
    0,
    63
  )
}

Output

my-s3-bucket-2026

📌 Used for: S3, ALB, DNS names


4. Working with Lists and Loops

Infrastructure often requires repeating rules (ports, CIDRs).

locals {
  ports = [
    for p in split("80,443,8080", ",") : {
      from = tonumber(p)
      to   = tonumber(p)
    }
  ]
}

Output

[
  { from = 80, to = 80 },
  { from = 443, to = 443 },
  { from = 8080, to = 8080 }
]

📌 Used for: Security groups, firewall rules


5. Environment-Based Configuration

Different environments need different sizes.

locals {
  instance_type = lookup(
    {
      dev  = "t2.micro"
      qa   = "t2.small"
      prod = "t3.medium"
    },
    "prod",
    "t2.micro"
  )
}

Output

t3.medium

📌 Used for: EC2, RDS, autoscaling


6. Validating Inputs Safely

Terraform can validate input without crashing.

locals {
  is_valid = can(
    regex("^t[0-9]\\.(micro|small|medium|large)$", "t3.micro")
  )
}

Output

true

📌 Used for: CI/CD guardrails, input validation


7. Protecting Sensitive Data

Secrets must never appear in logs.

locals {
  api_key = sensitive("super-secret-key")
}

Terraform hides this value automatically:

(sensitive value)

📌 Used for: Passwords, tokens, credentials


8. File and Path Handling

Terraform often reads files from the repository.

locals {
  file_exists = fileexists("./config/app.json")
  folder_name = dirname("./config/app.json")
}

📌 Used for: Config files, templates, scripts


9. Managing Lists and Removing Duplicates

Cloud deployments often span multiple regions.

locals {
  regions = toset(concat(
    ["us-east-1", "us-west-2"],
    ["us-west-2", "eu-west-1"]
  ))
}

Output

["us-east-1", "us-west-2", "eu-west-1"]

📌 Used for: Multi-region setups


10. Cost Calculations with Terraform

Terraform can handle numeric logic.

locals {
  total_cost = max(
    sum([for c in [120, 80, -20] : abs(c)]),
    0
  )
}

Output

220

📌 Used for: Cost controls, automation logic


11. Timestamp and Date Handling

Useful for tagging and auditing.

locals {
  current_date = formatdate("YYYY-MM-DD", timestamp())
}

Output

2026-01-23

📌 Used for: Resource tags, audits


12. Reading and Processing JSON Files

Most real configurations are stored as JSON.

locals {
  raw_json     = file("${path.module}/config/app.json")
  decoded_json = jsondecode(raw_json)
  secret_json  = sensitive(jsonencode(decoded_json))
}

Terraform safely reads, decodes, and protects the data.

📌 Used for: Secrets Manager, Parameter Store


Final Thoughts

Terraform functions turn static configuration into dynamic infrastructure logic.

If you master:

  • Strings

  • Lists & maps

  • Validation

  • Files & JSON

  • Time & cost logic

You move from writing Terraform to engineering infrastructure.

Video Walkthrough

Terraform on AWS

Part 5 of 14

30 Days of Terraform on AWS is a hands-on series that takes you from IaC fundamentals to production-ready AWS architectures. Learn Terraform basics, AWS provisioning, mini projects, and advanced topics like EKS, CI/CD, GitOps, and Terraform Cloud.

Up next

Day09: Terraform Lifecycle Meta-Arguments: When to Use and When Not to Use (With Real-World Examples)

Terraform makes infrastructure provisioning easy, but real-world infrastructure requires safety, validation, and control.This is where Terraform lifecycle meta-arguments play a crucial role. In this blog, we will explore all Terraform lifecycle meta-...

More from this blog

Terraform on AWS

29 posts

Stop clicking in the AWS console. Start coding your infrastructure.