通过使用变量来构建名称来调用jenkins作业

时间:2012-07-20 14:44:53

标签: jenkins start-job

我尝试从参数化触发器启动作业,然后从给定变量计算名称。 是否可以在现场设置:     构建触发器构建项目 像这样的价值      $ {RELEASE} - 主要 - $ {PROJECT} -LOAD_START

1 个答案:

答案 0 :(得分:4)

不幸的是,构建触发器无法实现这一点。我为这个“更高阶的构建作业”寻找了一个解决方案,它允许你用一个参数化的构建插件创建一个动态构建名称,但我找不到一个。

但是,使用Groovy Postbuild Plugin,你可以做很多有力的事情。下面是一个脚本,可以修改为执行您想要的操作。特别要注意,它使用build.buildVariables.get("MY_ENV_VAR")获取环境变量。环境变量TARGET_BUILD_JOB指定要构建的构建作业的名称。在您的情况下,您可能希望使用以下两个环境变量构建TARGET_BUILD_JOB

build.buildVariables.get("RELEASE")
build.buildVariables.get("PROJECT")

对脚本进行了注释,如果您不熟悉基于Java的Groovy,那么它应该是有意义的!

import hudson.model.*
import hudson.model.queue.*
import hudson.model.labels.*
import org.jvnet.jenkins.plugins.nodelabelparameter.*

def failBuild(msg)
{
     throw new RuntimeException("[GROOVY] User message, exiting with error: " + msg)
}

// Get the current build job
def thr = Thread.currentThread()
def build = thr?.executable

// Get the parameters for the current build job
// For ?:, see "Elvis Operator" (http://groovy.codehaus.org/Operators#Operators-ElvisOperator)
def currentParameters = build.getAction(ParametersAction.class)?.getParameters() ?: 
    failBuild("There are no parameters to pass down.")

def nodeName = build.getBuiltOnStr()
def newParameters = new ArrayList(currentParameters); newParameters << new NodeParameterValue("param_NODE", 
    "Target node -- the node of the previous job", nodeName)

// Retrieve information about the target build job
def targetJobName = build.buildVariables.get("TARGET_BUILD_JOB")
def targetJobObject = Hudson.instance.getItem(targetJobName) ?: 
    failBuild("Could not find a build job with the name $targetJobName. (Are you sure the spelling is correct?)")
println("$targetJobObject, $targetJobName")
def buildNumber = targetJobObject.getNextBuildNumber()

// Add information about downstream job to log
def jobUrl = targetJobObject.getAbsoluteUrl()
println("Starting downstream job $targetJobName ($jobUrl)" +  "\n")
println("======= DOWNSTREAM PARAMETERS =======")
println("$newParameters")

// Start the downstream build job if this build job was successful
boolean targetBuildQueued = targetJobObject.scheduleBuild(5,
      new Cause.UpstreamCause(build),
      new ParametersAction(newParameters)
    );

if (targetBuildQueued)
{
    println("Build started successfully")
    println("Console (wait a few seconds before clicking): $jobUrl/$buildNumber/console")
}
else
    failBuild("Could not start target build job")