Local Value
A Terraform local value is a named expression computed once inside a module and reused wherever needed. Locals cannot be set by callers, so they suit derived values like name prefixes and merged tags.
What Is a Local Value?
Define it in a locals block and reference it as local.name. It is the DRY principle for expressions.
HCL
locals { name_prefix = "${var.project}-${var.environment}" common_tags = { Project = var.project Environment = var.environment ManagedBy = "terraform" }} resource "aws_instance" "app" { ami = data.aws_ami.amazon_linux.id instance_type = "t3.medium" tags = merge(local.common_tags, { Name = "${local.name_prefix}-app" })}RememberIf the caller should be able to set the value, use a variable. If it is derived internally, use a local.
Frequently Asked Questions
How is a local different from a variable?
A variable is an input set from outside the module. A local is computed inside it and cannot be overridden.
Can I have several locals blocks?
Yes, in any file. Terraform merges them, as long as no two locals share a name.
Found a mistake, an outdated step or a broken link?