Search code examples
bashshellenvironment-variablesgoogle-cloud-buildcloudbuild.yaml

How to retain existing env variables in a new shell


I know I must be doing something silly here, but I'm trying to pass environment variables to a command being run under /bin/sh -c in Cloud Build.

My Cloud Build file looks like this:

 - id: db-migrate
  name: node:16.13.0
  dir: 'packages/backend'
  entrypoint: '/bin/sh'
  args: 
 - '-c'
 - '(/workspace/cloud_sql_proxy -dir=/workspace -instances=$_DB_CONNECTION=tcp:127.0.0.1:5432 & sleep 2) && yarn db:migrate'
  env:
 - 'DB_HOST=127.0.0.1'
 - 'DB_USER=$_DB_USER'
 - 'DB_PASSWORD=$_DB_PASSWORD'
 - 'DB_NAME=$_DATABASE'

My Cloud Build Trigger has the substitutions set, and when I look at the build details it shows the environment variables as set.

However the command yarn db:migrate acts as if there are no env variables set. I believe this is because they aren't being passed from the machine to the command.

Any idea what I'm doing wrong?

The problem here is that when we call bin/sh it's creating a new shell with it's own environment variables. While I read through the manual on SH/Dash I will leave this question here: How do I retain existing env variables in a new shell?


Solution

  • Alright, I figured this out.

    We were using TypeORM, and originally used a ormconfig.json file. Turns out, this was still being picked up somehow on the system and was overriding all env variables.

    Posting this response to help others in case they make this same mistake.