jenkinsjenkins-pipelinejenkins-groovyjenkins-job-dslpost-build

How To Run A Script As Jenkins Pipeline Post-Build Stage


Is it possible to execute a shell script as a post-build step of a pipeline job using job DSL?

    post {
        success {
            sh """
            echo "Pipeline Works"
            """
            }
        failure {
            shell('''
            |echo "This job failed"
            |echo "And I am not sure why"
            '''.stripMargin().stripIndent()
            )
        }
    }

I'm able to execute a oneliner, but ideally I would like to execute a script.

I've tried something like this

    publishers {
        postBuildScripts {
            steps {
                shell('echo Hello World')
            }
            onlyIfBuildSucceeds(false)
            onlyIfBuildFails()
        }
    }
}

But it looks like publishers has been deprecated.


Solution

  • Your original attempt is fine, the problem is calling .stripMargin().stripIndent() on a string in a declarative pipeline is not possible. To run such groovy code you need to wrap it with a script block.
    Try the following:

    post {
        success {
            sh 'echo "Pipeline Works"'
        }
        failure {
            script {
                sh '''
                |echo "This job failed"
                |echo "And I am not sure why"
                '''.stripMargin().stripIndent()
            }
        }
    }