Search code examples
google-cloud-platformterraformgithub-actionsservice-accounts

Cloud Build: The user is forbidden from accessing the bucket


In my project, I have created a container registry:

resource "google_container_registry" "registry" {
  project  = var.project_id
  location = "EU"
}

data "google_iam_policy" "admin" {
  binding {
    role    = "roles/storage.admin"
    members = [
      "serviceAccount:${local.terraform_service_account}",
    ]
  }
}

resource "google_storage_bucket_iam_policy" "policy" {
  bucket      = google_container_registry.registry.id
  policy_data = data.google_iam_policy.admin.policy_data
}

There's also an additional service account (github-sa), dedicated for GitHub, which does have the following roles attached to it:

resource "google_project_iam_member" "github_service_account_service_usage" {
  for_each = toset([
    "roles/serviceusage.serviceUsageAdmin",
    "roles/storage.objectAdmin"
  ])
  role    = each.key
  member  = "serviceAccount:${google_service_account.github_service_account.email}"
  project = var.project_id
}

Using account impersonation, I am trying to build a Docker image via GitHub Actions like so:

      - id: 'auth'
        name: 'Authenticate to Google Cloud'
        uses: 'google-github-actions/auth@v0'
        with:
          token_format: 'access_token'
          workload_identity_provider: ${{ env.gh_wip }}
          service_account: ${{ env.gh_sa }}  # github-sa
          create_credentials_file: true

      - name: 'Set up Cloud SDK'
        uses: google-github-actions/setup-gcloud@v0
        with:
          project_id: ${{ env.project_id }}

      - name: "show account"  # Prints the correct github-sa
        run: gcloud config list account --format "value(core.account)"

      - name: 'Build Docker image'
        run: |
          gcloud builds submit --config backend/docker/cloudbuild.yaml . \
            --substitutions=IMAGE_TAG="gcr.io/mnist",IMAGE_VERSION="v0.0.2"

However, the gcloud builds submit command fails with the following error:

Run gcloud builds submit --config backend/docker/cloudbuild.yaml . \
ERROR: (gcloud.builds.submit) The user is forbidden from accessing the bucket [dev-00-ebcd_cloudbuild]. Please check your organization's policy or if the user has the "serviceusage.services.use" permission
Error: Process completed with exit code 1.

Here's to verify that said service account has the Service Usage Admin and Storage Object Admin role set:

enter image description here

Why am I not able to build the Docker image here?


Solution

  • For some unknown reason (hello, Google Cloud Build!), your github-sa needs to have storage.buckets.list permission on your project. You can grant it by changing roles/storage.objectAdmin role to roles/storage.admin at project level.

    Also, it needs roles/cloudbuild.builds.editor to actually create a build.