Bypassing Terraform error: “The true and false result expressions must have consistent types”
2 min readMar 18, 2023
Available for free in English & Portuguese at my personal website.
Have you ever came across this Terraform error — when you intentionally want your ternary to output different types?
The true and false result expressions must have consistent types
To bypass this Terraform limitation, check the tip below. I'll follow it with two examples to clarify the usage:
attribute = [
<desired output if true>,
<desired output if false>
][<condition> ? 0 : 1]
Simple example
locals {
dynamic_value = [
{"region": "${var.region}"},
"unavailable"
][var.region == "eu-west-1" ? 0 : 1 ]
}
Here, local.dynamic_value
will return an object if the AWS region is Ireland, or the string "unavailable"
for any other region.
Wait, what's just happened?
Instead of using the ternary in the traditional way, we defined a tuple (aka, a list with mixed types), and used the ternary to return the index for the output we really want. Thanks mariux for the trick.