Platform services in Google Cloud act in the context of a service account. While these default service identities are mostly generated automatically, it is not always deterministic when they are created. Some are created when the API is enabled, others will only be created on first use of the API. This makes it hard for managing IAM permissions for these identities - especially when employing infrastructure as code like Terraform.
Service Usage API to the rescue
Luckily the Service Usage API now features a new method (generateServiceIdentity
) in v1beta1 that ensures the service identity is being created and will return its identifier (namely the email address of the service account).
The endpoint is already available in gcloud beta and the following snippit will create the service identity for Cloud Build:
project="<PROJECT ID>"
service="cloudbuild.googleapis.com"
gcloud beta services identity create \
--project $project \
--service $service
The google-beta provider for Terraform also makes a resource available for direct use in Terraform:
resource "google_project_service_identity" "cloudbuild" {
provider = google-beta
project = "<PROJECT ID>"
service = "cloudbuild.googleapis.com"
}