Local Block

In Terraform, a local value provides a way to name an expression so you can then reference that expression elsewhere in the module multiple times without having to repeat it. This is similar to how you would be using temporary local variables within a function in traditional programming languages.
Local values are convenient when you've got an expression that appears more than once within a module. Rather than make several copied of the same expression, you can give it a name, and then refer to the name everywhere within the module. It makes your code shorter, easier to read, and less vulnerable to errors.
NOTE: The values declared within the Local block can't be accessed outside of module.

Local block syntax

The syntax of a local block is as follows:
local {
    # name = expression 
}
Here is a breakdown of the syntax.

Referencing Local block

Once you declare a local value, you can access that value elsewhere in expressions in your Terraform configuration with the following syntax.
local.<name>

Example: Reusing an AWS Region

Now, consider the need to create a module where several resources will use the same AWS region. Instead of using the region expression several times, you can create a name for it using a Local Block. This way, you reutilize the region's value across your module.
local {
    region = "us-west-2"
}
In the above example we declared a local value named region with the value "us-west-2". You now can then refer to the named value of region in multiple resources throughout this module such as:
resource "aws_instance" "my_instance" {
    ami = "ami-abc123"
    instance_type = "t2.micro"
    region = local.region
}
resource "aws_s3_bucket" "my_bucket" {
    bucket = "my-terraform-bucket"
    region = local.region
    acl = "private"
}
In this case, we used local syntax to refer to the region local value inside of both the aws_instance and aws_s3_bucket resources. This makes your code a little bit more concise and easier to read.

Related Pages

Feedback

Was this page helpful?