HCL Blocks, Expressions, and Functions

Scenario: A configuration repeats environment names and CIDRs until a rename produces inconsistent resources.

HCL combines structural blocks with expressions. References, conditionals, for expressions, splats, templates, and built-in functions derive values without becoming a general-purpose imperative language. Prefer readable transformations and locals with domain names. Complex values—list, set, map, object, tuple—carry semantics: sets discard order and duplicates; objects have named attributes; maps have uniform element types.

Analogy: Expressions are a spreadsheet layer over infrastructure facts. Useful formulas remove repetition; nested formulas nobody can explain create a second programming language.

A worked configuration

locals {
  prefix = "${var.environment}-${var.service}"
  ports  = toset([443, 8443, 443])
}

resource "fakecloud_server" "api" {
  name = local.prefix
  tags = merge(var.common_tags, { Service = var.service })
}

Use terraform console to explore types and functions before embedding a transformation. Keep business policy visible, validate assumptions at boundaries, and split complex logic into named locals so plan reviewers can follow it.

Note: Treat the plan as a change contract: understand every create, update, replacement, and destroy before approving it.
Goal: Reinforce this lesson in the tf-count-for-each Terraform lab. Open /labs/terraform and choose slug tf-count-for-each; the lab runs real Terraform against the offline FakeCloud provider.