Home > Enterprise >  Terraform match multiple conditions in a single conditional
Terraform match multiple conditions in a single conditional

Time:12-09

I have 4 envs, qa and dev use one ID, uat and prod use another. I'm trying to do an if else, basically, if env is dev or qa, use id1, else use id2. This is what I tried:

locals{
  endpoint_id = "${var.env == "dev" || "qa" ? "id1" : "id2"}"
}

And this is what I get:

Error: Invalid operand
│ 
│   on ssm-parameters.tf line 2, in locals:
│    2:   endpoint_id = "${var.env == "dev" || "qa" ? "id1" : "id2"}"
│ 
│ Unsuitable value for right operand: a bool is required.

Apparently I can't do an "OR" here. How would I go about this? Thank you.

CodePudding user response:

How about:

locals{
  endpoint_id = length(regexall("dev|qa", var.env)) > 0 ? "id1" : "id2"
}

This will check if var.env matches either dev or qa, the output is a list, if there's some match the list will have at least one element and zero otherwise.

CodePudding user response:

It has to be a boolean expression on both sides of the or || operator. I'm not aware of any programming language where your syntax would be valid. It would need to look like this:

locals{
  endpoint_id = var.env == "dev" || var.env == "qa" ? "id1" : "id2"
}

This is because the boolean or operator applies to the boolean expression on its left, not the string value on its left. I've added parenthesis here to help visualize it:

locals{
  endpoint_id = (var.env == "dev") || (var.env == "qa") ? "id1" : "id2"
}
  • Related