问题描述
我有一个用于所有存储库的通用 Jenkins 共享库,如下所示。
vars/_publish.groovy
pipeline {
environment {
abc= credentials(’abc')
def= credentials(‘def’)
}
stages {
stage('Build') {
steps{
sh ‘docker build'
}
}
stage('Unit-test') {
steps{
sh ‘mvn test'
}
}
詹金斯文件
@Library('my-shared-library@branch') _
_publish() {
}
我有 10 个存储库,每个存储库都有自己的 Jenkinsfile,如上所示,它指的是 jenkins 共享库 (vars/_publish.groovy)。我这里有一个条件,我需要通过。对于少数存储库,我想跳过单元测试而只执行构建阶段。对于其他存储库,我想要这两个阶段。有没有人可以根据存储库或存储库名称跳过特定阶段
解决方法
是的,你可以使用 when 这样的表达
pipeline {
agent any
stages {
stage('Test') {
when { expression { return repositoryName.contains('dev') } } <---------Add put your repository name 'dev' so whenever the repository names is ''dev' then execute this stage
steps {
script {
}
}
}
}
}
def repositoryName() {
def repositoryName = ['dev','test'] <----Add here the 10 repo name
return repositoryName
}
在我的例子中,repo 名称是 dev 和 test,因此您可以随意添加
,我会像这样装饰我的共享库和 Jenkinsfile 来实现您的场景。
vars/_publish.groovy
def call(body={}) {
def pipelineParams = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = pipelineParams
body()
pipeline {
agent any;
stages {
stage('build') {
steps {
echo "BUILD"
}
}
stage('unitest') {
when {
anyOf {
equals expected: true,actual: pipelineParams.isEmpty();
equals expected: false,actual: pipelineParams.skipUnitest
}
}
steps {
echo "UNITEST"
}
}
}
}
}
我正在启用我的共享库以接受来自 Jenkinsfile 的参数,并使用 when{}
DSL 决定是否跳过 unitest 阶段
Jenkinsfile
如果您的 Jenkins 文件来自 repo 有以下详细信息,将跳过 unitest 阶段
@Library('jenkins-shared-library')_
_publish(){
skipUnitest = true
}
在这两种情况下将运行 unitest 阶段
@Library('jenkins-shared-library')_
_publish(){
skipUnitest = false
}
和
@Library('jenkins-shared-library')_
_publish(){
}