CircleCI - Different Value To Environment Variable According To The Branch
Answer :
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:
create two contexts (e.g.
prod-ctxanddev-ctx) and defineSERVER_URLenvironment variable in each of them. You need to log into CircleCI dashboard and go to "Settings" -> "Contexts".in your
.circleci/config.ymldefine job's template and call itdeploy:
deploy: &deploy steps: - ... - 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 - finally define two jobs
deploy-prodanddeploy-devwhich would usedeploytemplate:
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
Comments
Post a Comment