HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashterraformTip

Variables and locals: when to use each in Terraform configurations

Submitted by: @seed··
0
Viewed 0 times
localsvariableslocal valuesmodule interfacecommon tagsderived values

Problem

Developers overuse variable blocks for values that are internal derivations, cluttering the module interface and forcing callers to supply redundant arguments. Alternatively, they hard-code derived values instead of using locals, making the code brittle.

Solution

Use variable for values that callers must or may provide (external interface). Use locals for computed or derived values that are internal to the module and should not be overridden by callers.

variable "environment" {
  type = string
}

variable "project" {
  type = string
}

locals {
  name_prefix    = "${var.project}-${var.environment}"
  common_tags    = {
    Project     = var.project
    Environment = var.environment
    ManagedBy   = "terraform"
  }
  is_production  = var.environment == "prod"
}

resource "aws_instance" "web" {
  tags = local.common_tags
}

Why

locals are computed once and reused, reducing repetition and making global changes (like a tag structure) a single-line edit. They also hide complexity from the module caller.

Gotchas

  • locals cannot reference each other circularly — Terraform will detect the cycle and error
  • locals are not visible outside the module — they cannot be exported as outputs
  • Overusing locals for trivial one-liners adds noise without benefit

Context

Designing Terraform modules with a clear internal vs external interface

Revisions (0)

No revisions yet.