Jenkins 是否可以自动检测并构建 git 存储库中新创建的标签?

StackOverflow https://stackoverflow.com/questions/7805603

  •  25-10-2019
  •  | 
  •  

如果我们的 Jenkins CI 服务器能够在 Github 存储库中创建标签时自动检测、部署和构建标签,那就太好了。

这可能吗?

有帮助吗?

解决方案

通过以下配置,您可以使作业构建所有标签:

  1. 使作业获取标签就像分支一样:单击存储库 URL 下方的“高级”按钮并输入 Refspec +refs/tags/*:refs/remotes/origin/tags/*
  2. 让它使用分支说明符构建所有标签“分支” */tags/*
  3. 启用 SCM 轮询,以便作业检测新标签。

这种方法有一个缺点:工作将建立 全部 标签而不仅仅是新添加的标签。因此,在创建作业后,将为每个现有标签触发一次。因此,您可能希望作业一开始不执行任何操作,然后等到所有现有标签都已处理完毕,然后才配置您想要为每个新标签完成的构建步骤。

由于标签在 git 中不会更改,因此每个新标签只会触发一次作业。

其他提示

为了克服@oberlies的答案的缺点,即将建立所有标签,而是使用特殊的触发器构建。扳机构建使用与主构建相同的GIT存储库和分支,以及以下(POST)构建步骤。

构建 - >执行外壳:

# Get the most recent release tag.
PATTERN="release-tag-[0-9][0-9]-[0-9][0-9][0-9][0-9]"
TAG=$(git log --tags=$PATTERN --no-walk --pretty="format:%d" | grep -m 1 -o $PATTERN)

# Due to a Jenkins limitation (https://issues.jenkins-ci.org/browse/JENKINS-8952)
# when passing environment variables we have to write the tag to a file and
# inject it later again.
mv release.properties release-old.properties || true
echo "TAG = $TAG" > release.properties

# Fail the build if the most recent release tag did not change.
! diff release.properties release-old.properties

构建 - > 注入环境变量:

Properties File Path: release.properties

后构建动作 - >:: 触发其他项目的参数化构建

Projects to build: <your main project>
Trigger when build is: Stable
Parameters: TAG=$TAG

最后,在您的主要构建中,带有以下字符串参数的勾选“此构建已被参数化”

Name: TAG
Default Value: <your release branch>

并在“源代码管理”部分中使用“构建”字段中的“ $ tag”。

您可以安装后接收器钩,该钩检查是否符合标签,并在詹金斯(Jenkins)创建构建。

钩看起来像这样[*]:

#!/usr/bin/env python

import sys
from subprocess import Popen, PIPE, check_call

def call_git(command, args):
    return Popen(['git', command] + args, stdout=PIPE).communicate()[0]
JENKINS = 'http://localhost:8002/jenkins'
TOKEN = 'asdf8saffwedssdf'
jobname = 'project-tag'

def handle_ref(old, new, ref):
     print 'handle_ref(%s, %s, %s)' % (old, new, ref)
     if not ref.startswith('refs/tags/'):
          return
     url = '%s/job/%s/buildWithParameters?token=%s&branch=%s' % (
        JENKINS, jobname, TOKEN, new)
     print "queueing jenkins job " + jobname + " for " + new
     check_call(["wget", "-O/dev/null", "--quiet", url])
if __name__ == '__main__':
    for line in sys.stdin:
        handle_ref(*line.split())

*]注意:这只是从略有不同的脚本快速转换,因此很可能这里有一些小错误。这主要是为了展示这个想法。

在詹金斯一侧,您需要配置参数化作业。唯一的参数是“分支”。

  1. 检查“此构建已被参数化”,并添加参数
  2. 在“源代码管理 - >构建“ put'$分支”的分支机构中

这提供了一种相当安全,可靠的构建方式。要测试,通过Web界面运行构建,它将要求参数的值。

在现代(?)多分支管道的世界中,构建标签的工作原理如下。

  1. 添加“行为”来发现标签:
    enter image description here
  2. 使用插件 基本分支建立策略 为标签添加“构建策略”:enter image description here不要忘记也为分支机构添加构建策略;该插件完全禁用默认值!

您可以使用选项“ Git Publisher”,该选项是作为该选项的一部分 git插件 在成功的构建/部署后创建标签。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top