I would like to set a boolean variable to true if one of my environment variables equals a string. I only want to run my test stage if this RUN_TESTS
var is true.
pipeline{
environment {
RUN_TESTS = expression { "${env.JOB_BASE_NAME}" == 'Test Pipeline' }
}
stages{
stage('test'){
when {
expression { RUN_TESTS }
}
steps{
// run my tests.......
}
}
}
The above is not working though.
How can I set a boolean variable based on the value of an environment variable that I can then use to conditionally run a pipeline stage?
CodePudding user response:
It looks like you do not have to set environment variable in this case. You can evaluate expression directly in your stage:
pipeline{
stages{
stage('test'){
when {
expression { "${env.JOB_BASE_NAME}" == 'Test Pipeline' }
}
steps{
// run my tests.......
}
}
}
On the other hand if you still have to set the environment variable there are few ways to do it. Jenkins says:
Environment variable values must either be single quoted, double quoted, or function calls.
- Wrap it in double quoted expression:
environment {
RUN_TESTS = "${env.JOB_BASE_NAME == 'Test Pipeline'}"
}
- Wrap this expression in the function call, something like this:
def run_tests() {
return "${env.JOB_BASE_NAME}" == 'Test Pipeline'
}
pipeline{
environment {
RUN_TESTS = run_tests()
}
stages{
stage('test'){
when {
expression { RUN_TESTS }
}
steps{
// run my tests.......
}
}
}
But in general I would go for first approach