一尘不染

使用“ Process”在共享库Jenkins管道中执行CURL

jenkins

我在Jenkins管道的共享库中有一个方法。想法是使用该库并将文件上传到远程主机。该库将导入到单例库中。

import com.package.jobutil.UploadFile

def uploadFunc() {
 def uploader = new UploadFile(this)
 withCredentials ([usernamePassword(credentialsId: 'user', userNameVariable: 'username', passwordVariable:'password)]) {
  uploader.uploadArtifact("${username}", "${password}", file.txt, location)
 }
}

def call() {
 uploadFunc()
}

实例化的类如下所示:

class UploadFile {
   def steps

   UploadFile (steps) {
     this.steps = steps
   }

   pulic uploadArtifct (String user, String password, String file, String location) {
   Process proc
   def cred = "${user}:${pass}"
   def cmd = ["curl", "-v", "-u", cred, "--upload-file", file, location]
   steps.println "CURL: ${cmd}"

   proc = cmd.execute()
  }
}

即使我println在日志中看到该行。我看不到curl命令正在执行。我缺少某种无法调用的功能cmd.execute吗?

编辑

当我curl直接在库中使用时,它可以工作。

pulic uploadArtifct (String user, String password, String file, String 
  location) {
  def cred = "${user}:${password}"
  def cmd = "curl -v -u ${cred} --upload-file ${file} ${nexusLocation}/${file}"
  try {

  steps.sh cmd
  } catch (Exception e) {
    throw new RuntimeExceptipon("Cannot execute curl, exception: [${e.getClass().getName()} - '${e.getMessage()}']")
   }
  }

但是,尝试使用时Process不起作用。

pulic uploadArtifct (String user, String password, String file, String 
  location) {
  def cred = "${user}:${password}"
  def cmd = ["curl", "-v", "-u", cred, "--upload-file", ${file}, ${location}]
  try {
   def sout = new StringBuffer(), serr = new StringBuffer()
   def proc = cmd.execute()
   proc.consumeProcessOutput(sout, serr)
   proc.waitForOrKill(1000)
   println sout
  } catch (Exception e) {
    throw new RuntimeExceptipon("Cannot execute curl, exception: [${e.getClass().getName()} - '${e.getMessage()}']")
   }
  }

我得到的异常是:

java.lang.RuntimeException: Cannot execute curl, exception: [groovy.lang.MissingMethodException - 'No signature of method: java.lang.String.div() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [file.txt]

阅读 292

收藏
2020-07-25

共1个答案

一尘不染

如此处所述,您需要捕获stdout / stderr才能 _看到_任何内容。

至少:

def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)

或者,如本要点所示

def sout = new StringBuffer(), serr = new StringBuffer()
def proc = cmd.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println sout

阻止呼叫的示例为:

println new ProcessBuilder( 'sh', '-c', 'du -h --max-depth=1 /var/foo/bar/folder\\ with\\ spaces | sort -hr').redirectErrorStream(true).start().text

def cmd = ["curl", "-v", "-u", cred, "--upload-file", ${file}, ${location}/${file}]
No signature of method: java.lang.String.div() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [file.txt]

/‘in’ ${location}/${file}‘被解释为’ /div)操作,而不是字符串。

尝试使用该curl命令参数:

${location}+"/"+${file}

如您在随后的问题中所述,所有路径都必须在双引号之间。

2020-07-25