Iqbal´s DLQ main Help

Terraform - conditional on properties

toggle - if-else construct

In Terraform, it seems HCL does not always have concise language structures for conditionals on block of properties

Take for instance this made up example where we toggle between protocols:

dynamic "protocol" { for_each = var.toggle == "http" ? [{}] : [] content { http_props { version = "2" ssl = true } } } dynamic "protocol" { for_each = var.toggle == "websocket" ? [{}] : [] content { websocket_props { binaryType = "blob" } } }

depending on the value of var.toggle ("http" or "websocket") will either generate

Result 1

protocol { http_props { version = "2" ssl = true } }

Or

Result 2

protocol { websocket_props { binaryType = "blob" } }

validation

Also, AFAIK no proper way to make enums, and we can see the need in the previous example where the toggle can only have one of the two values (http, websocket)

The closest we have in HCL as of now is to use terraform validation on that variable declaration

variable "toggle" { type = string default = "http" description = "chosen protocol, possible values (http,websocket)" validation { condition = contains(["http", "websocket"], var.toggle) error_message = "validation error, allowed values are http, websocket" } }
Last modified: 12 March 2024