How to include storage service account key in func

2019-08-18 23:52发布

问题:

I'm trying to include service account key into my storage function to be able to get long lived signed url by following out of date example here

https://github.com/firebase/functions-samples/blob/b404482342906ee1b46dddb4c75667685ab098a1/generate-thumbnail/functions/index.js#L21

I have downloaded my key from IAM which is in JSON format. I have tried to save it right next to my function

-functions/storage/resizeProfileImg.js

-functions/storage/service-account-credentials.json

-functions/index.js

-functions/admin.js

where resizeProfileImg.js is my function and call it like this

const { Storage } = require('@google-cloud/storage');
const storage = new Storage({ projectId: projectId ,keyFilename: './service-account-credentials.json'})

but after deployment when the function is triggered then I get an error

Error: ENOENT: no such file or directory, open '/srv/service-account-credentials.json'

I have even tried to add it in constant like this

const serviceAccountCredentials = require('./accountKey/service-account-credentials.json')

const { Storage } = require('@google-cloud/storage');
const storage = new Storage({ projectId: projectId ,keyFilename: serviceAccountCredentials})

but then I get an error

TypeError: Path must be a string. Received { type: 'service_account',...

Any idea how to do this properly

回答1:

In Cloud Functions, the current directory . isn't where your source file is located. It's where the functions folder was deployed. Since your credentials file is in a subdirectory called "storage", you will need to use that in the path.

const serviceAccountCredentials = require('./storage/service-account-credentials.json')