Variable keys in terraform maps

JoeyP picture JoeyP · Feb 18, 2016 · Viewed 49.5k times · Source

In Terraform, I'm trying to create a module with that includes a map with variable keys. I'm not sure if this is possible but I've tried the following without success.

resource "aws_instance" "web" {
    ami = "${var.base_ami}"
    availability_zone = "${var.region_a}"
    instance_type = "${var.ec2_instance_size}"
    security_groups = ["sec1"]
    count = "${var.ec2_instance_count}"
    tags {
        Name = "${var.role} ${var_env}"
        role = "${var.app_role}"
        ${var.app_role} = "${var_env}"
    }
}

and this:

tags {
   Name = "${var.role} ${var_env}"
}
tags."${var.role}" = "${var.env}"

Any ideas? Is this not possible with Terraform currently?

Answer

gsaslis picture gsaslis · Feb 14, 2017

There's (now) a lookup function supported in the terraform interpolation syntax, that allows you to lookup dynamic keys in a map.

Using this, I can now do stuff like:

output "image_bucket_name" {
  value = "${lookup(var.image_bucket_names, var.environment, "No way this should happen")}"
}

where:

variable "image_bucket_names" {
  type = "map"

  default = {
    development = "bucket-dev"
    staging = "bucket-for-staging"
    preprod = "bucket-name-for-preprod"
    production = "bucket-for-production"
  }

}

and environment is a simple string variable.