Home > Back-end >  How to use conditional post action in Jenkins pipeline?
How to use conditional post action in Jenkins pipeline?

Time:12-08

I am using Jenkins declarative pipeline and want to perform some post build actions depending on the build status.

To be more precise, I want these conditions to be true:

beforeAgent true && jobName == 'Cypress Test'

Here's my code:

post {
        always {
            script {
                passwordIDs.each{ pw ->
                    credentialFetch.deleteTemporaryCredential(env.BUILD, pw, expireTime)
                  }
              }
        }
    }

Any idea where can I use my conditions? Also, how to use them since Post doesn't support when condition

CodePudding user response:

You can use normal if condition within the script block in the post conditions as you would do with a normal stage. For example, I have used this in one of my jobs:

post {
    failure {
        script {
            def response = httpRequest '${env.BUILD_URL}/consoleText'
            if (response.content.contains("Automatic merge failed; fix conflicts")){
                env.BUILD_FAILURE_MESSAGE = "Checkout Failing! Make sure that there are no merge conflicts...
            } else {
                env.BUILD_FAILURE_MESSAGE = "Checkout Failing! Check the build log and re-run the build if the issue seems unrelated to your commit...
            }
        }
    }
}

As you can see, it is a normal if condition that checks if the string contains text. You should be able to use your conditions in a similar manner:

if (beforeAgent && jobName == 'Cypress Test')
  • Related