App Engine environment variables

Load environment variables.

Nonsecret environment variables

You can add no secret environment variables simply by adding a couple of lines in app.yaml configuration file.

1
2
3
runtime: nodejs14
env_variables:
  NOT_SECRET_VARIABLE: "NOT_SECRET_VARIABLE"

Node.Js aplication can get NOT_SECRET_VARIABLE value from process.env.NOT_SECRET_VARIABLE.

DO NOT use such a method for secret environment variables, because the app.yaml values are visible in the repo. So everyone having access to the repo can see secrets.

Secret environment variables

Mandatory method for securely storing usernames, passwords, tokens, keys, and other secure information.

Enable the Secret Manager API

Go to Secret Manager API

/posts/gcp/app_engine_environment_variables/001_environment_variables.png

Add permissions for application access Secret Manager API

/posts/gcp/app_engine_environment_variables/002_environment_variables.png
Select edit App Engine default service account /posts/gcp/app_engine_environment_variables/003_environment_variables.png
Click Add another role. Select a role to add, such as Secret Manager Secret Accessor /posts/gcp/app_engine_environment_variables/004_environment_variables.png

Add secret

/posts/gcp/app_engine_environment_variables/005_environment_variables.png
/posts/gcp/app_engine_environment_variables/006_environment_variables.png
/posts/gcp/app_engine_environment_variables/007_environment_variables.png
/posts/gcp/app_engine_environment_variables/008_environment_variables.png

Write code

server.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const express = require('express');
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');
const client = new SecretManagerServiceClient();

async function getSecretValue(secret, v = "latest") {
  const [version] = await client.accessSecretVersion({
    name: `projects/${process.env.GOOGLE_CLOUD_PROJECT}/secrets/${secret}/versions/${v}`,
  });
  const payload = version.payload.data.toString('utf8');
  return payload;
}

const app = express();

app.get('/', async (req, res) => {
  const secretValue = await getSecretValue(process.env.SECRET_VARIABE);
  res.send(`Hello from App Engine! I see ${process.env.NOT_SECRET_VARIABLE} env variable! I see secret value ${secretValue}`);
});

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

Updating as well app.yaml

1
2
3
4
runtime: nodejs14
env_variables:
  NOT_SECRET_VARIABLE: "NOT_SECRET_VARIABLE"
  SECRET_VARIABE: "secret_value"