2

I have a Jenkinsfile like this

    pipeline {
        agent { label 'master' }
        stages {
            stage('1') {
                steps {
                    script {
                        sh '''#!/bin/bash
                        source $EXPORT_PATH_SCRIPT
                        cd $SCRIPT_PATH
                        python -m scripts.test.test
                        '''
                    }
                }
            }
            stage('2') {
                steps {
                    script {
                        sh '''#!/bin/bash
                        source $EXPORT_PATH_SCRIPT
                        cd $SCRIPT_PATH
                        python -m scripts.test.test
                        '''
                    }
                }
            }
        }
    }

As you can see, In both stages I am using the same script and calling the same file. Can I move this step to a function in Jenkinsfile and call that function in script? like this

    def execute script() {
         return {
           sh '''#!/bin/bash
           source $EXPORT_PATH_SCRIPT
           cd $SCRIPT_PATH
           python -m scripts.test.test
           '''  
    }
    }
JoSSte
  • 2,953
  • 6
  • 34
  • 54
sam
  • 203
  • 1
  • 3
  • 15
  • 3
    Does this answer your question? [How to create methods in Jenkins Declarative pipeline?](https://stackoverflow.com/questions/47628248/how-to-create-methods-in-jenkins-declarative-pipeline) – Sers Dec 06 '20 at 15:54

1 Answers1

5

Yes, It's possible like below example:

Jenkinsfile

def doIt(name) {
    return "The name is : ${name}"
}

def executeScript() {
    sh "echo HelloWorld"
}

pipeline {
    agent any;
    stages {
        stage('01') {
            steps {
                println doIt("stage 01")
                executeScript()
            }
        }
        stage('02') {
            steps {
                println doIt("stage 02")
                executeScript()
            }
        }
    }
}
JoSSte
  • 2,953
  • 6
  • 34
  • 54
Samit Kumar Patel
  • 1,932
  • 1
  • 13
  • 20