Conditional expressions in blocks other than `stages` with declarative Jenkins pipelines

33 Views Asked by At

We have a lot of declarative Jenkins pipeline code that is used for a certain Jenkins instance in our main environment, and now we want to have a second Jenkins instance for an isolated environment that should use the same pipelines, but behave a bit different with a few tweaks here and there.

The way we're going to distinguish between the two instances is by defining a global environment variable in the Jenkins master, and with that we can have conditional stages, and conditional steps with when and script blocks under the stage block. (e.g. if (env.ENVIRONMENT == "ISOLATED") { <do something else> })

How can we achieve something similar with the parameters {} and options {} blocks? I know we can use "variables" with shared libraries to provide, say, different options to a choice parameter, but we want to be able to have 1 less / 1 more parameters in some cases that are irrelevant / relevant only in a certain environment.

1

There are 1 best solutions below

0
ycr On

If you can convert your Pipeline to a scripted Pipeline you should be able to do this pretty easily.

if (env.ENVIRONMENT.contains("ISOLATED")) {
    properties([
        parameters([
            string(name: 'Cloud', defaultValue: 'AWS', description: 'Cloud Type')
        ]),
        // This is a option
        buildDiscarder(
            logRotator(
                daysToKeepStr: '7',
                numToKeepStr: '25'
            )
        )
    ])
} else {
    println "If not set something different"
}


pipeline {
    agent any
    stages {
        stage("Hello") {
            steps {
                echo "Building Something"
            }
        }
    }
}

Take a look at this on how to generate option snippets.