我有一個存盤在 GitHub 中的 ansible 主機檔案,我想知道是否有辦法用選擇引數列出 jenkins 中的所有主機?現在,每次我在 Github 中更新主機檔案時,我都必須手動進入每個 Jenkins 作業并手動更新選擇引數。謝謝!
uj5u.com熱心網友回復:
我假設您的主機檔案的內容類似于以下內容。
[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插件執行以下操作。如果您的存盤庫是私有的,您需要找到一種方法來生成訪問令牌以訪問原始 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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/508711.html
標籤:github詹金斯可靠的詹金斯管道ansible-库存
上一篇:獲取java.io.NotSerializableException:jenkins中的org.jenkinsci.plugins.workflow.job.WorkflowJob錯誤
