Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Key/Values from Terraform Map Variable

I am trying to extract both left and right values from the terraform map variable but couldn't extract the left value. Below is my code :-

variables.tf
  variable "notebook" {
    type = "map"
    default = {
    "01" = "[email protected]"
    "02" = "[email protected]"
    "03" = "[email protected]"
    "04" = "[email protected]"
    ......
  }
}

Below is my module in main.tf

 module "instance" {
   instance_ip = ["1.1.1.x", "1.1.2.y", "1.1.1.z","1.1.2.p"]
   dns         = ["x", "y", "z","p"]
   name        = ["a", "b", "c",  "d"]
 }

The output should be as below :-

 module "instance" {
   instance_ip = ["1.1.1.01", "1.1.2.02", "1.1.1.03","1.1.2.04" and so on]
   dns         = ["01", "02", "03","04" and so on]
   name        = ["[email protected]", "[email protected]", "[email protected]", "[email protected] and so on]
 }

Any suggestions. I tried lookup on variable but getting only the [email protected] and not the Key's.

like image 321
Lucky Avatar asked May 24 '26 21:05

Lucky


1 Answers

You can use the keys and values functions for this:

# terraform 0.12
module "instance" {
  instance_ip = ["1.1.1.${keys(var.notebook)[0]}", "1.1.1.${keys(var.notebook)[1]}", "1.1.1.${keys(var.notebook)[2]}"]
  dns         = keys(var.notebook)
  name        = values(var.notebook)
}

# terraform 0.11
module "instance" {
  instance_ip = ["1.1.1.${keys(var.notebook)[0]}", "1.1.1.${keys(var.notebook)[1]}", "1.1.1.${keys(var.notebook)[2]}"]
  dns         = ["${keys(var.notebook)}"]
  name        = ["${values(var.notebook)}"]
}
like image 77
Matt Schuchard Avatar answered May 28 '26 05:05

Matt Schuchard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!