javorosas
javorosas

Reputation: 769

How to authenticate to Cloud Storage from a Docker app on Cloud Run

I have a Node.js app in a Docker container that I'm trying to deploy to Google Cloud Run.

I want my app to be able to read/write files from my GCS buckets that live under the same project, and I haven't been able to find much information around it.

This is what I've tried so far:

1. Hoping it works out of the box

A.k.a. initializing without credentials, like in App Engine.

const { Storage } = require('@google-cloud/storage');

// ...later in an async function

const storage = new Storage();

// This line throws the exception below
const [file] = await storage.bucket('mybucket')
  .file('myfile.txt')
  .download()

The last line throws this exception

{ Error: Could not refresh access token: Unsuccessful response status code. Request failed with status code 500"
    at Gaxios._request (/server/node_modules/gaxios/build/src/gaxios.js:85:23)

2. Hoping it works out of the box after setting the Storage Admin IAM role to my Cloud Run service accounts.

Nope. No difference with previous.

3. Copying my credentials file as a cloudbuild.yaml step:

...
- name: 'gcr.io/cloud-builders/gsutil'
    args: ['cp', 'gs://top-secret-bucket/gcloud-prod-credentials.json', '/www/gcloud-prod-credentials.json']
...

It copies the file just fine, but then the file is nor visible from my app. I'm still not sure where exactly it was copied to, but listing the /www directory from my app shows no trace of it.

4. Copy my credentials file as a Docker step

Wait, but for that I need to authenticate gsutil, and for that I need the credentials.

So...

What options do I have without uploading my credentials file to version control?

Upvotes: 1

Views: 2272

Answers (2)

Hoopra
Hoopra

Reputation: 853

I believe the correct way is to change to a custom service account that has the desired permissions. You can do this under the 'Security' tab when deploying a new revision.

enter image description here

Upvotes: 0

javorosas
javorosas

Reputation: 769

This is how I managed to make it work:

  • The code for initializing the client library was correct. No changes here from the original question. You don't need to load any credentials if the GCS bucket belongs to the same project as your Cloud Run service.
  • I learned that the service account [myprojectid][email protected] (aka "Compute Engine default service account") is the one used by default for running the Cloud Run service unless you specify a different one.
  • I went to the Service Accounts page and made sure that the mentioned service account was enabled (mine wasn't, this was what I was missing).
  • Then I went here, edited the permissions for the mentioned service account and added the Storage Object Admin role.

More information on this article: https://cloud.google.com/run/docs/securing/service-identity

Upvotes: 1

Related Questions