Jenkins 管道与 kubectl get pods return "unexpected EOF"

Jenkins pipeline with kubectl get pods return "unexpected EOF"

我正在尝试创建一个多阶段的 Jenkins 管道,第一阶段创建图像,第二阶段从新创建的图像创建新的 pods,第三阶段检查每个 pods还活着。

第三阶段其中一个命令是:

result = sh(returnStdout: true, script: "kubectl get pods --all-namespaces | grep -i <specific pod name> | wc -l").trim()

我希望收到的值是 1 或 0,但是当命令 return 0 出现意外的 EOF 错误时:

/var/jenkins_home/workspace/git-test@tmp/durable-c72ab15c/script.sh: 第 1 行:寻找匹配的`''时出现意外的 EOF

在 运行 失败后,错误的位置不存在。

如何获得我需要的值?

舞台是这样的:

  def isDone = false
  def response = ""
  for (int i = 0; i < 10 && isDone == false; i++) {
    timeout(time: 60, unit: 'SECONDS') {
      waitUntil {
        response = sh(returnStdout: true, script: "kubectl get pods -o=name --all-namespaces --field-selector status.phase=Running | grep -i $testCaseName | grep . |  awk '{ print ($1 == \"\") ? \"0\" : \"1\" }'").trim()
        if (response != "") {
          return true
        }
      }
    }
    if (response == '1') {
      sh "echo '$testCaseName pod is running'"
      isDone = true
    } else {
      sh "echo '$testCaseName pod isn't running yet'"
      sleep(time:1,unit:"MINUTES")
    }

我仍然不确定这个问题的正确原因,但我假设它来自 Jenkins sh 命令的 readStdout 标志。

这个问题的解决方案是用 try catch 包装导致 unexpected EOF 错误的命令,这里是 if 部分,并将 else 部分放在 catch 部分。它看起来像这样:

def isDone = false
def response = ""
def state = ""
sh "mkdir -p ${workspace}/results/${currentBuildNumber}/$testCaseName"
for (int i = 0; i < 10 && isDone == false; i++) {
  sh "kubectl get pods --all-namespaces | grep -i $testCaseName | awk '{ printf ($4 == \"Running\") ? \"yes\" : \"'wait'\" }' > ${workspace}/results/${currentBuildNumber}/$testCaseName/commandResult.txt"
  sh "kubectl get pods --all-namespaces | grep -i $testCaseName | awk '{ printf $4 }' > ${workspace}/results/${currentBuildNumber}/$testCaseName/podState.txt"
  timeout(time:30,unit:"SECONDS") {
    waitUntil {
      response = readFile "${workspace}/results/${currentBuildNumber}/$testCaseName/commandResult.txt"
      return (response != "")
    }
  }
  timeout(time:30,unit:"SECONDS") {
    waitUntil {
      state = readFile "${workspace}/results/${currentBuildNumber}/$testCaseName/podState.txt"
      return (state != "")
    }
  }
  try {
    if ("$response" == "yes") {
      println("$testCaseName pod is running")
      isDone = true
    } else {
      println("$testCaseName pod state is: $state")
      sleep(time:1,unit:"MINUTES")
    }
  } catch(Exception e) {
    println("$testCaseName pod state is: $state")
    if ((i == 9) && (isDone == true)) {
      error("Build failed because $testCaseName pod couldn't start")
    } else {
      sleep(time:1,unit:"MINUTES")
    }
  }
}