How to set environment variables using Google Cloud Build or other method in Google App Engine Standard Environment?

后端 未结 3 1530
情深已故
情深已故 2020-12-29 15:40

Is there anyway to inject environment variables from Cloud Build into the App Engine Standard environment?

I do not want to push my environment variables to GitHub

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 16:23

    Here is a tutorial on how to securely store env vars in your cloud build (triggers) settings and import them into your app.

    Basically there are three steps:

    1. Add your env vars to the 'variables' section in one of your build trigger settings

      Screenshot of where to add variables in build triggers

      By convention variables set in the build trigger must begin with an underscore (_)

    2. Configure cloudbuild.yaml (on the second step in the code example) to read in variables from your build trigger, set them as env vars, and write all env vars in a local .env file

      Add couldbuild.yaml (below) to your project root directory

    steps:
    - name: node:10.15.1
      entrypoint: npm
      args: ["install"]
    - name: node:10.15.1
      entrypoint: npm
      args: ["run", "create-env"]
      env:
        - 'MY_SECRET_KEY=${_MY_SECRET_KEY}'
    - name: "gcr.io/cloud-builders/gcloud"
      args: ["app", "deploy"]
    timeout: "1600s"

    Add create-env script to package.json

    "scripts": {
      "create-env": "printenv > .env"
    },

    1. Read env vars from .env to your app (config.js)

      Install dotenv package

      npm i dotenv -S

      Add a config.js to your app

    // Import all env vars from .env file
    require('dotenv').config()
    
    export const MY_SECRET_KEY = process.env.MY_SECRET_KEY
    
    console.log(MY_SECRET_KEY) // => Hello

    Done! Now you may deploy your app by triggering the cloud build and your app will have access to the env vars.

提交回复
热议问题