You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkins Active Choice参数中运行Shell脚本?

在Jenkins Active Choice参数中执行Shell脚本并获取Nexus镜像列表

核心逻辑

Active Choice 参数基于 Groovy 脚本运行,要在其中执行 Shell 命令,需通过 Groovy 的 execute() 方法调用 Shell 脚本,捕获输出后处理成动态参数选项。

分步实现与示例

1. Groovy 调用 Shell 的基础写法

在 Active Choice 参数的 Groovy 脚本框中,用以下结构执行 Shell 命令并获取输出:

// 执行Shell命令,替换为你的curl请求
def proc = """
curl -u "nexus用户名:密码" "http://你的nexus地址/service/rest/v1/search?repository=目标仓库名&format=docker"
""".execute()

// 等待命令执行完成,获取标准输出和错误输出
proc.waitFor()
def output = proc.in.text
def error = proc.err.text

// 处理命令执行失败的情况
if (proc.exitValue() != 0) {
    return ["请求失败: ${error}"]
}

2. 解析 Nexus API 返回的镜像列表

Nexus Docker 仓库的 API 返回 JSON 格式数据,需用 Groovy 的 JSON 工具解析提取镜像名称:

import groovy.json.JsonSlurper

// 解析JSON响应
def jsonSlurper = new JsonSlurper()
def response = jsonSlurper.parseText(output)

// 提取镜像名称(根据Nexus实际返回结构调整,示例假设items中包含name字段)
def images = response.items.collect { item ->
    item.name // 若返回结构不同,可改为item.attributes.docker.name等
}.unique() // 去重

// 返回处理后的镜像列表作为参数选项
return images ?: ["未找到可用镜像"]

3. 完整 Groovy 脚本示例

整合上述逻辑,完整脚本如下:

import groovy.json.JsonSlurper

// 配置Nexus相关信息
def nexusUser = "admin"
def nexusPass = "你的nexus密码"
def nexusUrl = "http://nexus.example.com/service/rest/v1/search"
def targetRepo = "docker-repo"

// 构造curl命令
def curlCmd = "curl -u '${nexusUser}:${nexusPass}' '${nexusUrl}?repository=${targetRepo}&format=docker'"
def proc = curlCmd.execute()

proc.waitFor()
def output = proc.in.text
def error = proc.err.text

// 处理命令执行错误
if (proc.exitValue() != 0) {
    return ["API请求失败: ${error}"]
}

// 解析并提取镜像列表
def jsonData = new JsonSlurper().parseText(output)
def imageList = jsonData.items.collect { it.name }.unique().sort()

return imageList ?: ["无可用镜像"]

常见问题与注意事项

  • Nexus 认证优化:不要直接写明文密码,建议用 Jenkins 凭据管理存储认证信息,通过 credentials() 方法调用:
    def nexusCreds = credentials('nexus-auth-credential-id')
    def curlCmd = "curl -u '${nexusCreds.username}:${nexusCreds.password}' '${nexusUrl}?repository=${targetRepo}&format=docker'"
    
  • Groovy 语法细节:字符串拼接时注意引号转义,多行命令用三重引号包裹时避免缩进导致的语法错误。
  • 权限与网络:确保 Jenkins 代理节点能执行 curl 命令,且网络可访问 Nexus API 地址。
  • API 路径适配:不同版本 Nexus 的 API 路径可能不同,先在终端测试 curl 命令是否能正常返回结果,再调整脚本中的路径参数。
  • 输出清洗:若 Shell 输出有多余内容,可通过 trim() 或正则表达式过滤无效字符,保证参数列表的整洁。

Active Choice 参数配置步骤

  1. 确保 Jenkins 已安装 Active Choices Plugin,未安装则在插件管理中搜索安装。
  2. 进入目标 Jenkins 任务的配置页面,找到「参数化构建过程」,点击「添加参数」,选择「Active Choices Parameter」或「Active Choices Reactive Parameter」(按需选择)。
  3. 在「脚本」选项卡中选择「Groovy Script」,粘贴上述完整脚本。
  4. 配置参数名称、描述等信息,保存任务即可。

内容的提问来源于stack exchange,提问作者Swapnil Ghule

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:27:38