ternary
What is ternary?
ternary: The conditional expression: condition ? true_value : false_value. The closest HCL has to an if statement. Terraform's conditional expression, condition ? true_value : false_value, is the closest thing HCL has to an if statement. instance_type = var.env == "prod" ? "m5.large" : "t3.micro" picks a bigger server for production. Combined with count or for_each, it can switch resources on and off: count = var.enable_backups ? 1 : 0.
Frequently asked questions about ternary
What should you keep in mind with ternary?
Keep conditions simple and readable. Several nested ternaries in one line are hard to review. Move complex decisions into a locals block with descriptive names, or use a map lookup such as var.sizes[var.env], which scales better when you add more environments. Both branches must produce compatible types, which occasionally needs a conversion function like tostring().
What does an example of ternary look like?
instance_type = var.env == "prod" ? "m5.large" : "t3.micro" At a glance
| Category | Terraform |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |