gcp, terraform,

Enable Google APIs with GCP and Terraform

Jun 27, 2022 · 2 mins read · 29 views · Post a comment

Terraforming GCP projects from scratch could be a lot of hustle and bustle as you need to enable almost every freaking Google service (API) per project. That’s probably first and foremost, then you got service account impersonation, permissions and-so-forth just to get a simple project up and running in line with best practices, right?!

Okay, since I’m done ranting, let me show you two simple TF code snippets that could help you with enabling google APIs per GCP project.

Prerequisites

  • GCP account
  • Terraform

Solution(s)

Solution #1

What works for me though:

## variables.tf
variable "gcp_services_list" {
  description = "The list of GCP APIs necessary for the project."
  type        = list(string)
  default     = ["cloudresourcemanager.googleapis.com"]
}

## terraform.tfvars
gcp_services_list = [ 
    "cloudresourcemanager.googleapis.com",
    "cloudbilling.googleapis.com"
]

## main.tf
resource "google_project_service" "enable_google_apis" {
  count   = length(var.gcp_services_list)
  project = google_project.this.project_id
  service = var.gcp_services_list[count.index]

  disable_dependent_services = true
}

Solution #2

Alternate solution for those who experience dependency errors:

## variables.tf
variable "project_id" {
  description = "The project ID."
  type        = string
}

## terraform.tfvars
project_id = "<some_project_id>"

## main.tf
resource "null_resource" "enable_google_apis" {
  provisioner "local-exec" {
    command = "gcloud services enable cloudbilling.googleapis.com cloudresourcemanager.googleapis.com --project ${var.project_id}"
  }

  depends_on = [google_project.this]
}

resource "time_sleep" "wait_project_init" {
  create_duration = "60s"

  depends_on = [null_resource.enable_google_apis]
}

Note(s): Doesn’t scale well, for the reason that the required APIs are hardcoded, but it gets the job done.

Solution #3

The old school way. Enabling APIs manually from the GCP Console. As usually, it should be a one-time task to a certain extent, although it’s prone to human error.

Conclusion

Any questions, thoughts and opinions are much appreciated. On a side note, follow our official channel on Telegram.