我的要求很简单,我只想外部化一些“值”以使我的Jenkinsfile更可重用,为此,我需要从一个文件中加载属性,该文件将紧挨Jenkinsfile,并确保这些属性是在管道中的任何地方都可用。我对groovy和Jenkins代码仍然是陌生的,但是从未想到过如此简单的事情会如此困难。我在脚本安全性插件中启用了一些方法,但是以下代码(以及我尝试过的几种变体)始终会引起错误或显示null或给我NPE。我尝试了多种组合,下面的代码只是其中之一。
properties = null
@NonCPS
def loadProperties() {
checkout scm
File propertiesFile = new File('${workspace}/pipeline.properties')
propertiesFile.withInputStream {
properties.load(propertiesFile)
}
}
pipeline {
agent none
stages {
stage ('prepare') {
agent any
steps {
script {
loadProperties()
echo "${properties['repo']}"
}
}
}
stage('Build') {
agent any
steps {
sh 'echo ${properties.repo}'
}
}
}
}
我想出了两种方法来外部化Jenkins管道中的属性。您可以根据主要差异选择选择。
1)完全使用常规代码。此代码段将要求您在脚本安全性插件随附的“进程内脚本批准”中启用多个方法签名,因此,只有在经过适当考虑后,才能进行此操作。
properties = null
def loadProperties() {
node {
checkout scm
properties = new Properties()
File propertiesFile = new File("${workspace}/pipeline.properties")
properties.load(propertiesFile.newDataInputStream())
echo "Immediate one ${properties.repo}"
}
}
pipeline {
agent none
stages {
stage ('prepare') {
agent any
steps {
script {
loadProperties()
echo "Later one ${properties.branch}"
}
}
}
stage('Build') {
agent { label 'master' }
steps {
// works fine. properties is available everywhere
echo properties.branch
}
}
}
}
2)使用管道实用程序步骤插件-管道插件套件默认情况下包括此插件,它允许在无需启用安全异常的情况下更好地加载属性。我会推荐这种方法。
properties = null
def loadProperties() {
node {
checkout scm
properties = readProperties file: 'pipeline.properties'
echo "Immediate one ${properties.repo}"
}
}
pipeline {
agent none
stages {
stage ('prepare') {
agent any
steps {
script {
loadProperties()
echo "Later one ${properties.ansible}"
}
}
}
stage('Build') {
agent any
steps {
echo properties.branch
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句