如何通过Jira部署触发含对应Issue Key的最新提交仓库的Jenkins流水线?
解决方案
1. 改造Jira工作流的Deploy转换
在Jira的「deploy」状态转换中添加自定义触发逻辑,作为整个流程的入口:
- 用ScriptRunner(或Jira自动化规则)给「deploy」转换添加Post函数
- 核心逻辑:获取当前Issue的Key,去Bitbucket查找关联该Key的最新代码提交所属仓库,再触发对应Jenkins流水线
2. 从Bitbucket定位目标仓库
通过Bitbucket REST API遍历ABC项目下的所有仓库,筛选出包含当前Issue Key的最新提交对应的仓库:
// Jira ScriptRunner中执行的Groovy脚本片段 def bitbucketUrl = "http://你的Bitbucket地址/rest/api/1.0" def projectKey = "ABC" def issueKey = issue.getKey() // 获取ABC项目下所有仓库 def repoListResp = new URL("${bitbucketUrl}/projects/${projectKey}/repos").getText() def repos = new groovy.json.JsonSlurper().parseText(repoListResp).values def latestCommit = null def targetRepo = null // 遍历仓库查询最新关联提交 repos.each { repo -> def commitUrl = "${bitbucketUrl}/projects/${projectKey}/repos/${repo.slug}/commits?message=${URLEncoder.encode(issueKey, 'UTF-8')}" def commitsResp = new URL(commitUrl).getText() def commits = new groovy.json.JsonSlurper().parseText(commitsResp).values if (commits.size() > 0) { def currentCommit = commits[0] // 取时间最新的第一条提交 if (!latestCommit || currentCommit.authorTimestamp > latestCommit.authorTimestamp) { latestCommit = currentCommit targetRepo = repo.slug } } }
注意:给Jira配置Bitbucket的API访问权限;如果仓库数量较多,可添加仓库列表缓存或并行查询逻辑优化速度
3. 触发对应Jenkins流水线
根据拿到的仓库slug,调用Jenkins API触发流水线,两种方式可选:
方式一:直接触发微服务流水线
假设流水线命名与仓库slug对应(比如user-service-pipeline对应仓库user-service):
// 接上面的脚本,找到targetRepo后执行 if (targetRepo) { def jenkinsUrl = "http://你的Jenkins地址" def jenkinsUser = "专用API用户" def jenkinsToken = "用户的API Token" def jobName = "${targetRepo}-pipeline" def triggerUrl = "${jenkinsUrl}/job/${jobName}/buildWithParameters?JIRA_ID=${issueKey}" def auth = "${jenkinsUser}:${jenkinsToken}".bytes.encodeBase64().toString() def conn = new URL(triggerUrl).openConnection() conn.setRequestMethod("POST") conn.setRequestProperty("Authorization", "Basic ${auth}") conn.setDoOutput(true) def respCode = conn.getResponseCode() if (respCode != 201) { issue.addComment("触发流水线失败,响应码:${respCode}") } } else { issue.addComment("未找到关联该Issue的代码提交,无法触发部署") }
方式二:通过主流水线触发
如果用主流水线统一调度,只需传入仓库slug参数:
def triggerUrl = "${jenkinsUrl}/job/main-pipeline/buildWithParameters?REPO_SLUG=${targetRepo}&JIRA_ID=${issueKey}" // 其余API调用逻辑同上
4. 权限与安全配置
- Jira执行脚本的用户:需拥有Bitbucket项目读权限、Jenkins流水线触发权限
- Bitbucket:允许Jira服务器IP访问API,开启仓库提交查询权限
- Jenkins:开启远程API访问,创建专用API用户,仅授予流水线触发权限,避免使用管理员账号
5. 异常处理
在脚本中添加异常捕获,出现问题时给Issue添加评论留痕:
try { // 上述查询和触发逻辑 } catch (Exception e) { issue.addComment("自动部署触发失败:${e.getMessage()}") log.error("Issue ${issueKey} 触发流水线失败", e) }
内容的提问来源于stack exchange,提问作者Sri
相关产品推荐
相关产品推荐

