将Groovy中的值解析为Shell步骤Jenkins

时间:2017-10-02 13:27:36

标签: shell jenkins groovy

我的Jenkins构建步骤中有一个Groovy脚本,用于计算构建持续时间并将值放入我想在shell脚本中执行的字符串中。

我尝试过多种方式但仍然没有运气。在Jenkins Slave上运行确切的字符串工作正常,因此希望将该字符串传递给shell脚本步骤并在之后运行它。我该怎么做呢?

我考虑过设置一个环境变量,但目前只找到了检索它们的方法。

import hudson.model.*
import java.math.*

def apiKey = "secret"
def buildId = System.getenv("BUILD_ID")
def buildNo = System.getenv("BUILD_NUMBER")
def jobName = System.getenv("JOB_NAME")
jobName = jobName.replaceAll("\\.","-") 
def nodeName = System.getenv("NODE_NAME")

def (startDate, startTime) = buildId.tokenize("_")
def (YY, MM, DD) = startDate.tokenize("-")
def (hh, mm, ss) = startTime.tokenize("-")
MathContext mc = new MathContext(200);
Date startDateTime = new GregorianCalendar(YY.toInteger(), MM.toInteger() - 1, DD.toInteger(), hh.toInteger(), mm.toInteger(), 
ss.toInteger()).time
Date end = new Date()
long diffMillis = end.getTime() - startDateTime.getTime()     
long buildDurationInSeconds = (diffMillis / 1000);

String metric = String.format("%s.jenkins.%s.%s.%s.duration %s", 
apiKey, nodeName, jobName, buildNo, buildDurationInSeconds)

def cmd = 'echo "+metric+" | nc carbon.hostedgraphite.com 2003'

在这一步之后,我将在jenkins中调用“执行Shell”步骤,传递“cmd”的值。如果某人有一个传递值的示例,然后在shell脚本中调用它将是一个真正的帮助

2 个答案:

答案 0 :(得分:0)

def cmd = "ls -a"
new File("${build.workspace}/mycmd.sh").setText("#!/bin/sh\n${cmd}\n")

并执行下一步执行Shell ./mycmd.sh

答案 1 :(得分:0)

试试这个

def metric="WHAT_YOU_WANT_TO_PASS"
sh "echo $metric | nc carbon.hostedgraphite.com 2003"