我的要求很简单,我只是想外部化一些“值”以使我的 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) 完全使用groovy 代码。此代码片段需要您在脚本安全插件附带的“进程内脚本批准”中启用多个方法签名,因此只有在经过适当考虑后才应执行此操作。
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
}
}
}
}
关于jenkins - 从属性文件加载属性并使其在整个作业/管道中可用 - Jenkins 声明性语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43754764/