If
/Else
statements are conditional statements that carry out selections based mostly on some identified state, or variable.
Terraform permits you to carry out these if/else statements utilizing a ternary operation
which have turn into widespread as short-form if/else statements in lots of programming languages.
The place a language would write one thing much like:
let truthy = false
if (one thing == "worth") {
truthy = true
} else {
truthy = false
}
The ternary various could be:
let truthy = one thing == "worth" ? true : false
Or much more simplified:
let truthy = one thing == "worth"
If/Else in Terraform – Utilizing a Ternary
As Terraform solely offers the choice of utilizing a ternary, the next might be used:
vpc_config {
subnet_ids = (var.env == "dev") ? [data.aws_subnets.devsubnets.ids[0]] : [data.aws_subnets.prodsubnets.ids[0]]
}
You may make it extra readable by breaking it into a number of traces.
Notice that so as to add a multiline ternary, you have to wrap the assertion in brackets (...)
vpc_config {
subnet_ids = (
(var.env == "dev") ?
[data.aws_subnets.devsubnets.ids[0]] :
[data.aws_subnets.prodsubnets.ids[0]]
)
}
Including a number of If/Else statements in a single block
The above works nicely when you have a single conditional, however should you want a number of conditionals, then you will have to do the next:
vpc_config {
subnet_ids = (
(var.env == "dev") ?
[data.aws_subnets.devsubnets.ids[0]] :
(var.env == "uat" ?
[data.aws_subnets.uatsubnets.ids[0]] :
[data.aws_subnets.prodsubnets.ids[0]]
)
)
}