Firebase configuration for multiple projects/environments

前端 未结 3 793
有刺的猬
有刺的猬 2020-12-14 01:22

I\'m using Cloud Functions for Firebase with three different projects for development, testing and production purposes. Each project has a service-account.json. When I deplo

3条回答
  •  无人及你
    2020-12-14 01:59

    Short answer: the GCLOUD_PROJECT environment variable will be unique to your project, hence you can utilise it like this (sample code is for 2 different projects but you can extend it using switch or any other conditional statement):

    const env = process.env.GCLOUD_PROJECT === 'my-app-prod' ? 'prod' : 'dev';
    

    then use that env variable to load intended configuration.

    Full example: (TypeScript)

    1. update .firebaserc file

      {
       "projects": {
          "default": "my-app-dev",
          "prod": "my-app-prod",
        }
       }
      
    2. create and modify your ./somewhere/config.ts file accordingly, let's say you're using AWS services (please ensure to secure your configuration details)

      export const config = {
        dev: {
          awsRegion: 'myDevRegion',
          awsAccessKey: 'myDevKey',
          awsSecretKey: 'myDevSecretKey'
        },
        prod: {
          awsRegion: 'myProdRegion',
          awsAccessKey: 'myProdKey',
          awsSecretKey: 'myProdSecretKey'
        }
      };
      
    3. now above items can be used in the index.ts file

      import { config } from './somewhere/config';
      import * as aws  from 'aws-sdk';
      . . .
      const env = process.env.GCLOUD_PROJECT === 'my-app-prod' ? 'prod' : 'dev';
      const awsCredentials = {
          region: config[env].awsRegion,
          accessKeyId: config[env].awsAccessKey,
          secretAccessKey: config[env].awsSecretKey
      };
      aws.config.update(awsCredentials);
      . . . 
      export const myFuncToUseAWS = functions....       
      
    4. Now the deployment

      Dev environment deployment: $ firebase deploy --only functions -P default

      Prod environment deployment: $ firebase deploy --only functions -P prod

提交回复
热议问题