Circleci - cannot read env variables defined inside script

I write a script for setting env variables.

export DB_HOST='127.0.0.1'
export DB_USER='ubuntu'
export DB_PWD=''
export DB_NAME='circle_test'

My circle.yml look like this

machine:
  timezone: Asia/Taipei
  services:
    - mysql

dependencies:
  pre:
    - sudo apt-get update
    - nvm install 7.9 && npm install

test:
  pre:
    - source ./config/test_config.sh
    - sh ./config/test_config.sh
    - pwd
    - printenv
  override:
    - nvm use 7.9 && npm test

My nodejs application cannot read the env variables and I didn’t saw in the printenv also.

I don’t want to write env variables directly into circle.yml file because I would like to have prod_config.shdev_config.sh to dynamically change.

How can I do that ?

Hi,

Every separate command (lines prefixed with -) is run in its own shell. This is why your environment variables, which you source, don’t exists in the following commands. There’s three ways I see going about this:

  1. Define your environment variables in circle.yml. I know you said you don’t want to do this, but this is the by far the easiest and most clear method.

  2. You can prefix the lines that need the variables with the source command. For example:

test:
  override:
    - source ./config/test_config.sh; nvm use 7.9 && npm test
  1. Take advantage of multiline YAML:
test:
  override:
    - >
      source ./config/test_config.sh
      nvm use 7.9 && npm test
  1. Or place all of the commands in its on Bash file and just run that script:
test:
  override:
    - ./all-commands-script.sh
1 Like

Thanks a lot ! You save my day.

1 Like