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

求助:用Jenkins Active Choice参数从Nexus仓库拉取构件的Groovy脚本

在Jenkins Active Choice Parameter中编写Groovy脚本从Nexus拉取构件

原代码存在的问题

  1. 缺失必要导入:HttpAuthenticationFeature类未导入,导致认证逻辑无法执行
  2. 客户端兼容性问题:ClientBuilder在Jenkins环境中可能存在类加载依赖缺失,引发静默失败
  3. 返回格式错误:Active Choice Parameter需要返回列表(List)而非逗号分隔字符串,否则无法生成下拉选项
  4. 无错误处理:请求失败时没有任何提示,无法排查问题
  5. API路径可选优化:若目标是获取构件(而非具体资产文件),应使用Nexus的构件搜索API而非资产搜索API

修正后的Groovy脚本

import groovy.json.JsonSlurper

// Nexus配置
def nexusUrl = "https://nexus.xxx.xxx"
def nexusUsername = "admin"
def nexusPassword = "xxxxxx"
def repositoryId = "maven-releases"
def groupId = "xxx.xxx"

// 从Nexus获取构件列表
def fetchArtifacts() {
    def artifacts = []
    // 若要获取构件(如groupId:artifactId),用这个API路径;若要获取资产文件(如xxx.jar),保留原assets路径
    def apiUrl = "${nexusUrl}/service/rest/v1/search?repository=${repositoryId}&group=${groupId}"
    
    try {
        // 构建URL连接,处理认证
        def url = new URL(apiUrl)
        def conn = url.openConnection() as HttpURLConnection
        conn.setRequestMethod("GET")
        // 设置基础认证
        def authString = "${nexusUsername}:${nexusPassword}".bytes.encodeBase64().toString()
        conn.setRequestProperty("Authorization", "Basic ${authString}")
        conn.setConnectTimeout(5000)
        conn.setReadTimeout(5000)
        
        // 检查响应状态
        if (conn.getResponseCode() != 200) {
            throw new Exception("Nexus请求失败,状态码: ${conn.getResponseCode()},响应: ${conn.getErrorStream()?.text}")
        }
        
        // 解析JSON响应
        def responseJson = new JsonSlurper().parse(conn.getInputStream())
        
        // 提取所需内容:这里取构件的artifactId,若要资产文件名则切换回原逻辑取item.name
        responseJson.items.each { item ->
            artifacts << item.artifactId
            // 若要获取版本号,可改为:artifacts << item.version
            // 若要获取资产文件名,用:artifacts << item.name(需切换回assets API路径)
        }
        
        // 去重并排序(可选)
        return artifacts.unique().sort()
    } catch (Exception e) {
        // 抛出错误,Jenkins会显示在参数配置页面
        throw new RuntimeException("拉取Nexus构件失败: ${e.message}", e)
    }
}

// 执行并返回列表(Active Choice会自动将列表转为下拉选项)
fetchArtifacts()

使用说明

  1. API路径选择:
    • 若需要获取构件(如groupId:artifactId):使用/service/rest/v1/search,提取item.artifactId或item.version
    • 若需要获取具体资产文件(如xxx.jar、xxx.pom):切换回/service/rest/v1/search/assets,提取item.name
  2. 认证处理:通过Base64编码实现HTTP基础认证,无需额外依赖类
  3. 错误反馈:添加异常捕获,请求失败时会在Jenkins参数配置页面显示错误信息,便于排查
  4. 列表处理:返回去重排序后的列表,Active Choice Parameter会自动生成下拉选项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 06:15:22