Issue
I've an issue while using SWITCH on a Jenkinsfile. When the PR is done the pipeline is started using println I see the CHANGE_TARGET is correct to match the CASE condition, however it apply master and all variables are set using the MASTER case values.
the first println return:
The build ENV is test | PR Title: XXX
code example:
pipeline {
agent any
stages {
stage('Setup Variables') {
steps {
script {
switch(env.CHANGE_TARGET) {
case 'test':
API_Cluster = 'cluster-api'
API_Service = 'api'
API_DockerFile = 'api-test'
ECR_ImageTag = 'XXX'
case 'qa':
API_Cluster = 'cluster-api'
API_Service = 'api'
API_DockerFile = 'api-qa'
ECR_ImageTag = 'XXX'
case 'master':
API_Cluster = 'cluster-api'
API_Service = 'api'
API_DockerFile = 'api-prod'
ECR_ImageTag = 'XXX'
default:
println "Branch name was not set!"
break;
}
}
}
}
stage('Build Details') {
steps {
println("The build ENV is " + CHANGE_TARGET + " | " + "PR Title: " + CHANGE_TITLE)
println("Services:" + API_Service + " | " + WEB_Service)
}
}
stage('Build API') {
steps {
sh """docker build --rm --tag api:${ECR_ImageTag} -f ${API_DockerFile} ."""
}
}
}
}
Solution
You are missing break
at the end of every case. When there is no break
, Groovy continues and runs the code from the remaining cases.
switch(env.CHANGE_TARGET) {
case 'test':
API_Cluster = 'cluster-api'
API_Service = 'api'
API_DockerFile = 'api-test'
ECR_ImageTag = 'XXX'
break
case 'qa':
API_Cluster = 'cluster-api'
API_Service = 'api'
API_DockerFile = 'api-qa'
ECR_ImageTag = 'XXX'
break
case 'master':
API_Cluster = 'cluster-api'
API_Service = 'api'
API_DockerFile = 'api-prod'
ECR_ImageTag = 'XXX'
break
default:
println "Branch name was not set!"
break;
}
Answered By - Szymon Stepniak