本文介绍了在Jenkins构建步骤(Windows)中,从groovy脚本访问构建环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Scriptler插件,所以我可以运行一个groovy脚本作为构建步骤。我的Jenkins从站在服务模式下运行在Windows上。使用脚本程序,我不需要使用Windows批处理脚本。

I'm using Scriptler plugin, so I can run a groovy script as a build step. My Jenkins slaves are running on windows in service mode. With scriptler, I don't need to use windows batch scripts.

但是我无法在构建步骤中获取环境变量...这是正常工作: / p>

But I have trouble to get the environment variables in a build step... This is working:

System.getenv("BASE")

其中 BASE 是jenkins启动时的env-vars的一部分。但是,我想获得

Where BASE is part of the env-vars on jenkins startup. However, I would like to get

%JOB_NAME%

如果我添加一个执行Windows批处理命令构建步骤:

If I'm adding an "Execute Windows batch command" build step:

echo %JOB_NAME%

它有效。
如果我添加一个脚本脚本作为具有相同设置的构建步骤:

It works.If I'm adding a scriptler script as a build step with the same settings:

println "JOB_NAME: " + System.getenv("JOB_NAME")

我得到:

JOB_NAME: null

所以如何从groovy脚本中注入环境变量作为构建步骤?

So how can I reach the injected environment variables from a groovy script as a build step?

推荐答案

Scriptler Groovy脚本似乎不获取构建的所有环境变量。但是您可以做的是强制他们作为脚本的参数:

The Scriptler Groovy script doesn't seem to get all the environment variables of the build. But what you can do is force them in as parameters to the script:


  1. 将Scriptler构建步骤添加到您的工作中选择定义脚本参数选项

  1. When you add the Scriptler build step into your job, select the option "Define script parameters"

为要传入的每个环境变量添加一个参数,例如Name:JOB_NAME,Value :$ JOB_NAME。该值将从Jenkins构建环境中使用'$ envName'类型变量进行扩展,作业配置设置中的大多数字段根据我的经验支持这种扩展。

Add a parameter for each environment variable you want to pass in. For example "Name: JOB_NAME", "Value: $JOB_NAME". The value will get expanded from the Jenkins build environment using '$envName' type variables, most fields in the job configuration settings support this sort of expansion from my experience.

在您的脚本中,您应该有一个与参数名称相同的变量,因此您可以使用以下参数访问参数:

In your script, you should have a variable with the same name as the parameter, so you can access the parameters with something like:

printlnJOB_NAME = $ JOB_NAME

println "JOB_NAME = $JOB_NAME"

我没有使用Sciptler,除了一些实验,但你的问题提出了一个有趣的问题。我希望这有帮助!

I haven't used Sciptler myself apart from some experimentation, but your question posed an interesting problem. I hope this helps!

这篇关于在Jenkins构建步骤(Windows)中,从groovy脚本访问构建环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 14:50