Search code examples
gitjenkinsjenkins-groovy

Find git commit hash for a previous run in Jenkins pipeline


I have a job in Jenkins which is designed to build multiple Docker container images along with charts. I want this job to check git tree for differences to know if new version of an image should be built.

Initially I have Jenkins build number, then I run this function with currentBuild to recursively search through previous builds.

def findBuildByNumber (build, buildNo) {
    if (build == null) {
        error "FATAL: Called with null searching for $buildNo"
    }
    if (build.number == buildNo) {
        return build
    }
    return findBuildByNumber (build.getPreviousBuild(), buildNo)
}
buildFound = findBuildByNumber(currentBuild, buildNo)

This code returns build object of previous build and now I want to know what GIT_COMMIT variable was set in it.

Both buildFound.buildVariables.GIT_COMMIT and buildFound.getBuildVariables()?.GIT_COMMIT are giving null. Calling dump() on this object gives poor output:

org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper@5d8bc8d0 
externalizableId=devops/arc/main#125
currentBuild=false

How can I access build variables of the certain build, known by number, what was run in the same job?


Solution

  • You can access parameters of completed builds (build.getAction(ParametersAction.class).getParameter('PARAM_NAME')), but not their environment variables. You can reference build.xml to see what is actually persisted to disk.

    In your case you can access the scm build.getActions(hudson.plugins.git.util.BuildData.class)[0].getLastBuiltRevision().getSha1String(). If you have more than one checkout you might need to select which BuildData to use instead of just [0].

    Update:

    I was wrong, you can access some environment variables of other builds, but only the ones you set yourself. If they are set by plugins, like GIT_COMMIT, they are not persisted. build.buildVariables is a Map, so you can look at its .keySet() method to see which environment variables are available.