Jenkins Active选择参数从Nexus Repo中获取工件

ep6jt1vc  于 2023-08-03  发布在  Jenkins
关注(0)|答案(1)|浏览(102)

我想从nexus的存储库中获取工件。我不知道如何在Active Choice Parameter中编写groovy脚本。我在Jenkins中使用Nexus3平台插件。但它只允许一个管道中有一个存储库。我想用它作为动态参数。我不知道什么是时髦的剧本。任何帮助都将不胜感激。先谢谢你。我尝试了下面的代码,但它没有显示任何东西。
import groovy.json.JsonSlurper import javax.ws.rs.client.ClientBuilder

// Nexus API endpoint and credentials 
def nexusUrl = "https://nexus.xxx.xxx"
def nexusUsername = "admin"
def nexusPassword = "xxxxxx"

// Nexus repository and group ID
def repositoryId = "maven-releases"
def groupId = "xxx.xxx"
// Fetch artifacts from Nexus
def fetchArtifactsFromNexus() {
def artifacts = []
def apiUrl = "${nexusUrl}/service/rest/v1/search/assets?repository=${repositoryId}&group=${groupId}"

// Create a client and set authentication credentials
def client = ClientBuilder.newClient()
client.property('http.connection.timeout', 5000)
client.property('http.receive.timeout', 5000)
client.property('http.send.timeout', 5000)

// Set authentication credentials
client.register(HttpAuthenticationFeature.basic(nexusUsername, nexusPassword))

// Make the request and parse the JSON response
def response = client.target(apiUrl).request().get()
def responseJson = new JsonSlurper().parseText(response.readEntity(String))

// Extract artifact names from the response
responseJson.items.each { item ->
    artifacts << item.name
}

return artifacts.join(',')
}

// Execute the script and return the artifacts as a comma-separated string
fetchArtifactsFromNexus()

字符串

gblwokeq

gblwokeq1#

有新的jenkins plugin。我还是没有用。
My solutuion for nexus rest with groovy URL:

// myLibrary.groovy jenkins library script.
// you may call it in pipeline myLibrary.makeGetReq(param1,param2)
def makeGetReq(requestUrl,basicAuth){
    try {
        def url = new URL(requestUrl)
        def get = url.openConnection()
        get.requestMethod ="GET" 
        get.setRequestProperty("Content-Type", "application/json")
        get.setRequestProperty("Authorization", basicAuth)
        def getRC = get.getResponseCode()
        if (getRC.equals(200)) {
            return get.getInputStream().getText()
        }
    }
    catch(Exception e) {
        println("ERROR: " + e.toString()); 
    }
}

字符串
管道:

def List result = []
def resp = myLibrary.makeGetReq(url,authStr)
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parseText(resp)
result.addAll(json.items*.maven2.artifactId.unique())
result.join(',') // if you need string. choice param uses list


还有continuationToken用于分割REST结果--您可以使用while循环来获取artifactID的完整列表
复制粘贴流水线

def nexusUrl = 'http://nexus:8081'
def List artifactList = []
def String version_choice 

def getMavenRepos(url){
    def repo_api = "$url/service/rest/v1/repositories"
    def response = httpRequest authentication: 'jenkinsCREDS',  url: repo_api, wrapAsMultipart: false
    def jsoned_content  = readJSON(text: response.content)
    def filtred_array = jsoned_content.findAll{ it.format == 'maven2' && it.type == 'hosted' }
    return filtred_array*.name.sort()
}

def getMavenArtifacts(Map config = [:]){
    def List artifacts = []
    def artifact_api = "${config.url}/service/rest/v1/search/assets?&maven.groupId=${config.repo}&maven.extension=pom"
    // you may use any extention
    def response = httpRequest authentication: 'jenkinsAD',  url: artifact_api, wrapAsMultipart: false
    def jsoned_content  = readJSON(text: response.content, returnPojo:true)
    artifacts += jsoned_content.items 
    def continuationToken = jsoned_content.continuationToken
    while (continuationToken){
        def c_response = httpRequest(
                authentication: 'jenkinsCREDS',
                url: "$artifact_api&continuationToken=${jsoned_content.continuationToken}",
                wrapAsMultipart: false)
        def c_jsoned_content  = readJSON(text: c_response.content, returnPojo:true)
        artifacts += c_jsoned_content.items 
        continuationToken = c_jsoned_content.continuationToken
    }
    // this is example you may select anythihg you want
    def artifacts_with_version = artifacts.collect{ entry ->
        "${entry.maven2.artifactId}-${entry.maven2.version}"}

    return [artifacts_with_version, artifacts]
    
}


pipeline {
    agent any
    parameters {
        choice (
            choices:getMavenRepos(nexusUrl),
            description: 'maven repo list',
            name: 'repo')
    }
    stages {
        stage('Choose artifactId') {
            steps {
                script{
                    artifactList = getMavenArtifacts(url:nexusUrl, repo:params.repo)
                    timeout(4) {
                        version_choice = input(
                            message: 'Set artifactIds',
                            parameters: [
                                choice(
                                    choices:artifactList[0],
                                    description: 'maven artifact ids',
                                    name: 'artifactID')])
                    }
                }
                
            }
        }
        stage('do your staff') {
            steps{
                echo params.repo
                echo version_choice
                script{
                    print(artifactList[1].collect{
                       [artifactId:it.maven2.artifactId, downloadUrl: it.downloadUrl]
                    })
                }
            }
        }
    }
}

jenkinsCREDS只是一些credentials

相关问题