Enable/Disable resources conditionally in Terraform

Aug 02, 2022 · 1 min read · 2 views · 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.


  • Terraform


Step 1. Given the following Terraform code snippet:

## 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]

## 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     = []

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"]


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