Authentication when running Google Cloud Run functions locally with Functions Emulator

Published:

In short:

gcloud alpha functions local deploy <function-name> --set-env-vars=GOOGLE_APPLICATION_CREDENTIALS=./creds.json
gcloud alpha functions local call <function-name> --impersonate-service-account="<account>"

This information was difficult to find for me as I find the Functions Emulator to be quite immature as a product (it's alpha as it says) and poorly documented, even though it seems like a great idea.

Google Application Default Credentials can be set using an environment variable, and because Functions Emulator runs in a Docker container, we need to get that env variable set during the deploy. The creds.json file should be a JSON API key for the service user you are running the function as, which you can download from the Google Cloud console.

It's not ideal having the creds in a file in your codebase. You'll want a .gitignore entry to avoid it being committed to git, but accidents can still happen. This however was the first time I've been able to authenticate when running a cloud function locally, so it's useful for now.

Deploy

It's also best not to deploy the creds file to Google Cloud. A `.gcloudignore` file can contain a list of files not to deploy (a bit like `.gitignore`). But if we do that, then the creds file won't get deployed locally either, and we need the deployed container to see it (in fact, we only need it locally). The way I've gotten round that is when deploying to live/staging/etc:

gcloud functions deploy ... --ignore-file=.gcloudignore-non-local

Instead of using a `.gcloudignore` I'm specifying my own ignore file, which contains one line: `creds.json`. Then when I deploy locally, the `.gcloudignore-non-local` is ignored and `creds.json` is seen by the local container