I'm building a Terraform module that uses some variables for feature flags along with locals for storing some computed values. I'm bumping into some errors while a flag is true.
The flags (booleans saved as variables) are on every resource and use this convention which seems to be standard in Terraform:
resource "provider_resource_id" "resource_name" {
...
count = var.disable_resource ? 0 : 1
...
}
The provider outputs IDs when making these resources and because count
forces me to put an index on them, I'm saving them as locals in a locals.tf file to be less verbose:
locals {
resource_name_sid = provider_resource_id.resource_name[0].sid
}
I'm now running terraform apply
when disable_resource = true
and get this error: Invalid index: provider_resource_id.resource_name[0].sid (provider_resource_id.resource_name is empty tuple)
. I see that defining the local when the resource isn't created is a problem. So I commented out the local. Now I get other errors on all resources expecting the local: Reference to undeclared local value: (resource_name_sid has not been declared)
These resources wouldn't actually be built due to the flag, but they still expect the local (which I can't define because the resource isn't being built).
I bet I can put a ternary on every local to say, for example:
locals {
resource_name_sid = var.disable_resource ? "" : provider_resource_id.resource_name[0].sid
}
But that is getting verbose again. Maybe I can't externalize these locals and use feature flags at the same time. (I did try moving locals into the resources file but got the same result.) Maybe I need to abandon the use of locals for storing these and just put them inline in the resources. Or is there something I am missing?