How to "simulate" or emulate if-then-else or case-statement in Terraform

2.6k Views Asked by At

I am looking for a way to do this in Terraform, if possible. Assume that ami and region are variables in the variable.tf file. (in pseudo-code)

If region = "us-east-1" then
  ami = "123455679"
else if region = "us-west-1" then
  ami = "98765432"
endif

I know there is no "if-then-else" or case-statements in Terraform but seems like there should be a way to do this.

Is it possible? Can you point me to an example or article?

TIA Bill W

1

There are 1 best solutions below

0
pkatsourakis On

I believe Conditional Expressions are what you are looking for

You can set the ami variable like this

ami = (region == "us-east-1" ? "123455679" : "98765432")

If you have more than 2 regions you can keep adding conditionals, although that may be hard to read. In that case you could use a map variable type (aka a dictionary).

ami = ({
  "us-east-1" = "123455679"
  "us-west-1" = "98765432"
})