1
votes

I have a declarative Jenkins pipeline. I want to have a conditional in the "post" section of a build.

Is it possible to have "script blocks" in the post section of a jenkins file?

When I put it like this, no errors occur, but no hipchat messages are sent. Even if say "if master branch, hipchatSend, else hipchatSend", no hipchat messages are sent. Heck, if I replace hipchatSend with "echo" statements, nothing happens either.

post {
  always {
    script {
      if (env.BRANCH_NAME == "master") {
        hipchatSend color: 'RED', credentialId: 'HipChat-Jenkins-Token',
                    message: 'I am master branch',
                    room: 'Master-Commit-Room,',
                    sendAs: '', 
                    server: '',
                    v2enabled: true
      }
      if (env.BRANCH_NAME == "release/my-release") {
        hipchatSend color: 'RED', credentialId: 'HipChat-Jenkins-Token',
                    message: 'I am release branch',
                    room: 'Release-Commit-Room,',
                    sendAs: '',
                    server: '',
                    v2enabled: true
      }
    }
  }
}
2

2 Answers

4
votes

I have set up Jenkins declarative pipelines which successfully uses script blocks in the post section the way you describe.

Example:

post {
    always {
        script {
            // arbitrary script code runs successfully here
        }
    }
}

... and it works as expected. Have you verified that your if conditions evaluate as expected?

Note: I'm using the "Pipeline: Declarative" plugin (id pipeline-model-definition) version 1.3.2 on Jenkins 2.138.2).

-1
votes

Use when

stage('Deploy') {
        when { branch 'master' }
        steps {
            sh './docker-commands.sh deploy || exit 1'
        }
    }

Here is more examples how to use when