How to share stages between Jenkins Pipelines

719 views Asked by At

I have two JenkinsFile files where I want to share the same stages:

CommonJenkinsFile:

  pipeline {
  agent {
    node {
      label 'devel-slave'
    }
  }
  stages {
    stage("Select branch") {
              options {
                  timeout(time: 3, unit: 'MINUTES') 
              }
            steps {
                script {
                    env.branchName = input(
                            id: 'userInput', message: 'Enter the name of the branch you want to deploy',
                            parameters: [
                                    string(
                                        defaultValue: '', 
                                        name: 'BranchName',
                                        description: 'Name of the branch'),
                            ]).replaceAll('\\/', '%2F')
                }
            }
        }
}

Where I want to use it:

pipeline {
  agent {
    node {
        label 'devel-slave'
    }
  }
  load 'CommonJenkinsFile'
  stages {
        stage('Deploy to test') {
}
}

How can this stages be shared? Should I change to the Scripted Pipelines? Can they share stages or only steps?

1

There are 1 answers

0
smelm On

CommonJenkinsfile cannot contain the pipeline directive (otherwise you are executing a pipeline within a pipeline). I think you also need to move it to the scripted syntax instead of the declarative (might be wrong there)

This file could look like this:

def commonStep(){
    node('devel-slave'){
        stage("Select branch") {
            timeout(time: 3, unit: 'MINUTES'){
                env.branchName = input ...
            }
        }
    }
}

return this

You can then load it like this

stage('common step'){
    script{
        def sharedSteps = load "$workspace/common.groovy"
        sharedSteps.commonStep()
    }
}