Jenkins在groovy脚本中使用REST API创建文件夹

时间:2019-03-20 12:22:25

标签: rest jenkins groovy directory

我正在尝试使用groovy脚本在Jenkins中创建一个文件夹。为此,我使用REST API调用。 我的出发点基本上是curl命令:

curl -XPOST "http://userName:YourApiToken@JenkinsURL:Port/createItem?name=FolderName&mode=com.cloudbees.hudson.plugins.folder.Folder" -H "Content-Type:application/x-www-form-urlencoded"

我是从https://gist.github.com/marshyski/abaa1ccbcee5b15db92c那里得到的,后来发现,如果将用户放入URL,它也可以工作。在Windows cmd中使用此行可以完美地工作,并在我的Jenkins中生成一个新文件夹。

现在,我尝试从普通脚本中执行相同的操作。为此,我使用以下代码:

import groovyx.net.http.*

def post = new URL("http://userName:YourApiToken@JenkinsURL:Port/createItem?name=FolderName&mode=com.cloudbees.hudson.plugins.folder.Folder").openConnection();
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(200)) {
    println(post.getInputStream().getText());
}

我基本上是从Groovy built-in REST/HTTP client?那里得到的(我听说过Apache Http已被弃用)

长话短说,我没有设法用给定的常规脚本创建一个文件夹。我总是得到 403响应(我从Windows cmd和脚本控制台在jenkins中运行脚本)。

我也玩过詹金斯·克鲁姆(Jenkins-crumb),但这似乎没有必要,因为上面的cmd命令已经起作用。

所以问题是,有人知道我失踪了吗?为什么groovy脚本不起作用,但是curl命令起作用? 还是有人用不同的方法从普通的脚本生成Jenkins中的文件夹?

编辑: 当我尝试使用.execute()在groovy脚本中运行curl命令时,出现“系统找不到指定的文件”错误。

String command = "curl -XPOST "+ '"http://user.name:ApiToken@JenkinsURL:8080/createItem?name=FolderName&mode=com.cloudbees.hudson.plugins.folder.Folder"'+ ' -H "Content-Type:application/x-www-form-urlencoded"'
println(command)
command.execute()

1 个答案:

答案 0 :(得分:0)

curl命令在Windows平台上不存在-因此您有

  

“系统找不到指定的文件”。

403-禁止。我猜认证有问题。

更好地将用户和传递移动到标题:

post.setRequestProperty("Authorization", "Basic ${"username:password".bytes.encodeBase64().toString()}")