Jenkins动态选择参数来读取github中的可解析主机文件



我有一个存储在GitHub中的可解析主机文件,我想知道是否有办法用选择参数列出jenkins中的所有主机?现在,每次我在Github中更新主机文件时,我都必须手动进入每个Jenkins作业,并手动更新选择参数。谢谢

我假设您的主机文件的内容与下面类似。

[client-app]
client-app-preprod-01.aws-xxxx
client-app-preprod-02.aws
client-app-preprod-03.aws
client-app-preprod-04.aws
[server-app]
server-app-preprod-01.aws
server-app-preprod-02.aws
server-app-preprod-03.aws
server-app-preprod-04.aws

选项01

你可以做下面这样的事情。在这里,您可以先签出repo,然后请求用户输入。我已经实现了函数getHostList()来解析主机文件以过滤主机条目。

pipeline {
agent any
stages {
stage('Build') {
steps {
git 'https://github.com/jglick/simple-maven-project-with-tests.git'
script {
def selectedHost = input message: 'Please select the host', ok: 'Next',
parameters: [
choice(name: 'PRODUCT', choices: getHostList("client-app","ansible/host/location"), description: 'Please select the host')]

echo "Host:::: $selectedHost"
}
}
}
}
}
def getHostList(def appName, def filePath) {
def hosts = []
def content = readFile(file: filePath)
def startCollect = false
for(def line : content.split('n')) {
if(line.contains("["+ appName +"]")){ // This is a starting point of host entries
startCollect = true
continue
} else if(startCollect) {
if(!line.allWhitespace && !line.contains('[')){
hosts.add(line.trim())
} else {
break
}
} 
}
return hosts
}

选项2

如果您想在不签出源和使用作业参数的情况下执行此操作。您可以使用Active Choice Parameter插件执行以下操作。如果你的存储库是私有的,你需要想办法生成一个访问令牌来访问Raw GitHub链接。

properties([
parameters([
[$class: 'ChoiceParameter', 
choiceType: 'PT_SINGLE_SELECT', 
description: 'Select the Host', 
name: 'Host',
script: [
$class: 'GroovyScript', 
fallbackScript: [
classpath: [], 
sandbox: false, 
script: 
'return ['Could not get Host']'
], 
script: [
classpath: [], 
sandbox: false, 
script: 
'''
def appName = "client-app"
def content = new URL ("https://raw.githubusercontent.com/xxx/sample/main/testdir/hosts").getText()
def hosts = []
def startCollect = false
for(def line : content.split("\n")) {
if(line.contains("["+ appName +"]")){ // This is a starting point of host entries
startCollect = true
continue
} else if(startCollect) {
if(!line.allWhitespace && !line.contains("[")){
hosts.add(line.trim())
} else {
break
}
} 
}
return hosts
'''
]
]
]
])
])
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
echo "Host:::: ${params.Host}"
}
}
}
}
}

更新

当您调用私有回购时,您需要发送一个带有访问令牌的Basic Auth标头。因此,请使用以下groovy脚本。

def accessToken = "ACCESS_TOKEN".bytes.encodeBase64().toString()
def get = new URL("https://raw.githubusercontent.com/xxxx/something/hosts").openConnection();
get.setRequestProperty("authorization", "Basic " + accessToken)
def content = get.getInputStream().getText()

最新更新