【问题标题】:Parse value from Groovy into Shell step Jenkins将 Groovy 中的值解析为 Shell 步骤 Jenkins
【发布时间】:2017-10-02 13:27:35
【问题描述】:

我的 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 脚本中调用它的例子,这将是一个真正的帮助

【问题讨论】:

    标签: shell jenkins groovy


    【解决方案1】:
    def cmd = "ls -a"
    new File("${build.workspace}/mycmd.sh").setText("#!/bin/sh\n${cmd}\n")
    

    下一步执行 Shell ./mycmd.sh

    【讨论】:

    • 它返回以下错误:+ ./mycmd.sh./mycmd.sh: line 2: [echo: command not found nc: port range not valid 这很好,因为它正在运行,但仍然不确定在命令行中运行此 cmd 与通过此 .sh 执行它之间有什么区别文件:(
    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 2017-10-09
      相关资源
      最近更新 更多