DEV Community

Cover image for Granting Access to Cloud Build - Impersonating a Service Account
Deniss T.
Deniss T.

Posted on

Granting Access to Cloud Build - Impersonating a Service Account


Another option to allow your team members to interact with the Cloud Build in your project is to impersonate a service account.


How it Works:

  1. Create a Service account giving it the Predefined roles or a Custom one (preferred) to grant it the required permissions.
  2. Your users will (only) need to have the following roles:
    • roles/iam.serviceAccountTokenCreator
    • roles/serviceusage.serviceUsageConsumer
  3. This will allow your team members to submit builds using the impersonation flag:

    gcloud builds submit \
      --config cloudbuild.yaml \
      --impersonate-service-account=<SERVICE_ACCOUNT>
      --gcs-log-dir=gs://<BUCKET_NAME>/<SUBDIRECTORY>
    

The Flaws of this Option

Allowing the users to impersonate service accounts like that will provide them with a lot of possibilities within the project as they will technically be able to list the service accounts within the project and impersonate any of them, thus having access not only to Cloud Build but other project resources as well.

Therefore, you should never grant the Service Account Token Creator role to a user this way.


Solution for the Service Account Token Creator role

Instead of giving users the project-wide Service Account Token Creator role for the account impersonation, you should make that role service account-specific.

Here is how you can do that via Cloud Console or CLI:

Cloud Console solution

  1. Navigate to IAM & Admin -> Service Accounts.
  2. Click 'SHOW INFO PANEL'.
  3. Select the relevant Service Account.
  4. Click 'ADD MEMBER'.
  5. Specify the user account granting it Service Account Token Creator role.
  6. Click 'SAVE'.

CLI solution

  1. Using the gcloud tool, add an IAM policy binding for the service account:

    gcloud iam service-accounts add-iam-policy-binding <SERVICE_ACCOUNT> \
      --member="user:<USER_ACCOUNT>" \
      --role="roles/iam.serviceAccountTokenCreator"
    
  2. To see the current IAM policy bindings run the following gcloud command:

    gcloud iam service-accounts get-iam-policy <SERVICE_ACCOUNT>
    

In this case, your team members (group) will only need to have the Service Usage Consumer role, while the Service Account Token Creator role will be bound only to the specified service account.


Top comments (0)