How to build pipeline job inside the POST section in Jenkins pipeline

Viewed 161

I have a Jenkins pipeline which, among multiple steps should have a final step that should be executed regardless of the status of previous steps. For that to happen, I've tried using post section which looks like this:

pipeline {
    agent {
        label 'master'
    }

    stages {
        stage('Stage 1') {
            steps {
                build job: 'stage 1 job', parameters: [
                    ...
                ]
            }
        }

        stage('Stage 2') {
            steps {
                build job: 'stage 2 job', parameters: [
                    ...
                ]
            }
        }
    }

    post {
        always {
            build job: "cleanup", parameters: [
                ...
            ]
        }
    }
}

However, I'm getting following error when trying to execute something like this:

No such DSL method '$' found among steps

Question: Is it even possible to use build job inside post action? If not, what would be good alternative to achieve that "cleanup" job is always executed at the end (regardless of the status of stages above)

1 Answers

Yes, it is possible to use build a job inside post action. Here is the pipeline script:

pipeline {
    agent any
    stages {
        stage('1') {
            steps {
                
                script {
                         
                echo "Hello"
            }
            
            }
        }
        
    }
    
    post {
        always {
                   build job: 'schedule-job', parameters: [string(name: 'PLATFORM', value: 'Windows')]
  }
}
}

In the above example, I have schedule-job which accepts parameters PLATFORM and it will Always run, regardless of build status

Here is the output:

enter image description here

Related