Is it possible to display output conditionally?

I would like to be able to display output conditionally, along the lines of:

variable "vue_enabled" {
 description = "Set to true to enable building a vue queue"
 default = false
}

output "vue_queue" {
    value = "${var.vue_enabled ? aws_sqs_queue.vue_queue.id : ""}"
}

Where the vue_queue output gives the resource id if it exists, or and empty string (or not all) if not.

Is this possible in Terraform?

Thanks!

1 Like

What you wrote here should work, indeed. Though given your phrasing about “displaying” the output, I think you’re talking about outputs in a root module and about how they are rendered to the terminal at the end of terraform apply.

With a configuration like you showed here, terraform apply would still mention this output value, but would show it as having an empty string as its value.

If you are using Terraform 0.12 then I believe you could hide it altogether by setting it to null conditionally, like this:

output "vue_queue" {
    value = var.vue_enabled ? aws_sqs_queue.vue_queue.id : null
}

With that said, hiding output values from the display is not really an intentional feature right now, so whether the above works may depend on the version of Terraform you are running and may change in future versions of Terraform.

2 Likes

a small caveat of this approach is the output “schema” becomes conditional and the consumer (remote state data source) need to run extra validation

for the same reason, I slightly prefer using

output "vue_queue" {
    value = try(aws_sqs_queue.vue_queue[0].id, "")
}

I think the schema of the output should be consistent, but the value can be conditional.

the implicit assumption here is the resource is also conditionally created. e.g.

resource "aws_sqs_queue" "vue_queue" {
  count = var. vue_enabled ? 1 : 0
  ...
}

Hi @duxing,

The try call in your example doesn’t do anything, because the static reference to aws_sqs_queue.vue_queue.id can’t fail, so the default can’t ever be chosen. If you want an empty string as the default value, then replacing null with "" in the conditional expression should suffice.