I'm trying to set up an automated Jenkins pipeline for the Development
& Staging
branches within our Git repository. I have most of the pipeline working. But I do not know how to override globally set environment {}
variables depending on the git branch.
This is my Jenkinsfile:
pipeline {
agent any
environment {
dev_mongo_url = credentials('DEV_MONGO_URL')
stg_mongo_url = credentials('STG_MONGO_URL')
}
stages {
stage('Env Setup') {
steps {
script
{
if (env.BRANCH_NAME == 'bugfix/*' || env.BRANCH_NAME == 'feature/*' || env.BRANCH_NAME =='development' || env.BRANCH_NAME =='hotfix/*') {
env.environment = 'development'
echo 'Build & deployment to development environment'
}
if (env.BRANCH_NAME == 'staging'){
env.environment = 'staging'
echo 'Build & deployment to staging environment'
}
}
}
}
stage('Migration') {
when {
anyOf {
branch 'development';
branch 'feature/*';
branch 'staging'
}
}
steps {
echo "Installing the project NodeJS dependencies..."
sh 'npm ci'
echo "Executing the MongoDB migration script & displaying the status..."
dir('db-migrations') {
sh 'npm ci'
sh('npm run migrate --silent -- --mongodb-url=$mongo_url')
sh 'npm run migrate:status'
}
}
}
}
}
Within the above pipeline, I have the Env Setup
stage, which assigns the environment
type variable (development/staging) depending on the git branch. We have two MongoDB instances - one for development & one for the staging environment. I have defined both of the MongoDB server URL's under the environment {}
block. Now, I want to dynamically connect to the dev/staging mongo servers in the Migration
stage, depending on the environment type, and apply the migrations. I'm trying to automatically inject $mongo_url
value from the dev_mongo_url
& stg_mongo_url
global variables depending on the environment. I'm stuck, and I have no clue how to achieve it.
Any help?