Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a stage if environment variable contains specific substring

I have a jenkins declarative pipeline which I am interested to be able to perform a stage only if a specific environment variable contains a specific substring(not fully equals to it, just contains it). Does anyone got any idea on how can I implement it(maybe using the when condition if possible).

Thanks in advance, Alon

like image 963
Alon Tsaraf Avatar asked Apr 07 '26 20:04

Alon Tsaraf


1 Answers

As you mentioned, in declarative pipeline you can use the when directive to establish a condition in which the stage will be executed.
Among the built in condition options like triggeredBy,branch and tag there is the generic expression option, which allows you to run any groovy code and calculate the relevant Boolean value according to your needs.
So for your case for example you can just use the groovy contains methods to achieve what you want, something like:

pipeline {
    agent any
    stages {
        stage('Conditional Stage') {
            when {
                expression { return env.MyParamter.contains('MySubstring') }
            }
            steps {
                echo "Running the conditional stage"
            }
        }
    }
}
like image 93
Noam Helmer Avatar answered Apr 09 '26 15:04

Noam Helmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!