Terraform Locals
What are Terraform Locals?
Locals in Terraform are named values that you can refer to in your configuration. They're similar to variables, but their values are fixed when the configuration is loaded, and they can't be set from outside the module.
Why Use Locals?
Locals are useful for: 1. Reducing repetition within a module 2. Providing meaningful names to expressions 3. Creating simple computations and transformations of other values
Defining Locals
Locals are typically defined in a locals
block:
locals {
service_name = "forum"
owner = "Community Team"
}
You can also use expressions in locals:
locals {
# Ids for multiple sets of EC2 instances, merged together
instance_ids = concat(aws_instance.blue.*.id, aws_instance.green.*.id)
}
Using Locals
Reference locals in your configuration using the local.
prefix:
resource "aws_instance" "example" {
# ...
tags = {
Service = local.service_name
Owner = local.owner
}
}
Complex Transformations
Locals are excellent for more complex transformations:
locals {
# Common tags to be assigned to all resources
common_tags = {
Service = local.service_name
Owner = local.owner
}
}
resource "aws_instance" "example" {
# ...
tags = merge(
local.common_tags,
{
Name = "Example Instance"
}
)
}
Best Practices
- Use locals for repeated values within a module
- Keep locals simple and focused
- Use descriptive names for clarity
- Avoid overusing locals; sometimes it's clearer to use the original expression
Locals vs. Variables
- Use variables for values that need to be set from outside the module
- Use locals for internal calculations and intermediate values
Remember, locals are evaluated during the planning phase, so they can't depend on resource attributes that aren't known until after apply.