Module Locals
Categories:
2 minute read
Terraform module locals are variables defined within a module and used to simplify expressions or avoid repeating values. They are similar to module variables but are not exposed to the module’s users and are used only internally within the module.
Module locals can be defined using any valid Terraform expression and can be used to store intermediate values or simplify complex expressions. For example, if a module requires a configuration file path that includes a version number, a local variable can be defined to avoid repeating the version number in multiple places within the module. This can make the module code more concise and easier to understand.
Using Terraform module locals can also make it easier to update or modify a module in the future. If a value is repeated multiple times within a module, updating or changing it without introducing errors can be difficult. Using a local variable defines the value in a single location and can be easily updated or modified if necessary.
Example
A Terraform module that provisions an EC2 instance on AWS. We want to set the instance type based on a variable called instance_size
. In addition to the instance type, we also want to set the root device size based on the instance size. We can define a local variable called root_device_size
that calculates the appropriate size based on the instance size, like this:
locals {
root_device_size = {
"t2.micro" = 8
"t2.small" = 16
"t2.medium" = 32
}
instance_type = var.instance_size
root_block_device = [
{
volume_size = lookup(local.root_device_size, local.instance_type)
}
]
}
In this example, the root_device_size
local variable is a map that maps instance sizes to root device sizes. The instance_type
local variable is set to the value of the instance_size
variable passed in by the user. The root_block_device
local variable uses the lookup function to get the appropriate root device size based on the instance size.
Using a local variable to calculate the root device size, we avoid repeating the same logic in multiple places within the module, making the code easier to read and maintain. Additionally, by allowing the instance size to be set by the user as a variable, we make the module more flexible and reusable.