Mark
Mark

Reputation: 4935

How to set AWS S3 credentials in a Google Firebase cloud function?

I want my Firebase cloud function to access AWS S3. To do that, in my index.js file I am trying to tell AWS to look at the awscred.json file to get the connection credentials like this:

// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the Region
AWS.config.loadFromPath('./awscred.json');

This works fine when I test it locally, but when I try to deploy to the cloud I get this error:

Error: ENOENT: no such file or directory, open './awscred.json'

How can I add the file 'awscred.json' to the cloud function package? Do I need to add something to the package.json file?

Upvotes: 5

Views: 2070

Answers (3)

Caio Santos
Caio Santos

Reputation: 1805

You can set your credentials as env vars from your terminal:

firebase functions:config:set aws.aws_access_key_id="XXXXX" aws.secret_access_key="YYYYY"

and then, read them within your function like this:

const functions = require("firebase-functions")
const AWS = require('aws-sdk')

const { aws: { secret_access_key, aws_access_key_id } } = functions.config()

AWS.config.update({
    region: 'us-east-1',
    accessKeyId: aws_access_key_id,
    secretAccessKey: secret_access_key
})

if you want, you can see the current env vars:

firebase functions:config:get

Firebase does not allow uppercase named env vars, so I had to use the strategy above.

Upvotes: 1

Mark
Mark

Reputation: 4935

So it turned out that during the deployment process (ie. from local machine to Google's servers) the index.js file is run on my local machine. The error was generated because there was no 'awscred.json' file in the directory I was running my 'firebase deploy' command, so the solution was to just execute that command in my functions directory instead.

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317712

Just put the awscred.json file in your function source code deployment folder along with the source code. It will be deployed along with all the other source code so that it can be used while being run in Cloud Functions. If you want to load it from the relative path "./awecred.json" then it should exist right next to the source file.

Upvotes: 4

Related Questions