I am trying to create a Jenkinsfile to handle different steps in prod vs dev environments. I was attempting to use the anyOf pattern with an expression that checks the JOB_URL environmental variable to determine which build server/build instruction to follow.
Jenkinsfile ends up looking something like the below:
stage('In Prod') {
when {
allOf {
expression { params.P1 == 'x' }
expression { params.P2 == 'y' }
expression { env.JOB_URL.contains('prod_server.com') }
}
}
...
}
stage('In Dev') {
when {
allOf {
expression { params.P1 == 'x' }
expression { params.P2 == 'y' }
expression { env.JOB_URL.contains('dev_server.com') }
}
}
...
}
Expected Behavior:
In Dev stepIn Prod stepActual Behavior:
In Prod AND In Dev stepIn Prod stepYes, I have checked to make sure that JOB_URL on the dev does not contain prod_server.com.
I have also tried !env.JOB_URL.contains('dev_server.com') as an additional expression for the prod step with the same result.
I only know enough groovy to get through Jenkins, and am somewhat new to Jenkins pipeline syntax, so maybe I've misunderstood the behavior here, but from what I understand from the Jenkins expression documentation:
when returning strings from your expressions they must be converted to booleans or return null to evaluate to false. Simply returning "0" or "false" will still evaluate to "true".
And as a sanity check, I confirmed that the groovy documentation says contains should be returning a boolean.
You can use a regular expression comparator in the expression to check the one of these environment variables:
JENKINS_URL and BUILD_URL (source built-in var)JOB_URL (exists but can't find source)Note: environment variable are exposed through the reserved environment variable map env (using env variable), e.g. server_url = env.JENKINS_URL.
Try something like this:
pipeline {
agent none
parameters {
string(name: 'P1', defaultValue: 'x', description: '')
string(name: 'P2', defaultValue: 'y', description: '')
}
stages {
stage('Init') {
steps {
echo "params = ${params.toString()}"
echo "env.JENKINS_URL = ${env.JENKINS_URL}"
}
}
stage('In Prod') {
when {
allOf {
expression { params.P1 == 'x' }
expression { params.P2 == 'y' }
expression { env.JENKINS_URL ==~ /.*prod_server.com.*/ }
}
}
steps {
echo "Prod"
}
}
stage('In Dev') {
when {
allOf {
expression { params.P1 == 'x' }
expression { params.P2 == 'y' }
expression { env.JENKINS_URL ==~ /.*dev_server.com.*/ }
}
}
steps {
echo "DEV"
}
}
}
}
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