Terraform · Infrastructure as code
What are locals and when should you use them?
Short answer
Locals name intermediate expressions so you can reuse them without exposing them as inputs. They are evaluated per run and are not part of the module interface.
A local is a named expression inside a module. It is useful for derived values that several resources share, such as a name prefix, common tags or a calculated CIDR. Unlike a variable, a caller cannot override it.
locals {
name_prefix = join("-", [var.project, var.environment])
common_tags = {
project = var.project
environment = var.environment
managed_by = "terraform"
}
}
resource "aws_s3_bucket" "logs" {
bucket = local.name_prefix
tags = local.common_tags
}Good uses for locals
- Derived names, ARNs and CIDR ranges used in several places
- Common tag maps shared by many resources
- Flattened collections for for_each
- Readable intermediate steps in a complex expression
Avoid building a parallel variable layer with locals that simply rename inputs. That adds indirection without a decision. Also avoid deep chains of locals that depend on each other, because the dependency becomes hard to follow during review.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between a local and a variable?
- 2Can a caller override a local value?
- 3Why can't count use an unknown local?
- 4When do locals make a configuration harder to read?
Say it in the interview
Locals are named expressions inside a module for values I do not want to expose as inputs, like name prefixes, common tags or computed CIDRs. They reduce repetition and make complex expressions readable. I avoid using them as a second variable layer or building long chains. Because they are evaluated at plan time, a local based on an unknown resource attribute cannot drive count or for_each.
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.