Securely store .env variables of your nodejs api in cloud Storage Bucket

Trevor (Al Rashid)
2 min readOct 21, 2020

--

I assume your project has this already set up:

  • a CI CD with Cloud Build
  • Deploying on either Cloud Run or Google Kubernetes Engine
  • Use Github for code hosting

This is a section in one of my blogs about my assignments in one of the projects am currently contributing concerning DevOps practices. I decided to extract it out separately because its one of the major security practices as you develop your APIs.

Briefly, as we write APIs we always put the .env file in the .gitignore file so no chances to appear on github. However if you to set up a CI CD with cloud Build you may be forced to push the .env because cloud Build uses the variables to create the API Docker image for deployment.

I have seen this being done in some projects, however much we use private repos, not everyone should be able to access the .env file especially outside collaborators, as its a big security risk.

Let me first summarise the steps I have added:

  1. Create a cloud storage bucket
  2. Push the .env file to that storage bucket using gsutil command
  3. In cloudbuild.yaml file add a command to instruct Cloud Build to first copy the .env file as it starts building the image

Push the .env.production file to the cloud storage bucket

This can be done from the cloud console or command line if you have gcloud SDK installed. I will use the command line

Using gsutil command, we create the storage bucket and push the file. Will name our storage bucket node-api secretes

$ gsutil mb gs://node-api-secrets/
$ gsutil cp .env.production gs://node-api-secrets/

Update your cloudbuild.yaml file with first command that instructs cloud build to copy the .env file before building the image.

steps:  
# Copy .env file from storage bucket
- name: "gcr.io/cloud-builders/gsutil" args: ["cp", "gs://myapi-secrets/.env.prod", ".env"]

# build the container image
# push the container image to gcr
# Deploy container image to Cloud Run

The rest of process remains the same as before.

Read here… for a complete implementation of CI CD with cloud build

As i made research i found other option of adding .env secretes in cloud build variables however the above process is easier.

--

--

Trevor (Al Rashid)

Cloud Engineer | Educator | Entrepreneur | Champion Innovator at Google Cloud Innovators 🎖️