Terraform - outputs from disabled resources
A nice technique when using Terraform is to use modules that can be enabled or disabled depending on the requirements.
For example, consider the main.tf below
module "gke-network" { enabled = 1 source = "modules/network" gcp_project = "${var.gcp_project}" network_name = "${var.network_name}" } module "gke-cluster" { enabled = 1 source = "modules/gke" cluster_name = "${var.cluster_name}" gcp_region = "${var.gcp_region}" gcp_zone = "${var.gcp_zone}" gcp_project = "${var.gcp_project}" k8s_user = "${var.k8s_user}" k8s_password = "${var.k8s_password}" k8s_min_nodes = "${var.k8s_min_nodes}" network_name = "${module.gke-network.network_name == "" ? "default" : module.gke-network.network_name}" }
As can be seen, we're passing the new variable "enabled" and setting it to 1. The module code for gke-network looks like this
resource "google_compute_network" "db_network" { count = "${var.enabled}" name = "${var.network_name}" auto_create_subnetworks = "true" project = "${var.gcp_project}" } output "network_name" { value = "${join("", google_compute_network.db_network.*.name)}" }
You'll notice count has been added. This allows us to use the splat syntax for the network outputs (i.e because we've added count to the reource, terraform knows that google_compute_network.db_network will need to be an array).
So google_compute_network.db_network now becomes google_compute_network.db_network[n] or in terraform syntax google_compute_network.db_network.n.
This means we can substitute n with a wildcard (*)
Therefore, even when we disable gke-network by setting enabled to 0 in main.tf, terraform won't complain as it would do if we had used google_compute_network.db_network.0.name (i.e. because we would be referring to something that doesn't exist. Not sure why but when we use a wildcard terraform let's us get away with this fact.
Obviously the output would be blank and the consuming module would need to deal with this - I've shown an example using a conditional.
NOTE: the join there because the expected output is a string as opposed to an array.