Creating a Pipeline job with a dynamic options block

1 minute readKnowledge base

Issue

I have a use case where I’d like to have the options {} block of my Pipeline code generated dynamically, but this is currently not possible to do.

Resolution

Currently the options {} block is not dynamic, but this article does have a workaround that has been confirmed to be successful to allow for dynamic options.

Workaround

This workaround example will have one Jenkinsfile which will use an agent to load the developer’s Jenkinsfile, then call a groovy method to replace the options{} block dynamically, then evaluate the resulting Pipeline code.

By using this, you would be able to dynamically generate sections of Pipeline code that is currently not possible to use conditional logic to control, specifically in this example the options {} block.

This Jenkinsfile could be located inside the same repo as the developer’s Jenkinsfile, or could be put into a centralized repo (with modifications to the checkout scm line) if you prefer to use this across all developer repos.

def getOptions(){ //TODO put conditional logic here return "options {disableConcurrentBuilds()}" } node { checkout scm file=readFile 'Jenkinsfile' } file=file.replaceAll("OPTIONS_STRING", getOptions()) evaluate(file)

Here is a basic hello world Jenkinsfile that can be used with this:

pipeline { agent any OPTIONS_STRING stages { stage('Hello') { steps { echo 'Hello World' } } } }

Tested product/plugin versions