gpt4 book ai didi

groovy - 使用 SCM 存储库中的文件夹列表填充 jenkinsfile 中的选择参数

转载 作者:行者123 更新时间:2023-12-05 02:02:09 25 4
gpt4 key购买 nike

我有一个 Jenkinsfile 驱动一个管道,用户必须在 bitbucket 存储库中选择一个特定的文件夹作为目标。我希望动态填充该选择参数下拉列表。

目前,我已经按照这个通用示例对选择参数列表进行了硬编码:

choice(name: 'IMAGE', choices: ['workload-x','workload-y','workload-z'])

我想知道这是否可以从 jenkinsfile 本身内部实现,或者我是否必须为此创建一个特定的 groovy 脚本然后调用它。无论哪种方式,我都有些迷茫,因为我对 Jenkins 还很陌生,而且才刚刚开始使用 Jenkinsfiles。

一些试错谷歌搜索让我创建了一个 groovy 脚本,它使用 json slurper 返回存储库中的文件夹名称数组:

import groovy.json.JsonSlurper
import jenkins.model.Jenkins

def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.Credentials.class,
Jenkins.instance,
null,
null
);

def credential = creds.find {it.id == "MYBITBUCKETCRED"}

if (!credential) { return "Unable to pickup credential from Jenkins" }
username = credential.username
pass = credential.password.toString()

def urlStr = "https://bitbucket.mydomain.com/rest/api/1.0/projects/MYPROJECT/repos/MYREPO/browse/"

HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection()
String encoded = Base64.getEncoder().encodeToString((username + ":" + pass).getBytes("UTF-8"));
conn.setRequestProperty("Authorization", "Basic " + encoded);
conn.connect();

def slurper = new JsonSlurper()
def browseList = slurper.parseText(conn.getInputStream().getText())

def dfList = browseList.children.values.path.name.findAll {it.contains('workload-')}

return dfList

返回结果如下:

Result:   [workload-a,workload-b,workload-c,workload-x,workload-y,workload-z]

但是我不确定如何在我的 Jenkinsfile 中调用它来填充下拉列表。

如有任何帮助,我们将不胜感激。

最佳答案

您可以这样做(按照我下面的示例)或使用 Active Choice Jenkins Plugins - 因为它允许一些常规脚本来准备您的选择

注意 - Choice 参数将在第一次运行后可用。

def choiceArray = []
node {
checkout scm
def folders = sh(returnStdout: true, script: "ls $WORKSPACE")

folders.split().each {
//condition to skip files if any
choiceArray << it
}
}

pipeline {
agent any;
parameters { choice(name: 'CHOICES', choices: choiceArray, description: 'Please Select One') }
stages {
stage('debug') {
steps {
echo "Selected choice is : ${params.CHOICES}"
}
}
}
}

关于groovy - 使用 SCM 存储库中的文件夹列表填充 jenkinsfile 中的选择参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66049517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com