Postbuild action in Jenkins pipeline

It’s a sample of how to do post-build using pipeline inside Jenkins.It’s a sample of how to do post build using pipeline inside Jenkins

Explanation when we use post-build
First, let’s do some pipeline
pipeline {
  agent any
  stages {
    stage(‘Error’) {
      steps {
        error “failure test. It’s work”
      }
    }
    stage(‘ItNotWork’) {
      steps {
        echo “is not pass here”
        echo “You can’t do post build in other stage”
      }
    }
  }
}
This pipeline has two stages, ‘Error’ and ‘ItNotWork’.The first stage will get errors and the second stage will not run.
If you need a code to run after build, you can put it in post-build.
pipeline {
  agent any
  stages {
    stage(‘Error’) {
      steps {
        error “failure test. It’s work”
      }
    }
    stage(‘ItNotWork’) {
      steps {
        echo “is not pass here”
      }
   }
  }
  post {
    success {
      mail to: [email protected], subject: ‘The Pipeline success :(‘
    }
  }
}

In Post Build you have a lot of steps, let’s talk about the two most useful steps.
If we want to run every time after our work is finished, we can use the step “always”
pipeline {
  agent any
  stages {
    …
  }
  post {
    always {
      echo ‘I will always execute this!’
    }
  }
}
If you want to execute some code only if the build fails, you can use the step “failure”
pipeline {
  agent any
  stages {
    …
  }
  post {
    failure {
      mail to: [email protected], subject: ‘The Pipeline failed :(‘
    }
  }
}

create a job to test
pipeline {
  environment {
    //This variable need be tested as string
    doError = ‘1’
  }
  agent any
  stages {
    stage(‘Error’) {
      when {
        expression { doError == ‘1’ }
      }
      steps {
        echo “Failure”
        error “failure test. It’s work”
      }
    }
    stage(‘Success’) {
      when {
        expression { doError == ‘0’ }
      }
      steps {
        echo “ok”
      }
    }
  }
  post {
    always {
      echo ‘I will always execute this!’
    }
  }
}
we can test how to work post-build only changing the environment “doError”.

Recent Comments

No comments

Leave a Comment