How can I parameterize Jenkinsfile jobs How can I parameterize Jenkinsfile jobs jenkins jenkins

How can I parameterize Jenkinsfile jobs


Basically you need to create a jenkins shared library example name myCoolLib and have a full declarative pipeline in one file under vars, let say you call the file myFancyPipeline.groovy.

Wanted to write my examples but actually I see the docs are quite nice, so I'll copy from there. First the myFancyPipeline.groovy

def call(int buildNumber) {  if (buildNumber % 2 == 0) {    pipeline {      agent any      stages {        stage('Even Stage') {          steps {            echo "The build number is even"          }        }      }    }  } else {    pipeline {      agent any      stages {        stage('Odd Stage') {          steps {            echo "The build number is odd"          }        }      }    }  }}

and then aJenkinsfile that uses it (now has 2 lines)

@Library('myCoolLib') _evenOrOdd(currentBuild.getNumber())

Obviously parameter here is of type int, but it can be any number of parameters of any type.

I use this approach and have one of the groovy scripts that has 3 parameters (2 Strings and an int) and have 15-20 Jenkinsfiles that use that script via shared library and it's perfect. Motivation is of course one of the most basic rules in any programming (not a quote but goes something like): If you have "same code" at 2 different places, something is not right.


Add this to your Jenkinsfile:

properties([  parameters([    string(name: 'myParam', defaultValue: '')  ])])

Then, once the build has run once, you will see the "build with parameters" button on the job UI.

There you can input the parameter value you want.

In the pipeline script you can reference it with params.myParam


There is an option This project is parameterized in your pipeline job configuration. Write variable name and a default value if you wish. In pipeline access this variable with env.variable_name