在GitHub推送到特定分支时触发Jenkins作业

4
我正在尝试基于 GitHub 对特定分支的 PUSH 触发作业。
我设置了一个 webhook 到 JENKINS_URL/git/notifyCommit?url=REPO_URL 和没有计划的 Poll SCM
该作业会在每次 push 时触发,但我无法过滤掉分支 - 我希望只在 master 分支上进行 push 时才触发。

3个回答

0

我最初寻找了一些插件,但没有找到任何能够满足您要求的东西。

最初,我创建了一个单独的作业,在那里检测分支,然后只构建其他作业作为下游作业。

这就是我所做的,并且已经成功实现了。该功能已经在Jenkins中可用,我们不需要安装任何插件。

我认为,下面的图片将使一切变得清晰明了。

enter image description here

如果我们只想在更改被推送或合并到TEST分支时触发作业,我们可以这样做。

最简单的解决方案。无需脚本,无需插件。单击高级按钮以添加refspec,在添加源代码管理部分中的存储库URL时默认隐藏

有关完整信息,请阅读我的博客


1
这个指令会触发所有分支构建,也就是说,如果任何一个分支上有新的提交,它都会执行构建。 - Idothisallday
@Idothisallday 在我的 Jenkins 服务器上运行得非常好。为什么不显示设置,只需在 Refspec 中指定分支即可仅触发该分支的操作。 - Tara Prasad Gurung

0
您可以参考这个答案:如何在Bitbucket上的特定分支中触发Jenkins构建

I just discovered that Bitbucket does not allow to choose specific hook on pushing to any branch. It just calls all the hooks, then starts all Jenkins jobs.

My solution was to create an specific file on my machine which Jenkins is installed and set a Bitbucket hook to this file. (e.g.

http://{jenkins url}:{apache port}/check.php)

Note that this apache port is not the same of Jenkins', but Apache's. In my case, Jenkins was running at 8080 and Apache at 7777.

It did this to run php script, but not in Jenkins' directory.

Since Bitbucket hook sends a json file, I was able to verify in check.php which branch has been pushed on. Reference: POST hook

management

After the verification using a simple 'if', I just called the right url to start the right job with exec_curl, like:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, http://{jenkins url}:{jenkins port}/job/{job name}/build?token={job token});
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);

And voilà.

0

你需要使用git hook来实现这个目的。

git hook会将分支名称作为参数传递。

Hook代码

#!/bin/sh

while read oldrev newrev refname
do
    branch=`echo $refname | cut -d'/' -f3`

    ###
    # Do whatever you want to do here with the branch name
    ###

done

使用git hook是什么意思?这不是我一直在做的吗? 此外,我的工作是一个构建流程工作,它编排对多个工作的调用,我不能在该工作中使用shell脚本。 - Tal Auslander
我向您展示了如何过滤分支,然后根据分支名称决定要运行哪个URL。 - CodeWizard
这意味着必须通过“执行 shell”进行自由样式的作业,对吗?我想避免这种情况,因为它会拉取一个非常大的仓库,这将导致很长的拉取/提取时间。 - Tal Auslander
反之亦然,您将代码放在调用构建服务器的git服务器上。提交执行钩子,使用分支名称和参数调用Jenkins。 - CodeWizard
Git服务器是GitHub,它将信息发送到Webhook,但Jenkins中的Git插件由于某些原因无法处理它。 - Tal Auslander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接