鄭元傑
鄭元傑

Reputation: 1677

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 ?

Upvotes: 2

Views: 649

Answers (1)

FelicianoTech
FelicianoTech

Reputation: 4017

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

3) Take advantage of multiline YAML:

test:
  override:
    - >
      source ./config/test_config.sh
      nvm use 7.9 && npm test

4) Or place all of the commands in its on Bash file and just run that script:

test:
  override:
    - ./all-commands-script.sh

-Ricardo N Feliciano
Developer Evangelist, CircleCI

Upvotes: 3

Related Questions