i am trying to create a Folder in Jenkins using a groovy script. For that i use an REST API call. My starting point is was basically a curl command:
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"
I got this from https://gist.github.com/marshyski/abaa1ccbcee5b15db92c and found later out that it also works if you put the user into the URL. Using this line in the Windows cmd works perfectly and generates me a new Folder in my Jenkins.
Now i try to do the same thing but from a groovy script. For that i use the following code:
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());
}
I got this basically from Groovy built-in REST/HTTP client? (i have heard apache Http is deprecated)
Long story short i did not manage to create a folder with the given groovy script. I always get an 403 response (I run the script from windows cmd and inside jenkins with the script console).
I also played around with Jenkins-crumb but that seems not necessary because the above cmd command already worked.
So the question is does anyone know what i am missing? why is the groovy script not working but the curl command is? Or has anyone a different approach on how to generate a Folder in Jenkins from a groovy script?
Edit: When i try to run the curl command in the groovy script with .execute() i get an "The system cannot find the file specified" Error.
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()