Terraform Map Variable

A map value is a lookup table from string keys to string values. This is useful for selecting a value based on some other provided value.

A common use of maps is to create a table of machine images per region, as follows:

variable "images" {
  type    = "map"
  default = {
    "us-east-1" = "image-1234"
    "us-west-2" = "image-4567"
  }
}

lets take an simple example of terraform map

create a file with tf extension.

variable "usersage" {
    type = map
    default = {
        gaurav = 20
        saurav = 19
    }
}
output "userage" {
    value = "my name is gaurav and my age is ${lookup(var.usersage, "gaurav")}"
}

now let's run terraform apply and see the output

┌──(gaurav㉿learning-ocean)-[~/terraform/youtube-course/map-variable]
└─$ terraform plan

Changes to Outputs:
  + userage = "my name is gaurav and my age is 20"
You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:
userage = "my name is gaurav and my age is 20"

┌──(gaurav㉿learning-ocean)-[~/terraform/youtube-course/map-variable]
└─$

How to Read values Dynamically from Map Variable

lets create a file

variable "usersage" {
    type = map
    default = {
        gaurav = 20
        saurav = 19
    }
}

variable "username" {
  type = string
}

output "userage" {
    value = "my name is ${var.username} and my age is ${lookup(var.usersage, "${var.username}")}"
}

now lets run terraform apply

┌──(gaurav㉿learning-ocean)-[~/terraform/youtube-course/map-variable]
└─$ terraform plan -var username="gaurav"

No changes. Your infrastructure matches the configuration.
Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:
userage = "my name is gaurav and my age is 20"

How to pass Map Variable From Command line

┌──(gaurav㉿learning-ocean)-[~/terraform/youtube-course/map-variable]
└─$ terraform plan -var username="gaurav" -var usersage="{"gaurav"=22,"saurav"=23}"                                                                       1 ⨯

Changes to Outputs:
  + userage = "my name is gaurav and my age is 22"

You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.

Demo Video