How do I use service account in deployed code?

50 Views Asked by At

I have used the IAMCredentialsClient to generate an access token for the service account on a project

  const client = new IAMCredentialsClient();
  const [token] = await client.generateAccessToken({
    name: 'projects/-/serviceAccounts/[email protected]',
    scope: SCOPES,
  });

this has successfully authenticated as I now have an access token.

I have also used gcloud auth application-default login --impersonate-service-account [email protected] to allow running as a service account locally.

To initialise the API client, locally I can do something like this:

    const auth = new google.auth.GoogleAuth({
        keyFile: '../AppData/Roaming/gcloud/application_default_credentials.json',
        scopes: ['https://www.googleapis.com/auth/spreadsheets'],
      });
    const sheets = google.sheets({version: 'v4', auth});

This works locally but I plan to containerise this app and then deploy it with Cloud Run. Obviously using keyFile and a file path would not work. How would I write the code in a way that the production code knows to use the service account?

1

There are 1 best solutions below

13
John Hanley On

Google Cloud Run has a default service account and a metadata service. You can request access tokens from the metadata service.

In your post, you are impersonating a service account. You can attach any service account you require, assign IAM roles to that service account, and then request access tokens. There is no need to involve impersonation which would require more permissions than are necessary.

By using the default Cloud Run service account (service identity), you do not need to download, manage, protect, or deploy the service account key JSON file. This is a best practice.

Review this guide for more details on Cloud Run's Service Identity:

Google Cloud Run Service Identity