我有多个 GIT 存储库,为了简单起见,将其保留为 2,并且我创建了一个 Jenkins 管道来轮询这些存储库以检查新提交并触发一个单独的 Jenkins 作业来对该存储库运行扫描。
我的 Groovy 脚本遇到的问题是,它能够轮询任一存储库上的新提交并触发管道,但最终会触发两个存储库的扫描作业。
这是我的 Jenkins 管道的 Groovy 脚本
properties([
pipelineTriggers([
[$class: "SCMTrigger", scmpoll_spec: "H/5 * * * *"],
])
])
node {
stage ('Trigger') {
dir('ABC') {
if (git(
poll: true,
url: 'ssh://[email protected]/XXX/ABC.git',
credentialsId: 'abc123',
branch: 'master'
)){
build job: 'Scan', parameters: [
string(name: 'Project_Name', value: "ABC"),
string(name: 'Git_project', value: "ABC.git")
]
}
}
dir('XYZ') {
if (git(
poll: true,
url: 'ssh://[email protected]/XXX/XYZ.git',
credentialsId: 'abc123',
branch: 'master'
)){
build job: 'Scan', parameters: [
string(name: 'Project_Name', value: "XYZ"),
string(name: 'Git_project', value: "XYZ.git")
]
}
}
}
}
我添加了 IF 条件,但它仍然会触发两个存储库的作业,但我只需要它为已提交的存储库运行。
您的所有作业都会运行,因为
git
步骤正在返回始终评估为 true 的对象。
实际上,文档说没有 poll 参数意味着 poll:true,所以你不需要它(https://www.jenkins.io/doc/pipeline/steps/git/#git-git)。
如果你尝试这个:
def obj = git("https://some-git-repo")
echo obj.toString()
你会看到它的内容,看起来像是一张地图:
[GIT_BRANCH:origin/master, GIT_COMMIT:1095fa8efbb96f2f63322be7b5a2e9d4d8988b5c, GIT_LOCAL_BRANCH:master, GIT_URL:https://some-git-repo]
但是,如果重新运行它,您将看到可能有用的其他信息:
[GIT_BRANCH:origin/master, GIT_COMMIT:1095fa8efbb96f2f63322be7b5a2e9d4d8988b5c, GIT_LOCAL_BRANCH:master, GIT_PREVIOUS_COMMIT:1095fa8efbb96f2f63322be7b5a2e9d4d8988b5c, GIT_PREVIOUS_SUCCESSFUL_COMMIT:1095fa8efbb96f2f63322be7b5a2e9d4d8988b5c, GIT_URL:https://some-git-repo]
现在,让我们提交这个存储库,结果是:
[GIT_BRANCH:origin/master, GIT_COMMIT:1aac1ae15b7e872f273a44d4bf4ef5dc23cc19fb, GIT_LOCAL_BRANCH:master, GIT_PREVIOUS_COMMIT:1095fa8efbb96f2f63322be7b5a2e9d4d8988b5c, GIT_PREVIOUS_SUCCESSFUL_COMMIT:1095fa8efbb96f2f63322be7b5a2e9d4d8988b5c, GIT_URL:https://some-git-repo]
啊哈!我们可以利用这个信息。 综合起来:
def repoMap = git("https://some-git-repo")
if(repoMap.GIT_COMMIT != repoMap.GIT_PREVIOUS_COMMIT){
run-the-job
}