0
votes

I am trying to setup Terraform to deploy into various AWS regions, I am sending the Region on the command line since its one of the few changing values in the script. I am using -var "region=east" - for example, and it works in other modules by assigning the region correctly, the main.tf where I am using this value is set correctly.

In creating a resource there is a lookup which uses region as mapped value, amis is a map of regions and different ami values I only want the ami that matches for this resource. I tried two methods, using the command line interpolation:

ami = "${lookup(var.amis, $${var.region})}"

or as an intermediate value

variables "map_region" {
  default = "${var.region}"
}
ami = "${lookup(var.amis, var.map_region)}"

Both give me syntax errors, though in looking through some of the documents with lookup I don't see where terraform supports this. Anyone else tried this successfully in some manner, or know a better way to pull out a value from a map using a command line variable?

EDIT: Part of the problem was hidden because I was using a Bash script to run the Terraform modules. This was running a destroy -force, then apply. Because I was considering the command line variables as part of the build I did not add them to the destroy command, which is where they were being requested and giving me a prompt to enter them. Once I added in the -var commands to the destroy command as well as apply this all worked.

1
You'll only ever need one set of ${} when using interpolation - anything inside of it will be rendered. I don't believe you can have interpolation inside of your variables. Does ${lookup(var.amis, 'us-east-1')} return what you want?TJ Biddle
Yes, it returns what I want but I need to use an interpolated value in someway so I can reuse the scripts for deploying in different regions.MichaelF

1 Answers

1
votes
ami = "${lookup(var.amis, $${var.region})}"

is wrong because $$ is only valid for interpolated variables within inline templates.

variables "map_region" {
  default = "${var.region}"
}
ami = "${lookup(var.amis, var.map_region)}"

does not work because you are passing a map as a key to lookup.

Terraform console is a useful tool for trying out interpolated expressions. Suppose the variables are defined as follows:

$ cat vars.tf
variable "amis" {
  type = "map"

  default {
    "us-east-2" = "ami-58f5db3d"
    "us-east-1" = "ami-fad25980"
  }
}

variable "region" {}

Fire up the console passing a value to region to emulate what you would be doing with plan, apply etc:

$ terraform console -var "region=us-east-1"
> var.region
us-east-1
> lookup(var.amis, var.region)
ami-fad25980

Hope this helps.