Terraform · Infrastructure as code

Which Terraform functions are most useful in practice?

MediumfunctionsexpressionstransformationUpdated Oct 2026
Quiz this track

Short answer

Terraform has built-in functions for strings, collections, numbers, encoding and CIDR maths, plus provider-defined functions in newer versions. Use try and coalesce for optional values instead of brittle indexes.

Functions transform values inside expressions. They do not call APIs or mutate infrastructure. Common families cover strings, collections, type conversion, encoding, filesystem reads and network maths. Provider-defined functions extend this set when a provider ships them.

hcl
locals {
  name    = join("-", [var.project, var.environment])
  port    = lookup(var.ports, "http", 80)
  tags    = merge(var.tags, { managed_by = "terraform" })
  payload = jsonencode({ name = local.name, port = local.port })
  retries = try(var.settings.retries, 3)
  subnet  = cidrsubnet("10.0.0.0/16", 8, 1)
}
merge, lookup, try, jsonencode and cidrsubnet cover many everyday transformations.

Functions worth knowing

  • Strings: format, replace, split, trimspace
  • Collections: merge, lookup, flatten, distinct, setproduct
  • Safety: try, can, coalesce
  • Encoding: jsonencode, yamlencode, base64encode
  • Network: cidrsubnet, cidrhost, cidrnetmask

Prefer explicit types and simple expressions over clever one-liners. If a transformation spans several functions, split it into locals with names. Avoid using file or templatefile for values that should be inputs, because it makes the module harder to reuse and test.

HCL does not let you define custom functions. Reuse goes through modules, locals or provider-defined functions, not a user function library.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between try and can?
  2. 2How would you compute subnets from a CIDR block?
  3. 3Can you define your own functions in HCL?
  4. 4When should a value come from a variable instead of templatefile?

Say it in the interview

I use built-in functions for transformations: merge for tags, lookup for optional map values, try and coalesce for safe defaults, jsonencode for policy documents, and cidrsubnet for network calculations. If an expression needs several functions, I break it into named locals so reviewers can follow it. HCL has no user-defined functions, so reusable logic belongs in modules or provider-defined functions.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Terraform mock interview and get scored feedback on depth, clarity and confidence.