How to use Terraform locals?
In programming world we have concept of variables, similar to that in Terraform we also have concept of Terraform Locals.
What is Terraform locals?
Here is an very basic example code which show - "How to create locals in Terraform?"
1## Example of local with static value
2
3locals {
4 my_local = "value"
5}
As you can see in the above code locals are very easy to define. In the later section of this blog we will take a look on dynamic way to assign the value.
Here are the key properties of locals -
- Static Value - Terraform local can retain static value
- Dynamic Value - You can also assign dynamic value to Terraform local.
1## Example of local with dynamic value
2
3locals {
4 my_local = "${var.my_variable_value}"
5}
Table of Content
- Terraform Locals in nutshell
- Benefits of using Terraform Locals
- Create your first Terraform Local
- Combine terraform local with terraform variable
- Reference locals within locals
- Best practices for using locals
- Conclusion
1. Terraform Locals in a nutshell
Let's talk about the scope and visibility. Terraform Locals are only accessible within that functions or within the scope of terraform file. Here are few more points which you should take into consideration for the value assignment -
1. Value assignment- Terraform locals do not change their value once it is assigned, you have to re-assign a new value.
2. 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. Reference locals within locals
On a large Terraform project you might end up in a situation where you need to create multiple Terraform locals and even you might need to reference locals with other locals.
So terraform does provide support to reference Locals within Locals. Here is an example code-
1# Here I have first created my_first_local
2
3locals {
4 my_first_local = "value-1"
5}
6
7# Here my_second_local is referencing to my_first_local
8
9locals {
10 my_second_local = "value-2-${local.my_first_local}"
11}
Note- You need to make sure to prefix local before referencing to other local. Refer to this thread for more details
6. Best practices for using locals
- You should never 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.
7. 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 - Terragrunt -
Posts in this Series
- Securing Sensitive Data in Terraform
- Boost Your AWS Security with Terraform : A Step-by-Step Guide
- How to Load Input Data from a File in Terraform?
- Can Terraform be used to provision on-premises infrastructure?
- Fixing the Terraform Error creating IAM Role. MalformedPolicyDocument Has prohibited field Resource
- In terraform how to handle null value with default value?
- Terraform use module output variables as inputs for another module?
- How to Reference a Resource Created by a Terraform Module?
- Understanding Terraform Escape Sequences
- How to fix private-dns-enabled cannot be set because there is already a conflicting DNS domain?
- Use Terraform to manage AWS IAM Policies, Roles and Users
- How to split Your Terraform main.tf File into Multiple Files
- How to use Terraform variable within variable
- Mastering the Terraform Lookup Function for Dynamic Keys
- Copy files to EC2 and S3 bucket using Terraform
- Troubleshooting Error creating EC2 Subnet InvalidSubnet Range The CIDR is Invalid
- Troubleshooting InvalidParameter Security group and subnet belong to different networks
- Managing strings in Terraform: A comprehensive guide
- How to use terraform depends_on meta argument?
- What is user_data in Terraform?
- Why you should not store terraform state file(.tfstate) inside Git Repository?
- How to import existing resource using terraform import comand?
- Terraform - A detailed guide on setting up ALB(Application Load Balancer) and SSL?
- Testing Infrastructure as Code with Terraform?
- How to remove a resource from Terraform state?
- What is Terraform null Resource?
- In terraform how to skip creation of resource if the resource already exist?
- How to setup Virtual machine on Google Cloud Platform
- How to use Terraform locals?
- Terraform Guide - Docker Containers & AWS ECR(elastic container registry)?
- How to generate SSH key in Terraform using tls_private_key?
- How to fix-Terraform Error acquiring the state lock ConditionalCheckFiledException?
- Terraform Template - A complete guide?
- 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?
- Secure AWS EC2s & GCP VMs with Terraform SSH Keys!
- 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 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 Variables - Locals,Input,Output
- 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
- Install terraform on Ubuntu 20.04, CentOS 8, MacOS, Windows 10, Fedora 33, Red hat 8 and Solaris 11