Search code examples
firebasegoogle-cloud-platformgoogle-cloud-functionsservice-accountsfirebase-cli

Deploying different service-account-credentials.json file to different cloud functions


Working on creating two separate Firebase Projects, one as a dev environment and the other as our production environment so as to simulate the real thing when testing new features.

Whenever I need to deploy to the cloud functions to either of the projects I do the following things:

  1. Copy and paste the correct service account credentials into the service-account-credentials.json file

  2. Select respective project's alias (dev or prod)

firebase use dev or firebase use prod

  1. Deploy cloud functions to respective project

firebase deploy --only functions

I feel like this is the naive and tedious way of doing this. Is there a better way of doing this where I can have a service-account-credentials-prod.json and a service-account-credentials-dev.json file in my functions directory, then depending on which project alias I'm using, it will know which service account credentials to deploy?

Would greatly appreciate if someone could point me in the right direction


Solution

  • I have two projects as well, development and production.

    In /functions I have both files:

    /functions/production-cred.json and

    /functions/development-cred.json

    I deploy using the respective commands:

    firebase deploy --only functions -P development or

    firebase deploy --only functions -P production.

    In index.js I use the environment variable process.env.GCLOUD_PROJECT to determine which environment is being used. This variable will contain the name of your project, which should be different between production and development, you cant print it to check.

    Here's a sample:

    const env = process.env.GCLOUD_PROJECT
    const development = (env == "myDevProject")
    const database = development ? devDbUrl : prodDbUrl
    const serviceAccountFile = development ? "devCred.json" : "prodCred.json"
    const serviceAccount = require(`./${serviceAccountFile}`)
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: database
    })
    

    Doing it this way doesn't require you to set the alias with firebase use dev|prod. I used to do it the same way as you, and this improvement has made deploys faster and more reliable.