仅在构建标记

时间:2018-01-21 02:50:45

标签: jenkins jenkins-pipeline multibranch-pipeline jenkins-declarative-pipeline

我有一些构建逻辑,例如发布,我希望Jenkins只在构建Git标记时执行。如何使用Jenkin的声明性管道来实现这一目标?

换句话说,我正在尝试构建与Travis CI部署标签功能相当的功能:

deploy:
  [...]
  on: 
    tags: true

有一个built-in condition to check the branch,但我没有看到一个表明该标签。

2 个答案:

答案 0 :(得分:8)

更新:从Pipeline Model Definition Plugin版本1.2.8开始,您现在可以使用buldingTag()

stage('Deploy') {
  when {
    buildingTag()
  }
  steps {
    echo 'Replace this with your actual deployment steps'
  }
}

使用Multibranch Pipeline配置时,您可以使用expression条件以及基础Branch API Plugin提供的TAG_NAME环境变量。遗憾的是,您无法直接检查环境变量是否在Groovy级别定义(API限制),因此您必须在shell中进行测试:

stage('Deploy') {
  when { expression { sh([returnStdout: true, script: 'echo $TAG_NAME | tr -d \'\n\'']) } }
  steps {
    echo 'Replace this with your actual deployment steps'
  }
}

上面利用了非空字符串在Groovy中的真实性。

在未来的版本中可能会引入更简单的方法。请参阅jenkinsci/pipeline-model-definition-plugin#240

答案 1 :(得分:1)

我有一个类似的情况我通过获取分支名称来处理,如果标记它就像refs/tags/v101.0.0-beta8468,所以你必须提取/解析它以检查它是否是一个标记,否则它只是分支名称比如pipeline。例如

if(env.gitlabBranch.contains("tags"))
    {
        isTag = true
        echo "----------------true----------------"
        branch = env.gitlabBranch.split("/")[2]
        imageTag = branch

    }
    else
    {
        branch = "origin/$env.gitlabBranch"

    }

在chekout步骤中提到分支为

 branches: [[name: "${branch}"]

如果您想从同一个项目结帐。 基于isTag变量,您可以选择运行某个阶段。 像:

if(isTag) {
stage('Deploy') {
   // your logic here
}

将您的isTag初始化为false :)