Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know inside jenkinsfile / script that current build is a replay?

As in subject - is there any way to verify if current build is effect of using 'Replay' button?

like image 424
hi_my_name_is Avatar asked Jul 27 '18 10:07

hi_my_name_is


People also ask

What is replay in Jenkins build?

The Jenkins Replay Button It is somewhat similar to the Rebuild button but allows you to edit the Jenkinsfile just before running the job.

How do you abort a build in Jenkinsfile?

You can mark the build as ABORTED, and then use the error step to cause the build to stop: if (! continueBuild) { currentBuild. result = 'ABORTED' error('Stopping early…') }

What does sh mean in Jenkinsfile?

On Linux, BSD, and Mac OS (Unix-like) systems, the sh step is used to execute a shell command in a Pipeline. Jenkinsfile (Declarative Pipeline) pipeline { agent any stages { stage('Build') { steps { sh 'echo "Hello World"' sh ''' echo "Multiline shell steps works too" ls -lah ''' } } } }


Video Answer


1 Answers

I found the following solution using the rawBuild instance from currentBuild. Since we can't get the class of the causes, we just verify its string value.

def replayClassName = "org.jenkinsci.plugins.workflow.cps.replay.ReplayCause​"
def isReplay = currentBuild.rawBuild.getCauses().any{ cause -> cause.toString().contains(replayClassName) }

This solution works for Jenkins with Blue-Ocean. References to how to get to this answer is Jenkins declarative pipeline: find out triggering job

Update

Using this a step condition works like a charm!

You can define a shared library like jenkins.groovy

def isBuildAReplay() {
  // https://stackoverflow.com/questions/51555910/how-to-know-inside-jenkinsfile-script-that-current-build-is-an-replay/52302879#52302879
  def replyClassName = "org.jenkinsci.plugins.workflow.cps.replay.ReplayCause"
  currentBuild.rawBuild.getCauses().any{ cause -> cause.toString().contains(replyClassName) }
}

You can reuse it in a Jenkins pipeline

stage('Conditional Stage') {
  when {
    expression { jenkins.isBuildAReplay() }
  }
  steps {
    ...
    ...
  }
}
like image 59
Marcello de Sales Avatar answered Sep 20 '22 14:09

Marcello de Sales