Search code examples
google-cloud-platformterraformservice-accountsimpersonation

GCP Service Account Impersonation using Terraform


I am trying to impersonate a GCP service account with the following code in provider.tf file

locals {
 terraform_service_account = "[email protected]"
}

provider "google" {
 alias = "impersonation"
 scopes = [
   "https://www.googleapis.com/auth/cloud-platform",
   "https://www.googleapis.com/auth/userinfo.email",
 ]
}

data "google_service_account_access_token" "default" {
 provider                   = google.impersonation
 target_service_account     = local.terraform_service_account
 scopes                     = ["userinfo-email", "cloud-platform"]
 lifetime                   = "1200s"
}

provider "google" {
 project        = "projectx-4567"
 access_token   = data.google_service_account_access_token.default.access_token
 request_timeout    = "60s"
}

My Service Account has the following roles

   "roles/container.admin",
    "roles/compute.admin",
    "roles/servicemanagement.admin",
    "roles/iam.serviceAccountUser",

Also the default login has the iam.serviceAccountTokenCreator role

however the service account does seem to have access to the service usage api

Error: Error when reading or editing Project Service : Request List Project Services projectx-4567 returned error: Failed to list enabled services for project projectx- 4567: googleapi: Error 403: Service Usage API has not been used in project 1355341940 before or it is disabled. Enable it by visiting https://console.developers.google. com/apis/api/serviceusage.googleapis.com/overview?project=1355341940 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

how to fix this

If I enable the API manually I am able to get a success but I want the serviceaccount to be able to enable the api


Solution

  • Can you try enabling it using terraform:

    resource "google_project_service" "serviceusage_api" {
      project            = "projectx-4567"
      service            = "serviceusage.googleapis.com"
      disable_on_destroy = false
    }