How to move steps inside stage to a function in Jenkins pipeline

Viewed 857

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
       '''  
}
}
1 Answers

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()
            }
        }
    }
}
Related