我正在尝试将我的 jenkins 管道转换为共享库,因为它可以在大多数应用程序上重复使用。作为其中的一部分,我在 vars 文件夹中创建了 groovy 文件,并将管道保存在 github 的 jenkins 文件中,并且能够在 jenkins 中成功调用它
作为改进这一点的一部分,我想通过文件传递参数、变量、节点标签,这样我们就不应该接触 jenkins 管道,如果我们想修改任何变量、参数,我们必须在 git repo 本身中做到这一点< /p>
pipeline {
agent
{
node
{
label 'jks_deployment'
}
}
environment{
ENV_CONFIG_ID = 'jenkins-prod'
ENV_CONFIG_FILE = 'test.groovy'
ENV_PLAYBOOK_NAME = 'test.tar.gz'
}
parameters {
string (
defaultValue: 'test.x86_64',
description: 'Enter app version',
name: 'app_version'
)
choice (
choices: ['10.0.0.1','10.0.0.2','10.0.0.3'],
description: 'Select a host to be delpoyed',
name: 'host'
)
}
stages {
stage("reading properties from properties file") {
steps {
// Use a script block to do custom scripting
script {
def props = readProperties file: 'extravars.properties'
env.var1 = props.var1
env.var2 = props.var2
}
echo "The variable 1 value is $var1"
echo "The variable 2 value is $var2"
}
在上面的代码中,我使用了管道实用程序步骤插件并且能够从 extravars.properties 文件中读取变量。我们也可以对 jenkins 参数做同样的事情吗?或者我们是否有任何合适的方法来处理通过 git repo 中的文件传递这些参数?
也可以为节点标签传递变量吗?
================================================ ======================
以下是我在这个项目中所做的改进
Used node label plugin to pass the node name as variable
下面是我的 vars/sayHello.groovy 文件内容
def call(body) {
// evaluate the body block, and collect configuration into the object
def pipelineParams= [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = pipelineParams
body()
pipeline {
agent
{
node
{
label "${pipelineParams.slaveName}"
}
}
stages {
stage("reading properties from properties file") {
steps {
// Use a script block to do custom scripting
script {
// def props = readProperties file: 'extravars.properties'
// script {
readProperties(file: 'extravars.properties').each {key, value -> env[key] = value }
//}
// env.var1 = props.var1
// env.var2 = props.var2
}
echo "The variable 1 value is $var1"
echo "The variable 2 value is $var2"
}
}
stage ('stage2') {
steps {
sh "echo ${var1}"
sh "echo ${var2}"
sh "echo ${pipelineParams.appVersion}"
sh "echo ${pipelineParams.hostIp}"
}
}
}
}
}
下面是我的 vars/params.groovy 文件
properties( [
parameters([
choice(choices: ['10.80.66.171','10.80.67.6','10.80.67.200'], description: 'Select a host to be delpoyed', name: 'host')
,string(defaultValue: 'fxxxxx.x86_64', description: 'Enter app version', name: 'app_version')
])
] )
下面是我的詹金斯文件
def _hostIp = params.host
def _appVersion = params.app_version
sayHello {
slaveName = 'master'
hostIp = _hostIp
appVersion = _appVersion
}
现在到我们可以改进了吗?有任何建议让我知道。