Search code examples
google-cloud-platformgcloudgoogle-iam

Creating a custom service account for Cloud Run using the gcloud CLI


Background

By default, Cloud Run uses the Compute Engine default service account which grants a broad range of permissions which are not required by the container that I'm trying to run in it, and as a result I'd like to set up a new service account.

If I understand correctly, I'd need to do the following:

  1. Create a role with the desired set of permissions (using gcloud iam roles create)
  2. Create a service account (using gcloud iam service-accounts create)
  3. Bind the role permissions to the service account.
  4. Deploy an image with the service account set up in step 2 (using gcloud run deploy --service-account).

The aforementioned documentation doesn't mention how to achieve step 3. I found the gcloud iam service-accounts add-iam-policy-binding command, but I see this is a three way binding between an user (member), a service account and a role, whereas what I've described above seems to require only a two-way binding with the permission grant to the Cloud Run service occurring in the fourth step.

Questions

  1. Do I have the right understanding with regards to the steps required to set up a custom service account for Cloud Run to use?
  2. Assuming I have understood this correctly, what would be the correct way to set up the binding of permissions with the service account?

Solution

  • You can use a custom role in addition of user managed service account, but it's not mandatory. You can also create a user managed service account and bind it with predefined roles.

    Anyway, if you want to bind a custom role to a service account (or a user account, no difference), you have to use the fully qualified path for the role

    # Project level
    projects/<projectID>/roles/<custom role name>
    # Organization level
    organizations/<organizationID>/roles/<custom role name>
    

    And the gcloud command can be this one

    gcloud projects add-iam-policy-binding <projectID> \
      --member=serviceAccount:<service account email> \
      --role=projects/<projectID>/roles/<custom role name>