How can I use “local.tf” in the terraform?
I am currently working on a Terraform project in order to divide the infrastructure on a cloud. How can I utilize the “locals.tf” file in order to define and manage the reusable values?
In the context of terraform the terraform local.tf function is used for defining reusable values. Here is the example below of how you can use “local.tf”
Create locals.tf file by using:-
Create file
# locals.tf
locals {
# Define reusable values or expressions
region = "us-west-1"
instance_type = "t2.micro"
tags = {
Name = "MyInstance"
Environment = "Production"
}
}
Reference the locals
# main.tf
resource "aws_instance" "example_instance" {
# Use values defined in locals
ami = "ami-12345678"
instance_type = local.instance_type
availability_zone = "${local.region}a"
tags = local.tags
# ... other configuration settings
}
Reference the “locals” in the block called resource by using:-
# main.tf
Resource “aws_instance” “example_instance” {
# Use values defined in locals
Ami = “ami-12345678”
Instance_type = local.instance_type
Availability_zone = “${local.region}a”
Tags = local.tags
# … other configuration settings
}
If you use locals.tf then you can properly organize and manage the reusable values which will further maintain the consistency in the whole process of your terraform project as it promotes centralization, and improves readability.