如何在Jenkins的groovy动态参数上获取作业名称

时间:2013-09-03 20:14:31

标签: groovy jenkins

我需要在这个例子中获取名称作业,我有一个代码用于获取带有该代码的构建参数的先前值

jenkins.model.Jenkins.instance.getItem("nameOfJob").lastBuild.getBuildVariables().get("NameOfParameter");

现在的工作名称是硬编码的,我需要得到这个名字将是当前工作的名称,我怎能不这样做?

谢谢

7 个答案:

答案 0 :(得分:11)

Groovy动态参数无法访问jenkins其他作业所知的常用环境变量。

这是一个获得工作名称的工作黑客:

def build = Thread.currentThread().toString()
def regexp= ".+?/job/([^/]+)/.*"
def match = build  =~ regexp
def jobName = match[0][1]

答案 1 :(得分:4)

如果您正在项目中运行一个步骤,那么就有一个环境变量JOB_NAME

在groovy中你可以访问

String jobName = System.getenv('JOB_NAME')

如果您希望在构建后发布,请检查此答案How to get specific information about the current build project in Jenkins with Groovy?

根据附加问题,要在设置阶段访问Jenkins作业名称,您需要使用支持groovy的EnvInject plugin - 它需要返回地图

println "currentJob -->${currentJob}"
println "currentBuild --> ${currentBuild}"

[currentJob: currentJob, currentBuild: currentBuild]

这是我使用shell作业回显新环境时的输出

Started by user anonymous
[EnvInject] - Loading node environment variables.
[EnvInject] - Preparing an environment for the build.
[EnvInject] - Keeping Jenkins system variables.
[EnvInject] - Keeping Jenkins build variables.
[EnvInject] - Evaluation the following Groovy script content: 

println "currentJob -->${currentJob}"
println "currentBuild --> ${currentBuild}"

[currentJob: currentJob, currentBuild: currentBuild]

currentJob -->hudson.model.FreeStyleProject@5ffe31a7[_xxx]
currentBuild --> _xxx #6
[EnvInject] - Injecting contributions.
Building on master in workspace /var/lib/jenkins/workspace/_xxx
[_xxx] $ /bin/sh -xe /tmp/hudson3812821436584477615.sh
+ echo _xxx #6
_xxx #6 
+ echo hudson.model.FreeStyleProject@5ffe31a7[_xxx]
hudson.model.FreeStyleProject@5ffe31a7[_xxx]
Finished: SUCCESS

你需要做一些字符串操作来分离作业和构建

答案 2 :(得分:2)

以下是uno-choice插件参数Groovy脚本(在绑定构建之前的意思)为我工作的:

def job = this.binding.jenkinsProject

如果您对工作名称感兴趣,那么:

def jobName = this.binding.jenkinsProject.name

答案 3 :(得分:1)

(Thread.currentThread().toString() =~ /job\/(.*?)\//)[0][1]

答案 4 :(得分:1)

这在脚本管道的脚本块中对我有用

${env.getEnvironment().get('JOB_NAME')}

答案 5 :(得分:0)

首先请确保您使用“执行系统Groovy脚本”步骤(不是“执行Groovy脚本”)。

获得工作名称的最简单答案是:

String JOB_NAME = build.project.name;

就像在shell脚本中一样使用JOB_NAME

但是由于您实际上需要一个工作实例,因此请使用:

build.project.lastBuild.getBuildVariables().get("NameOfParameter");

但是,要获取当前构建的参数(目前正在运行),只需使用:

// string
// (bool is also a string -- "true"/"false" string)
def someStr = build.buildVariableResolver.resolve("someBuildParam");
// mapping to int
def someInt = build.buildVariableResolver.resolve("someBuildParam") as int;

Jenkins文档中的类名有些棘手,所以这里有一些技巧:

答案 6 :(得分:0)

def jobName = env.JOB_NAME在2.176 Enterprise滚动环境下对我来说效果很好。 这具有将其列入白名单的额外好处,因此您可以将其用作锁定的Jenkins。

相关问题