jenkins pipeline 中自动获取 git 仓库所有分支

jenkins pipeline 中自动获取 git 仓库所有分支

在 Jenkins 中使用 pipeline 构建项目时自动获取 git 项目的所有分支与 tag 列表

插件安装

在 Pipeline 中如果需要获取 git 分支与 tag 首先我们需要在 Jenkins 中安装插件 Git Parameter

使用

新建 pipeline 工程,然后修改如下示例代码填写到 Pipeline script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
pipeline {
agent any
parameters {
string(name: 'repo_url',
defaultValue: 'git@git.akiya.cc:foo/bar.git',
description: 'git 仓库')
// Git Parameter
gitParameter(name: 'branch_name',
type: 'PT_BRANCH_TAG',
branchFilter: 'origin/(.*)',
defaultValue: 'master',
selectedValue: 'DEFAULT',
sortMode: 'DESCENDING_SMART',
useRepository: 'git@git.akiya.cc:foo/bar.git',
description: 'git 分支')
}
environment {
// Jenkins 访问 Git cert ID
git_cert_id = 'jenkins-git-key'
// git checkout 出来的工程项目存放子目录
code_subdirectory = "./"
}
stages {
stage("CheckOut"){
steps{
script{
println("${branch_name}")
checkout([$class: 'GitSCM', branches: [[name: "${branch_name}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'RelativeTargetDirectory',
relativeTargetDir: "${code_subdirectory}"]],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: "${git_cert_id}",
url: "${repo_url}"]]])
}
}
}
stage("build"){
steps{
println "now branch is: ${branch_name}"
}
}
}
}

保存后,第一次直接 build 即可,报错属于正常现象,第一次 build 完成后可看到当前工程左侧菜单栏中 build 变成了 Build with Parameters

点击 Build with Parameters,可看到如下图,可看到 branch_name 窗口中仅有 master 且下方提示配置错误,这个时候不要慌问题不大。

出现这个问题也是正常现象,是由于我们在 gitParameter 中定义了 useRepository: 'git@git.akiya.cc:foo/bar.git',由于第一次构建会读取 pipeline 中定义好的参数并在 Jenkins 工程中建立对应的参数项,但是也仅仅只是建立了而已,我们要想 gitParameter 拿到 git 的 branch 与 tag 还需要再次 build 才行。

根据上图我们可以看到第二次 build 执行结果为 SUCCESS,同时也能看到已经按照我们脚本中打印出了当前代码的分支信息

再次回到项目构建页面,可以看到已经能够正确获取到项目的 branch 与 tag

评论

:D 一言句子获取中...

加载中,最新评论有1分钟缓存...