simulate post step for dynamically generated Jenkins pipeline stages

The following simplified Jenkinsfile dynamically generates sequentially executed stages; however, I cannot create a post step for these dynamically stages, like so:

pipeline {
    agent none
    stages {
        stage('Gen Stages') {
            steps {
                script {
                    def stageNames = ["st1", "st2", "st3"]
                    stageNames.each { stageName ->
                        createStage(stageName)
                    }
                }
            }
        }
    }
    post {
        always {
            echo "post > always"
        }
        success {
            echo "post > success"
        }
    }
}

def createStage(String stageName) {
    stage(stageName) {
        echo "Stage: ${stageName}"
    }
    // I want to uncomment and use code below - or something effectively simiarl:
    // post {
    //     always {
    //         echo "${stageName} > post > always"
    //     }
    //     success {
    //         echo "${stageName} > success > always"
    //     }
    // }
}

I would like to be able to use the commented-out post {} stage, or something effectively similar.

If at all possible, I’d like to use the DSL as much as possible and avoid scripted pipelines.

Suggestions?

Go to Source
Author: Trevor