Chris Edwards
Chris Edwards

Reputation: 484

Terraform dynamic variable lookup

I am writing some terraform code that looks up the ami based on a variable called fortios_version. I seem to not understand how to have a map pass back a map value. Here is my code...

variable "fortios_version" {
  type        = string
}

variable "fortios_map" {
  type = map
  default = {
    "7.2.0" = "fgtvmbyolami-7-2-0"
    "6.4.8" = "fgtvmbyolami-6-4-8"
  }
}

variable "fgtvmbyolami-7-2-0" {
  type = map
  default = {
    us-east-1      = "ami-08a9244de2d3b3cfa"
    us-east-2      = "ami-0b07d15df1781b3d8"
  }
}

My aws instance code:

ami                     = lookup(lookup(var.fortios_map[var.fortios_version]), var.region)

My variable:

fortios_version: "7.2.0"

I hope I am making sense. I have played with different variations all day with no luck.

Upvotes: 1

Views: 632

Answers (1)

Marcin
Marcin

Reputation: 238827

You can't dynamically refer to fgtvmbyolami-7-2-0 based on the output of fortios_map. It would be best to re-organize your variables:

variable "fortios_version" {
  type        = string
}

variable "fortios_map" {
  type = map
  default = {
    "7.2.0" = "fgtvmbyolami-7-2-0"
    "6.4.8" = "fgtvmbyolami-6-4-8"
  }
}

variable "amis" {
  type = map
  default = {
    "fgtvmbyolami-7-2-0"  =  {
          us-east-1      = "ami-08a9244de2d3b3cfa"
          us-east-2      = "ami-0b07d15df1781b3d8"
        },
    "fgtvmbyolami-6-4-8"  =  {
          us-east-1      = "ami-08a92333cfa"
          us-east-2      = "ami-0b07dgggg781b3d8"
        }        
  }
}

then

ami  = var.amis[var.fortios_map[var.fortios_version]][var.region]

You can expand this to ad lookup in to have some default values for each map.

Upvotes: 2

Related Questions