简体   繁体   中英

How to get jenkins multibranch pipeline last build revision?

I have jenkins pipeline and also using a shared library for jenkins. In my multibranch pipeline three to four repo clone while executing build using bitbucket plugin.

my question is how to get the last build revision from the previous build.

I have tried currentBuild.changeSets approach but for multiple repositories clone, it fails.

I had to get SCM revisions from the previous builds too. I didn't find any API to get it nicely, so I implemented a workaround. It is not great, but at least it works ;-)

When you save an environment variable by using env.setProperty(name, value) it is saved in the build metadata as a build variable. You can read it at any moment.

pipeline {
  agent any
  stages {
    stage('Test') {
      script {
        env.setProperty('MY_ENV', env.BUILD_NUMBER)
        def previousBuild = currentBuild.previousBuild
        if (previousBuild != null) {
          echo previousBuild.buildVariables['MY_ENV'] // prints env.BUILD_NUMBER - 1
        }
      }
    }
  }
}

In your case you have 4 checkouts. I don't know how you close sources, so let's imagine that you have a method cloneRepo and it sets GIT_COMMIT environment variable. They you may use:

def previousBuild = currentBuild.previousBuild
if (previousBuild != null) {
  echo previousBuild.buildVariables['GIT_COMMIT_REPO_1']
  echo previousBuild.buildVariables['GIT_COMMIT_REPO_2']
  echo previousBuild.buildVariables['GIT_COMMIT_REPO_3']
  echo previousBuild.buildVariables['GIT_COMMIT_REPO_4']
}

cloneRepo(repo1)
env.setProperty('GIT_COMMIT_REPO_1', env.GIT_COMMIT)
cloneRepo(repo2)
env.setProperty('GIT_COMMIT_REPO_2', env.GIT_COMMIT)
cloneRepo(repo3)
env.setProperty('GIT_COMMIT_REPO_3', env.GIT_COMMIT)
cloneRepo(repo4)
env.setProperty('GIT_COMMIT_REPO_4', env.GIT_COMMIT)

If you use the checkout step, then you may do:

def commitId = checkout(scm).find { it.key == 'GIT_COMMIT' }
env.setProperty('GIT_COMMIT_REPO_1', commitId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM