使用 Groovy 创建 Jenkins 环境变量 [英] Creating a Jenkins environment variable using Groovy

查看:64
本文介绍了使用 Groovy 创建 Jenkins 环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目采用版本号(以."或_"分隔).我尝试编写一个 Groovy 脚本,该脚本仅使用这些数字中的前两个数字来创建 Jenkins 环境变量:

My project takes in a version number (separated by '.' or '_'). I tried writing a Groovy script that creates a Jenkins environment variable using only the first two of these numbers:

//Get the version parameter
def env = System.getenv()
def version = env['currentversion']
def m = version =~/d{1,2}/
env = ['miniVersion':m[0].m[1]]

我这样做正确吗?我什至可以创建一个新的环境变量吗?有没有更好的解决方案?

Am I doing this correctly? Can I even create a new environment variable? Is there a better solution to this?

推荐答案

Jenkins 1.x

以下 groovy 代码段应传递版本(正如您已经提供的那样),并将其作为miniVersion"存储在作业的变量中.

Jenkins 1.x

The following groovy snippet should pass the version (as you've already supplied), and store it in the job's variables as 'miniVersion'.

import hudson.model.*

def env = System.getenv()
def version = env['currentversion']
def m = version =~/d{1,2}/
def minVerVal = m[0]+"."+m[1]

def pa = new ParametersAction([
  new StringParameterValue("miniVersion", minVerVal)
])

// add variable to current job
Thread.currentThread().executable.addAction(pa)

然后可以从其他构建步骤访问该变量.例如

The variable will then be accessible from other build steps. e.g.

echo miniVersion=%miniVersion%

输出:

miniVersion=12.34

我相信您需要使用系统 Groovy 脚本"(仅在主节点上)而不是Groovy 插件" - https://wiki.jenkins-ci.org/display/JENKINS/Groovy+plugin#Groovyplugin-GroovyScriptvsSystemGroovyScript

I believe you'll need to use the "System Groovy Script" (on the Master node only) as opposed to the "Groovy Plugin" - https://wiki.jenkins-ci.org/display/JENKINS/Groovy+plugin#Groovyplugin-GroovyScriptvsSystemGroovyScript

我相信之前的 (Jenkins 1.x) 行为由于 此安全公告...

I believe the previous (Jenkins 1.x) behaviour stopped working because of this Security Advisory...

可以通过将系统属性 hudson.model.ParametersAction.keepUndefinedParameters 设置为 true 来恢复以前的行为.这可能非常不安全,仅供短期解决.

It's possible to restore the previous behaviour by setting the system property hudson.model.ParametersAction.keepUndefinedParameters to true. This is potentially very unsafe and intended as a short-term workaround only.

java -Dhudson.model.ParametersAction.keepUndefinedParameters=true -jar jenkins.war

要允许将特定的已知安全参数名称传递给构建,请将系统属性 hudson.model.ParametersAction.safeParameters 设置为以逗号分隔的安全参数名称列表.

To allow specific, known safe parameter names to be passed to builds, set the system property hudson.model.ParametersAction.safeParameters to a comma-separated list of safe parameter names.

例如

java -Dhudson.model.ParametersAction.safeParameters=miniVersion,FOO,BAR -jar jenkins.war

这篇关于使用 Groovy 创建 Jenkins 环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆