Terraform Locals
Terraform Locals is a powerful feature that allows the assignment of a name to an expression, effectively enabling developers to use the name multiple times within a module rather than repeatedly writing out the entire expression. This feature greatly enhances the readability and maintainability of the Terraform code, making it easier for developers to manage their infrastructure configurations.
Declaring Terraform Locals
In Terraform, locals are declared in a locals
block, where each local value is assigned a name and an expression. The basic structure of a local declaration looks like this:
locals {
local_name = expression
}
Grouping Related Local Values
For better organization and readability, related local values can be declared together within the same locals
block. This approach is particularly useful when working with complex modules where numerous local values are used:
locals {
service_name = "forum"
owner = "Community Team"
}
Referencing Other Values in Local Expressions
One of the powerful features of Terraform locals is the ability to reference other values within local expressions. This includes variables, resource attributes, and even other local values. This ability to reference and use other values enables more complex transformations and combinations, aiding in the creation of intricate and nuanced infrastructure configurations.
locals {
instance_ids = concat(aws_instance.blue.*.id, aws_instance.green.*.id)
}
Using Local Values in Terraform
Once a local value has been declared, it can be referenced in expressions using the syntax local.<NAME>
. This syntax allows Terraform to distinguish between local values and other types of expressions.
Here's an example of how to reference a local value in a resource
block:
resource "aws_instance" "example" {
tags = local.common_tags
}
Scope of Local Variables
Note that locals can only be accessed in expressions within the module where they were declared. This scope limitation helps maintain clean, organized code and avoids potential conflicts between different modules or nested modules.
When to Use Local Values
Local values in Terraform can be very beneficial when you need to avoid repeating the same values or expressions in your configuration. However, they are not meant to replace every repeated value. Rather, they are designed to reduce redundancy in situations where a single value or result is used in multiple places and is likely to be changed in the future.
References