1. Terraform Locals Before we try to understand the Terraform locals take a step back and try to compare terraform locals with a normal ...
1. Terraform Locals
Before we try to understand the Terraform locals take a step back and try to compare terraform locals with a normal local variables declared inside the function, so any local variable present inside the function will only be accessible within that function similarly to the terraform locals are available within -
- Local terraform module
- Within the terraform configuration
Value assignment- Terraform locals do not change their value once it is assigned, you have to re-assign a new value.
Power of Expression- Apart from static value assignment terraform locals can use the power of expression, so instead of writing the same expression the multiple times through the terraform configuration, you can declare a terraform locals and use the same terraform locals at other places.
Example with expression -
Example without expression -
2. Benefits of using Terraform Locals
If you are working on a large enterprise infrastructure then it is impossible to work without Terraform Locals. But let's see the benefits of using terraform locals in a bit more detail -
- Terraform locals can be re-used multiple numbers of times in the terraform configuration file.
- It can reduce the work of updating your terraform configuration at multiple places. With terraform locals you need to update its value once and it should reflect all over the place where it is referred.
3. Create your first Terraform Local on AWS
Let's create our first Terraform local and in this terraform local we will store the Tag name for the AWS EC2 instance.
As you can see in the above syntax we have created a tag name Staging for the EC2 instance. And we're going to use the same local throughout our Terraform configuration.
We use the terraform locals for -
- Putting a tag on aws_subnet
- Putting a tag on aws_instance for ec2
Here is my Terraform configuration for my AWS environment
4. Combine terraform local with terraform variable
now we know how to use terraform local the next thing which we are going to try is to combine terraform local along with Terraform variable.
First, let's create a few terraform variables -
variable.tf
main.tf
COMMENTS