DEV Community

Cover image for πŸš€ Terraform Day 12: Validation, Numeric, Time & File Functions β€” Writing Safer IaC
Jeeva
Jeeva

Posted on

πŸš€ Terraform Day 12: Validation, Numeric, Time & File Functions β€” Writing Safer IaC

🎯 Why Day 12 Matters

As Terraform projects grow, common problems appear:
Invalid user inputs causing failed deployments
Duplicate values in lists
Incorrect numeric calculations
Hardcoded timestamps or names
External configuration managed outside Terraform

Day 12 addresses all of these using Terraform’s built-in functions.

1️⃣ Validation Functions β€” Catch Errors Early
Terraform allows input validation inside variable blocks.

Example: Length Validation
variable "instance_type" {
type = string
default = "t2.micro"

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

Regex Validation
validation {
condition = can(regex("^t(2|3).*", var.instance_type))
error_message = "Only t2 or t3 instance types are allowed."
}

endswith Validation
validation {
condition = endswith(var.backup_name, "-backup")
error_message = "Backup name must end with -backup."
}

βœ… Prevents invalid infrastructure before terraform apply.
πŸ” Sensitive Variables
Terraform supports sensitive variables to hide values from logs and outputs.

variable "db_password" {
type = string
sensitive = true
}

_
⚠ Important:
Sensitive β‰  encrypted
Values still exist in state files
Use secret managers (AWS Secrets Manager, Vault) for real security_

2️⃣ Type Conversion & Deduplication
Lists allow duplicates; sets do not.

Example
locals {
all_locations = concat(var.default_locations, var.user_locations)
unique_locations = toset(local.all_locations)
}

βœ” toset() removes duplicates
βœ” Useful for regions, CIDRs, names

3️⃣ Numeric Functions β€” Real Calculations

Terraform numeric functions work on individual values, not lists.
Example Data
variable "monthly_costs" {
type = list(number)
default = [100, -50, 200]
}

Absolute Values Using for-expression
locals {
positive_costs = [for c in var.monthly_costs : abs(c)]
}

Aggregations
locals {
max_cost = max(local.positive_costs...)
min_cost = min(local.positive_costs...)
total = sum(local.positive_costs)
average = sum(local.positive_costs) / length(local.positive_costs)
}
πŸ“Œ Spread operator (...) is required for max() and min().

4️⃣ Timestamp & Date Functions
Current Time
timestamp()

⚠ Value is known only after apply.
Formatting Dates
formatdate("YYYY-MM-DD", timestamp())

Practical Use
"${var.project}-backup-${formatdate("YYYYMMDD", timestamp())}"

βœ” Useful for backups
βœ” Logs and audit trails
βœ” Time-based naming

5️⃣ File Handling in Terraform
Terraform can read external files safely.

Check if File Exists
fileexists("config.json")

Read and Decode JSON
locals {
config = fileexists("config.json") ? jsondecode(file("config.json")) : {}
}

Example JSON
{
"db_name": "appdb",
"port": 5432
}

Now accessible as:
local.config.db_name

πŸ“‚ Enables:
External configuration management
Cleaner Terraform files
Automation-friendly setups

🏁 Conclusion

Day 12 completes a major milestone in Terraform learning.
You now know how to:
Validate inputs
Protect sensitive values
Clean collections
Perform numeric analysis
Use timestamps correctly
Read external files safely
These skills turn Terraform from simple configuration into robust infrastructure automation.

πŸ”œ Next Steps
Apply validation in all variables
Deduplicate collections properly
Use timestamps for naming & audits
Externalize configs using files
Practice hands-on with assignments
Happy Terraforming! πŸš€

Top comments (0)