在 Jenkins 构建步骤 (Windows) 中从 groovy 脚本访问构建环境变量 [英] Access to build environment variables from a groovy script in a Jenkins build step (Windows)

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

问题描述

我正在使用 Scriptler 插件,因此我可以将 groovy 脚本作为构建步骤运行.我的 Jenkins slaves 以服务模式在 Windows 上运行.使用scriptler,我不需要使用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.

但是我在构建步骤中无法获取环境变量...这是有效的:

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

System.getenv("BASE")

其中 BASE 是 jenkins 启动时环境变量的一部分.但是,我想得到

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"

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

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:

打印JOB_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 脚本访问构建环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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