Hammed
Hammed

Reputation: 1557

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.

Upvotes: 2

Views: 5221

Answers (1)

Noam Helmer
Noam Helmer

Reputation: 6849

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

Upvotes: 2

Related Questions