terraform,

Enable/Disable resources conditionally in Terraform

Aug 02, 2022 · 1 min read · Post a comment

Since there isn’t any resource_enabled = false feature developed by Terraform yet, here’s a quick hack to enable / disable resources.

Prerequisites

  • Terraform

Solution

Step 1. Given the following Terraform code snippet:

## variables.tf
variable "enable_shared_vpc" {
  description = "Enable Shared VPC feature."
  default = false
}

variable "service_projects" {
  description = "List of service projects that gains access to network resources provided by its associated host project."
  default     = []
}

## main.tf
resource "google_compute_shared_vpc_host_project" "this" {
  count = var.enable_shared_vpc ? 1 : 0

  project = var.project
}

resource "google_compute_shared_vpc_service_project" "this" {
  count = length(var.service_projects)

  host_project    = google_compute_shared_vpc_host_project.this[0].id
  service_project = var.service_projects[count.index]
}

We can enable or disable the GCP Shared VPC feature per project. Considering count being the key factor here, we need an index right?! In this case host_project will always be referenced in other resources or outputs as the first element of a list even though it’s the only one – google_compute_shared_vpc_host_project.this[0].id.

Using the given example module above, a main GCP project will look something like this:

## main.tf
module "network" {
  source = "../modules/network"

  enable_shared_vpc = true
  project           = var.project_name
  service_projects  = ["devcoops-something", "devcoops-something-else"]
}

Conclusion

Tried everything and nothing works? Let me know in the comment section below. On a side note, follow our official channel on Telegram.