Terraform Locals
Hello Everyone
Welcome to CloudAffaire and this is Debjeet.
In the last blog post, we have discussed terraform backends.
https://cloudaffaire.com/terraform-backends/
In this blog post, we will discuss terraform locals.
What is terraform local?
The local block defines one or more local variables within a module. Comparing modules to functions in a traditional programming language, if input variables are analogous to function arguments and outputs values are analogous to function return values, then local values are comparable to a function’s local temporary symbols.
Each locals block can have as many locals as needed, and there can be any number of locals blocks within a module. The names given for the items in the local block must be unique throughout a module. The given value can be any expression that is valid within the current module. The expression of a local value can refer to other locals, but as usual reference cycles are not allowed. That is, a local cannot refer to itself or to a variable that refers (directly or indirectly) back to it.
Next, we are going to explain terraform locals with a demo.
Terraform locals:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
##---------------------- ## Terraform: Local ## ##---------------------- ## Create a directory and get inside it mkdir terraform && cd terraform ## Create resources vi main.tf ------------------ #declare variable variable "name" { default = "myapp" } #aws provider provider "aws" { access_key = " secret_key = " region = "ap-south-1" } #get region details data "aws_region" "myregion" {} #get availability zone details data "aws_availability_zones" "myavailabilityzones" {} #get account details data "aws_caller_identity" "myidentity" {} #declare local locals { tag_prefix = "${var.name}_${data.aws_caller_identity.myidentity.account_id}_${data.aws_region.myregion.name}" } #create vpc resource "aws_vpc" "myvpc" { cidr_block = "10.0.0.0/16" enable_dns_hostnames = true tags { Name = "${local.tag_prefix}_vpc" #local block called } } #create subnet resource "aws_subnet" "myvpc_subnet" { vpc_id = "${aws_vpc.myvpc.id}" cidr_block = "10.0.0.0/24" availability_zone = "${data.aws_availability_zones.myavailabilityzones.names[0]}" tags { Name = "${local.tag_prefix}_subnet" #local block called } } ------------------ :wq ## Format code terraform fmt ## Initialize terraform terraform init ## Create the resource terraform apply ## Show state terraform show ## Cleanup ## Destory resources terraform destory ## Remove terraform directory cd .. && rm -rf terraform |
Hope you have enjoyed this article. In the next blog post, we will discuss terraform imports.
To get more details on terraform, please refer below terraform documentation.
https://www.terraform.io/docs/index.html