xenoterracide
xenoterracide

Reputation: 16865

How can I parameterize Jenkinsfile jobs

I have Jenkins Pipeline jobs, where the only difference between the jobs is a parameter, a single "name" value, I could even use the multibranch job name (though not what it's passing as JOB_NAME which is the BRANCH name, sadly none of the envs look suitable without parsing). It would be great if I could set this outiside of the Jenkinsfile, since then I could reuse the same jenkinsfile for all the various jobs.

Upvotes: 12

Views: 19225

Answers (3)

bp2010
bp2010

Reputation: 2472

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

Upvotes: 8

cantSleepNow
cantSleepNow

Reputation: 10202

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.

Upvotes: 6

minas
minas

Reputation: 230

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

Upvotes: 0

Related Questions