4.3.3. Local Values
💡 First Principle: A local value names an expression once so you can reuse it everywhere — reducing repetition and centralizing logic — but unlike a variable it's computed inside the module and cannot be overridden from outside.
locals blocks define named expressions used within a module:
locals {
name_prefix = "${var.project}-${var.environment}"
common_tags = {
Project = var.project
Environment = var.environment
}
}
resource "aws_instance" "web" {
tags = local.common_tags
}
Locals are ideal for values derived from variables or resources that you'd otherwise repeat. Because they're internal, they keep complex expressions out of resource blocks and give a single place to change shared logic. Reference them with local.<name>.
⚠️ Exam Trap: Locals cannot be set with -var, tfvars, or environment variables — those only feed input variables. If an answer suggests overriding a local at the command line, it's wrong. Locals are computed, not supplied.
Reflection Question: When would you reach for a local instead of a variable, and what does that choice say about where the value comes from?