Sean Pianka
Sean Pianka

Reputation: 2325

Trigger an action within Jenkins declarative pipeline right after a stage ends or just before a stage begins?

I have the following Jenkinsfile:

pipeline {
    agent any
    environment { }
    stages {
        stage('stageA') {
            steps {
                ... Do something with arg1, arg2 or arg3
            }
        }
        stage('stageB') {
            steps {
                ... Do something with arg1, arg2 or arg3
            }
        }
        ...
    }
}

Is there anywhere I can specify a universal "pre-stage" or "post-stage" set of actions to perform? A use-case would be sending logging information at the end of a stage to a log manager, but it would be preferable to not copy and paste those invocations at the end of each and every stage.

Upvotes: 1

Views: 1973

Answers (1)

Michael
Michael

Reputation: 2683

As far as I know there is no generic post- or pre-stage hook in Jenkins pipelines. You can define post steps in a post section but you need one per stage.

However, if you don't want to repeat yourself, you have some options.

Use a shared lib

The place to put repeating code to it a shared library. That way allows you to declare your own steps using Groovy.

You need another repository to define a shared lib, but apart from that it is a pretty strait forward way and you can reuse the code in all of your Jenkins' pipelines.

Use a function

If you declare a function outside of the pipeline, you can call it from any stage. This is not really documented and might be prevented in the future. As far as I understand it messes with the coordination between master and agents. However, it works:

pipeline {

    agent any

    stages {
        stage ("First") {
            steps {
                writeFile file: "resultFirst.txt", text: "all good"
            }
            post {
                always {
                    cleanup "first"
                }
            }
        }
        stage ("Second") {
            steps {
                writeFile file: "resultSecond.txt", text: "all good as well"
            }
            post {
                always {
                    cleanup "second"
                }
            }
        }

        post {
            always {
                cleanup "global" // this is only triggered after all stages, not after every
            }
        }
    }
}

void cleanup(String stage) {
    echo "cleanup ${stage}"
    archiveArtifacts artifacts: "result*"
}

Upvotes: 1

Related Questions