rocky
rocky

Reputation: 5004

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?

Upvotes: 13

Views: 4598

Answers (2)

Swapnil
Swapnil

Reputation: 1

Try the below Groovy script

import org.jenkinsci.plugins.workflow.job.WorkflowJob
import org.jenkinsci.plugins.workflow.cps.replay.ReplayCause

Jenkins.instance.getAllItems(WorkflowJob.class).each { job ->
    println("Job: ${job.name}")

    job.builds.each { build ->
        boolean isReplay = build.getCauses().any { cause -> cause instanceof ReplayCause }

        if (isReplay) {
            println("  Detected Replay: Job '${job.name}' with build number: ${build.number}")
        }
    }
}

Upvotes: 0

Marcello DeSales
Marcello DeSales

Reputation: 22358

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 {
    ...
    ...
  }
}

Upvotes: 13

Related Questions