If
/Else
statements are conditional statements that carry out choices based mostly on some identified state, or variable.
Terraform permits you to carry out these if/else statements utilizing a ternary operation
which have develop into widespread as short-form if/else statements in lots of programming languages.
The place a language would write one thing just like:
let truthy = false
if (one thing == "worth") {
truthy = true
} else {
truthy = false
}
The ternary different 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 provides 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 can also make it extra readable by breaking it into a number of strains.
Be aware that so as to add a multiline ternary, it is advisable 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 properly if in case you have a single conditional, however should you want a number of conditionals, then you have to 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]]
)
)
}