Jenkins Pipeline 脚本参数定义与引用:分支选择
在 Jenkins Pipeline 脚本中,可以使用 parameters 关键字来定义参数,例如:
parameters {
string(name: 'BRANCH', defaultValue: 'master', description: 'Git branch to build')
}
在 stage 步骤中,可以使用 ${params.<parameter_name>} 来引用参数,例如:
stage('Build') {
steps {
git branch: '${params.BRANCH}', url: 'https://github.com/myorg/myrepo.git'
sh 'mvn clean install'
}
}
要从 Git 项目中选择任意分支进行构建,可以在参数类型中使用 choice,例如:
parameters {
choice(name: 'BRANCH', choices: gitBranches('https://github.com/myorg/myrepo.git'), description: 'Git branch to build')
}
def gitBranches(repoUrl) {
def branches = []
sh(script: "git ls-remote --heads ${repoUrl} | cut -d'/' -f3-", returnStdout: true).split().each { branches.add(it) }
return branches
}
这里使用了 git ls-remote 命令获取远程仓库的所有分支,并使用 cut 命令提取分支名称。然后将分支名称添加到一个列表中,并返回给参数类型 choice。这样在构建时,就可以选择一个 Git 项目的所有分支作为参数值。
原文地址: https://www.cveoy.top/t/topic/nwEJ 著作权归作者所有。请勿转载和采集!