HCL Syntax, Variables, Locals & Functions
Master HashiCorp Configuration Language (HCL): complex type constraints, validation rules, locals, built-in functions, and dynamic blocks.
HCL Syntax, Variables, Locals & Dynamic Blocks
Section titled “HCL Syntax, Variables, Locals & Dynamic Blocks”HashiCorp Configuration Language (HCL) is designed to strike the balance between human-readable declarative syntax and machine-evaluable configuration. Writing clean, maintainable Terraform requires mastering variables, locals, expressions, and dynamic blocks.
1. Input Variables & Validation Rules
Section titled “1. Input Variables & Validation Rules”In production modules, always specify type, description, and strict validation blocks to catch erroneous configurations before Terraform touches cloud APIs.
variable "environment" { type = string description = "Target deployment environment tier"
validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "The environment variable must be exactly one of: dev, staging, or prod." }}
variable "cluster_config" { type = object({ node_count = number instance_type = string enable_spot = bool subnets = list(string) }) description = "Comprehensive compute cluster specification"}2. Locals: When to Use Them vs. Variables
Section titled “2. Locals: When to Use Them vs. Variables”- Variables (
var.xyz): External inputs passed into a module by the caller. - Locals (
local.xyz): Internal computed expressions and standard naming standards that should never be overridden by external callers.
locals { name_prefix = "${var.project}-${var.environment}"
# Standard enterprise tags merged with custom resource tags common_tags = { Project = var.project Environment = var.environment ManagedBy = "Terraform" CostCenter = "Core-Platform-101" }}3. Core Built-In Functions You Must Know
Section titled “3. Core Built-In Functions You Must Know”Terraform includes a rich set of built-in functions (tested via terraform console):
| Function | Purpose | Example |
|---|---|---|
lookup(map, key, default) |
Safely retrieves map value with fallback | lookup(var.instance_types, var.env, "t3.medium") |
merge(map1, map2) |
Combines multiple maps into one | merge(local.common_tags, { Tier = "Public" }) |
try(eval, fallback) |
Returns first expression that doesn’t error | try(var.vpc.cidr, "10.0.0.0/16") |
flatten(list_of_lists) |
Flattens multidimensional arrays | Useful for mapping subnets across Availability Zones |
templatefile(path, vars) |
Renders user-data startup scripts dynamically | templatefile("./scripts/init.sh.tpl", { port = 8080 }) |
4. Dynamic Blocks: Eliminating Boilerplate
Section titled “4. Dynamic Blocks: Eliminating Boilerplate”Instead of repeating blocks (such as AWS Security Group ingress rules), use dynamic blocks with for_each:
variable "ingress_rules" { type = list(object({ port = number description = string cidr_blocks = list(string) })) default = [ { port = 443, description = "HTTPS traffic", cidr_blocks = ["0.0.0.0/0"] }, { port = 80, description = "HTTP redirect", cidr_blocks = ["0.0.0.0/0"] }, { port = 22, description = "Bastion SSH", cidr_blocks = ["10.0.0.0/8"] } ]}
resource "aws_security_group" "web" { name = "${local.name_prefix}-web-sg" vpc_id = var.vpc_id description = "Ingress traffic rules managed via dynamic block"
dynamic "ingress" { for_each = var.ingress_rules content { description = ingress.value.description from_port = ingress.value.port to_port = ingress.value.port protocol = "tcp" cidr_blocks = ingress.value.cidr_blocks } }
tags = local.common_tags}🧠 Quick Check: HCL Best Practices
Section titled “🧠 Quick Check: HCL Best Practices”[!TIP] Avoid Complex Logic Inside HCL: Terraform is a declarative configuration language, not a general-purpose programming language. If you find yourself writing deeply nested ternary expressions (
condition ? a : (other ? b : c)), refactor the data into structured maps andlookup()tables for clarity and maintainability.