How can I create an environment file during a cloud build process

Viewed 332

How can I pass environment variables to a Gatsby build task in a Google Cloud Build CI process? Using the substitution variables I can make variables available in the cloudbuild.json file but these then need to be available in the build task.

Gatsby uses a .env.production file to hold the environment variables which are then available using the dotenv package. At the top of my gatsby-config.js file I set the path to the environment file as follows:

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

Further down the file I use these variables to configure the gatsby-plugin-firebase plugin for Firebase. Given that I need an environment file, I have tried to create one in the cloudbuild.json file before running the build step.

{
  "steps": [
    {
      "name": "ubuntu",
      "args": ["echo", "FIREBASE_API_KEY=$_FIREBASE_API_KEY\\nFIREBASE_AUTH_DOMAIN=$_FIREBASE_AUTH_DOMAIN\\nFIREBASE_DATABASE_URL=$_FIREBASE_DATABASE_URL\\nFIREBASE_PROJECT_ID=$_FIREBASE_PROJECT_ID\\nFIREBASE_STORAGE_BUCKET=$_FIREBASE_STORAGE_BUCKET\\nFIREBASE_MESSAGING_SENDER_ID=$_FIREBASE_MESSAGING_SENDER_ID\\nFIREBASE_APP_ID=$_FIREBASE_APP_ID\\nFIREBASE_MEASUREMENT_ID=$_FIREBASE_MEASUREMENT_ID", ">", ".env.production"]
    },
    ...More steps here...
    {
      "name": "node:14.4.0",
      "entrypoint": "npm",
      "args": ["run", "build"]
    },
    {
      "name": "node:14.4.0",
      "entrypoint": "./node_modules/.bin/firebase",
      "args": ["deploy", "--project", "$PROJECT_ID", "--token", "$_FIREBASE_TOKEN"]
    }

The .env.production file does not exist when I get to the build step, which I think is because it has been created in the ubuntu container. How can I create an environment file that can be read by the build step. Or is there a better way of passing the variables?

Thanks,

1 Answers

Your first step is wrong, you only echo the command, not execute it. Change it like this

{
  "steps": [
    {
      "name": "ubuntu",
      "entrypoint": "bash",
      "args": ["-c", "echo FIREBASE_API_KEY=$_FIREBASE_API_KEY\\nFIREBASE_AUTH_DOMAIN=$_FIREBASE_AUTH_DOMAIN\\nFIREBASE_DATABASE_URL=$_FIREBASE_DATABASE_URL\\nFIREBASE_PROJECT_ID=$_FIREBASE_PROJECT_ID\\nFIREBASE_STORAGE_BUCKET=$_FIREBASE_STORAGE_BUCKET\\nFIREBASE_MESSAGING_SENDER_ID=$_FIREBASE_MESSAGING_SENDER_ID\\nFIREBASE_APP_ID=$_FIREBASE_APP_ID\\nFIREBASE_MEASUREMENT_ID=$_FIREBASE_MEASUREMENT_ID > .env.production"]
    },


Related