CircleCI - different value to environment variable according to the branch

The question is almost 2 years now but recently I was looking for similar solution and I found it.

It refers to CircleCI's feature called Contexts (https://circleci.com/docs/2.0/contexts/). Thanks to Contexts you can create multiple sets of environment variables which are available within entire organisation. Then you can dynamically load one of the sets depending of workflows' filters property.

Let me demonstrate it with following example:

Imagine you have two branches and you want each of them to be deployed into different server. What you have to do is:

  1. create two contexts (e.g. prod-ctx and dev-ctx) and define SERVER_URLenvironment variable in each of them. You need to log into CircleCI dashboard and go to "Settings" -> "Contexts".

  2. in your .circleci/config.yml define job's template and call it deploy:

deploy: &deploy
steps:
  - ...
  1. define workflows:
workflows:
  version: 2
  deploy:
    jobs:
      - deploy-dev:
          context: dev-ctx
          filters:
            branches:
              only:
                - develop
      - deploy-prod:
          context: prod-ctx
          filters:
            branches:
              only:
                - master
  1. finally define two jobs deploy-prod and deploy-dev which would use deploy template:
jobs:
  deploy-dev:
    <<: *deploy

  deploy-prod:
    <<: *deploy

Above steps create two jobs and run them depending on filters condition. Additionally, each job gets different set of environment variables but the logic of deployment stays the same and is defined once. Thanks to this, we achieved dynamic environment variables values for different branches.


Use a bash script

In my projects, I archive that by using a bash script.

For example, this is my circle.yml :

machine:
  node:
    version: 6.9.5

dependencies:
  override:
    - yarn install

compile:
  override:
    - chmod -x compile.sh
    - bash ./compile.sh

And this is my compile.sh

#!/bin/bash

if [ "${CIRCLE_BRANCH}" == "development" ]
then
  export NODE_ENV=development
  export MONGODB_URI=${DEVELOPMENT_DB}
  npm run build
elif [ "${CIRCLE_BRANCH}" == "staging" ]
then
  export NODE_ENV=staging
  export MONGODB_URI=${STAGING_DB}
  npm run build
elif [ "${CIRCLE_BRANCH}" == "master" ]
then
  export NODE_ENV=production
  export MONGODB_URI=${PRODUCTION_DB}
  npm run build
else
  export NODE_ENV=development
  export MONGODB_URI=${DEVELOPMENT_DB}
  npm run build
fi

echo "Sucessfull build for environment: ${NODE_ENV}"

exit 0