Day11-12: AWS Terraform Built-in Functions
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)
This is a summary aggregated from Dev.to. Read the complete article on the original site:
Read full article at Dev.to