How to use Terraform locals?
Working with the Terraform is always fun but it would be much easier to use when you know all the concepts very well.
There is one core concept Terraform locals that comes very handy when you are working with very large terraform configuration files.
Terraform locals are quite similar to Terraform input variables but Terraform locals do not change their value. On the other hand, if you talk about Terraform input variables then it is dependent on user input and it can change its value.
If you look at the following diagram, here I am trying to create a terraform local in which I am going to Define the server name so in the future if there is a change in the server name so I do not need to change the server name at all places but instead I can just update my locals.
So if you have a very large Terraform file where you need to use the same values or expressions multiple times then Terraform local can be useful for you.
Table of Content
- Terraform Locals in nutshell
- Benefits of using Terraform Locals
- Create your first Terraform Local
- Combine terraform local with terraform variable
- Best practices for using locals
- Conclusion
1. Terraform Locals in a nutshell
Before we try to understand the Terraform locals take a step back and try to compare terraform locals with normal local variable declared inside 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 -
1 locals {
2 my_local = "${var.ec2_instance_name}"
3}
Example without expression -
1 locals {
2 my_local = "t2.micro"
3}
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.
1locals {
2 staging_env = "staging"
3}
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
1provider "aws" {
2 region = "eu-central-1"
3 access_key = "<YOUR_AWS_ACCESS_KEY>"
4 secret_key = "<YOUR_AWS_SECRET_KEY>"
5}
6
7locals {
8 staging_env = "staging"
9}
10
11resource "aws_vpc" "staging-vpc" {
12 cidr_block = "10.5.0.0/16"
13
14 tags = {
15 Name = "${local.staging_env}-vpc-tag"
16 }
17}
18
19resource "aws_subnet" "staging-subnet" {
20 vpc_id = aws_vpc.staging-vpc.id
21 cidr_block = "10.5.0.0/16"
22
23 tags = {
24 Name = "${local.staging_env}-subnet-tag"
25 }
26}
27
28resource "aws_instance" "ec2_example" {
29
30 ami = "ami-0767046d1677be5a0"
31 instance_type = "t2.micro"
32 subnet_id = aws_subnet.staging-subnet.id
33
34 tags = {
35 Name = "${local.staging_env} - Terraform EC2"
36 }
37}
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 -
1variable location {
2 description = "Location of server"
3 type = string
4 default = "finland"
5}
1variable server_name {
2 description = "Name of server"
3 type = string
4 default = "primary-app-server"
5}
Now let's create a terraform local, in which we are going to combine the two variables which we have created just above
1locals {
2 server_details = "${var.location}-${var.server_name}"
3}
And now we can use this local inside our terraform configuration where we are going to define the server detail.
5. Best practices for using locals
- You should use terraform locals excessively inside your Terraform configuration
- Always keep in mind to use terraform local where you think that value is going to be changed in the future.
- Always think of Terraform Locals as a central place for storing configuration values.
- Try not too hard to code locals inside terraform configuration file instead pick the value of terraform locals from the
.tfvars
so that you have a single location to update in the future.
6. Conclusion
Terraform locals are a great utility when you are working with a bigger terraform configuration and it reduces a lot of code redundancy. But the good recommendation is to use the terraform locals in moderation excessive use of terraform locals will defy the purpose of it and it will make your terraform configuration more difficult to read and troubleshoot.
Read More -
- Install terraform on Ubuntu 20.04, CentOS 8, MacOS, Windows 10, Fedora 33, Red hat 8 and Solaris 11
- How to setup Virtual machine on Google Cloud Platform using terraform
- Create EC2 Instance on AWS using terraform
- How to use Terraform Input Variables
- What is variable.tf and terraform.tfvars?
- How to use Terraform locals?
- How to use Terraform output values?
- Understanding terraform count, for_each and for loop?
- Cloud-nuke : How to nuke AWS resources and save additional AWS infrastructure cost?
- How to use Terraform Dynamic blocks?
- How to use Terraform resource meta arguments?
- How to use Terraform Data sources?
- What is terraform provisioner?
- Terraform how to do SSH in AWS EC2 instance?
- How Terraform modules works?
- How to run specific terraform resource?
- How to use Workspaces in Terraform?
- Securing AWS secrets using HashiCorp Vault with Terraform?
- Managing Terraform states?
- Terraform state locking using DynamoDB (aws_dynamodb_table)
- Terraform and AWS credentials handling?
- Terraform and AWS Multi account Setup?
Terragrunt -
Posts in this Series
- How to use Terragrunt?
- Terraform and AWS Multi account Setup?
- Terraform and AWS credentials handling?
- How to fix-error configuring S3 Backend no valid credential sources for S3 Backend found?
- Terraform state locking using DynamoDB (aws_dynamodb_table)?
- Managing Terraform states?
- Securing AWS secrets using HashiCorp Vault with Terraform?
- How to use Workspaces in Terraform?
- How to run specific terraform resource, module, target?
- How Terraform modules works?
- Terraform how to do SSH in AWS EC2 instance?
- What is terraform provisioner?
- Is terraform destroy needed before terraform apply?
- How to fix terraform error Your query returned no results. Please change your search criteria and try again?
- How to use Terraform Data sources?
- How to use Terraform resource meta arguments?
- How to use Terraform Dynamic blocks?
- Terraform - How to nuke AWS resources and save additional AWS infrastructure cost?
- Understanding terraform count, for_each and for loop?
- How to use Terraform output values?
- How to use Terraform locals?
- How to fix error configuring Terraform AWS Provider error validating provider credentials error calling sts GetCallerIdentity SignatureDoesNotMatch?
- How to fix Invalid function argument on line in provider credentials file google Invalid value for path parameter no file exists
- How to fix error value for undeclared variable a variable named was assigned on the command line?
- What is variable.tf and terraform.tfvars?
- How to use Terraform Input Variables
- Terraform create EC2 Instance on AWS
- How to fix Error creating service account googleapi Error 403 Identity and Access Management (IAM) API has not been used in project before or it is disabled
- How to setup Virtual machine on Google Cloud Platform
- Install terraform on Ubuntu 20.04, CentOS 8, MacOS, Windows 10, Fedora 33, Red hat 8 and Solaris 11