Search code examples
terraformterraform-provider-gcp

How to enable GCP service agent account via Terraform?


I understand there is a difference between a service account and a service agent for different services such as composer.

How do you enable a service agent via terraform?

What I'm trying to do is this :

# TODO : Maybe enable this service agent somehow via gcloud? It got enabled when trying to manually create the composer env from the console
# Step  4 (Src2) - Host project GKE service account: service-<some-numeric-id>@container-engine-robot.iam.gserviceaccount.com
# Need 'container.serviceAgent' in the host project
resource "google_project_iam_member" "dev-omni-orch-gke-project-lvl-roles-t2" {
  provider = google.as_super_admin
  for_each = toset([
    "roles/container.serviceAgent",
  ])
  role   = each.value
  member = "serviceAccount:service-<some-numeric-id>@container-engine-robot.iam.gserviceaccount.com"
  # member  = "serviceAccount:service-${google_project.main-shared-vpc-host.number}@container-engine-robot.iam.gserviceaccount.com"
  # project = google_project.dev-main-code-base.project_id
  project = google_project.main-shared-vpc-host.project_id
}

I get

 Request `Create IAM Members roles/container.serviceAgent serviceAccount:service-<some-numeric-id>@container-engine-robot.iam.gserviceaccount.com for project "<shared-vpc-host-project-id>"` returned error: Batch request and retried single request "Create IAM Members roles/container.serviceAgent serviceAccount:service-<some-numeric-id>@container-engine-robot.iam.gserviceaccount.com for project \"<shared-vpc-host-project-id>\"" both failed. Final error: Error applying IAM policy for project "<shared-vpc-host-project-id>": Error setting IAM policy for project "<shared-vpc-host-project-id>": googleapi: Error 400: Service account service-<some-numeric-id>@container-engine-robot.iam.gserviceaccount.com does not exist., badRequest

But when I try to do it via the console manually, there is a prompt that asks me if I want to enable this service agent, which I do, but I want to be able to do this on terraform.

The said prompt :

enter image description here


Solution

  • The service-[PROJECT_ID]@cloudcomposer-accounts.iam.gserviceaccount.com service agent will only exist after the Cloud Composer API has been enabled.

    This can be done in Terraform using the google_project_service resource, for example:

    resource "google_project_service" "project" {
      project = "your-project-id"
      service = "composer.googleapis.com"
    }
    

    Once the API has been enabled, the service agent should exist and you should be able to grant it the required permissions.