I'm trying to set different values for environment variables on CircleCI according to the current $CIRCLE_BRANCH. I tried setting two different values on CircleCI settings and exporting them accordingly on the deployment phase, but that doesn't work:
deployment:
release:
branch: master
commands:
...
- export API_URL=$RELEASE_API_URL; npm run build
...
staging:
branch: develop
commands:
...
- export API_URL=$STAGING_API_URL; npm run build
...
How could I achieve that?
Thanks in advance.
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-ctx
and dev-ctx
) and define SERVER_URL
environment variable in each of them. You need to log into CircleCI dashboard and go to "Settings" -> "Contexts".
in your .circleci/config.yml
define job's template and call it deploy
:
deploy: &deploy
steps:
- ...
workflows:
version: 2
deploy:
jobs:
- deploy-dev:
context: dev-ctx
filters:
branches:
only:
- develop
- deploy-prod:
context: prod-ctx
filters:
branches:
only:
- master
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With