Setting environment variables per branch in Gitlab CI or “a poor man’s dotenv”

Phillip Kessels
spacepilots
Published in
1 min readMay 15, 2019

Often times a different set of environment variables is needed when executing jobs in Gitlab CI depending on the branch we are on. The following is a real life example for the website of our shift scheduling software at tiftapp.com.

We build our website with Hugo and deploy it to different subdomains. From our develop branch we want to deploy to staging and from master we want to deploy to production.

In the past we scattered some test commands around our deploy script, however when our build stage required one of the environment variables as well we decided for a more concise way.

# .gitlab-ci.yml
before_script:
- source .${CI_COMMIT_REF_NAME}.env
# ...

We simply source environment variables from the .develop.env and .master.env files.

# .master.env
export DOMAIN='tiftapp.com'
export FTP_DIR='staging'
export FTP_HOST='tiftapp.com'

Discussion

  • a single source of truth makes it easy for developers to add new and find existing configuration
  • Gitlab offers a similar feature, but only for its enterprise customers, see this link
  • secrets should not be commited in these files, however you can reassign environment variables which you set directly in Gitlab (which can be protected)
# .master.env
export FTP_PASS="$PROD_FTP_PASS"
export FTP_USER="$PROD_FTP_USER"

--

--