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

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.