Jenkins create Folder with REST API in groovy script - rest

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()

curl command not present on windows platform - so you have
"The system cannot find the file specified".
403 - forbidden. something wrong with auth I guess.
better to move user&pass to header:
post.setRequestProperty("Authorization", "Basic ${"username:password".bytes.encodeBase64().toString()}")

Related

PowerShell runs Invoke-WebRequest instead of curl [duplicate]

I'm new to cURL, just got it installed but it seems to only do what it feels like. I'm using the 64 bit version I got from here: http://curl.haxx.se/latest.cgi?curl=win64-ssl-sspi with installation instructions I found here: http://guides.instructure.com/m/4214/l/83393-how-do-i-install-and-use-curl-on-a-windows-machine. Opening a new Powershell window I'm able to use a simple GET request like so:
curl http://localhost:3000
but if I run a POST
curl -d "hello world" http://localhost:3000
it tells me "Invoke-WebRequest : Parameter cannot be processed because the parameter name 'd' is ambiguous. Possible matches include: -DisableKeepAlive -Debug."
Trying to get help I type
curl -h or curl --help
gives me "Invoke-WebRequest : Missing an argument for parameter 'Headers'. Specify a parameter of type 'System.Collections.IDictionary' and try again."
As I mentioned, I'm a cURL newbie but it seems strange that it can do get requests but nothing else. Any ideas what I'm doing wrong?
Windows 7 64 bit
Powershell version 4
Your problem is that your are not using the Curl you installed but a CmdLet called Invoke-WebRequest.
Just execute :
Remove-item alias:curl
And test your curl again, then store it in your profile.
The explanation is that it exists a native alias to the Invoke-WebRequest which is a CmdLet that is supposed to deliver a kind of curl service.
From Windows 10 build 17063 and later (April 2018), Curl is included into Windows, so that you can execute it directly from Cmd.exe or PowerShell.exe. To use it in PowerShell be careful to unalias this CmdLet or explicitly call curl.exe.
Built with Schannel (Microsoft's native TLS engine), libcurl still perform peer certificate verification, but instead of using a CA cert bundle, it uses the certificates that are built into the OS.
You can execute curl commands with Command Prompt instead of Windows Powershell. Command prompt doesn't alias curl commands like Windows Powershell does.
To open command prompt, hit Win + R, type cmd in the input box, <Enter>.

Ansible Tower: Writing job stdout to files

Is there any way in Ansible Tower to create log files for the each job stdout? I am aware that the below API will show me the output.
https://<tower_ip>/api/v2/jobs/<job id>/stdout/
But we also want these output into separate files for each job. Could you please help me with this?
According the Tower API Reference Guide Jobs it is possible to get via REST API call a formatted downloadable plain text, in example
curl --silent -u ${TOWER_USER}:${TOWER_PASSWORD} --location https://${TOWER_URL}/api/v2/jobs/${JobID}/stdout?format=txt_download --output job_${JobID}.log
and write it into a file like job_${JobID}.log.
Thanks to
man curl

Trying to issue a curl POST command in PowerShell

I have been able to use curl to issue a query and return a result or series of named parameters.
I want to issue a POST command on these series of named parameters, but the "multiple" is tripping me up.
I can issue the POST command on one of the parameters, but not on the entire series of them.
The command I'm using within powershell is
curl.exe -u username:password -X POST http://site.url:8042/modalities/MCTEST/store -d '["6a3eb7c4-a9d83950-24d36e94-5c20d248-0b5ce989","8c93b430-757278ab-21ab643c-c98aa03d-da14148e","b8f648fa-175de243-de76b1c0-2dc7551a-928b86a5","c865b966-f0c7d2c2-0a1114e0-80531305-31cd104e","aac7f73f-fcb922ef-b950c4c1-ee1d512e-e2aeb5ae"]'
If I issue the command on only one, it processes fine...obviously, I don't need quotes or brackets, which I think is what is tripping me up.
curl.exe -u username:password -X POST http://site.url:8042/modalities/MCTEST/store -d 6a3eb7c4-a9d83950-24d36e94-5c20d248-0b5ce989
I've tried subbing the double quotes with a backslash, tried adding a backslash, I've tried everything i can think of...I'm missing something.
I get a response of "must provide a json value"
I'm not sure what my error is in my syntax.
Any ideas?
external commands have to be called/quoted properly
PowerShell: Running Executables
Solve Problems with External Command Lines in PowerShell
Top 5 tips for running external commands in Powershell
Execution of External Commands in PowerShell Done Right
Using Windows PowerShell to run old command-line tools (and their
weirdest parameters)
See also about Redirection
Powershell: Pipe external command output to another external command
How to use the curl command in PowerShell?
Stackoverflow example by Ansgar Wiechers
$CurlArgument = '-u', 'xxx#gmail.com:yyyy',
'-X', 'POST',
'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
'--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE #CurlArgument

What is the PowerShell Equivilant of `curl -L https://unpkg.com/#pnpm/self-installer | node`?

I'm using GitLab.com with a Windows OS runner, so we commonly use PowerShell in place of Bash for scripting steps in the console. I'm trying to use pnpm and the examples they give suggest the following
$ curl -L https://unpkg.com/#pnpm/self-installer | node
$ install pnpm
What's the PowerShell version of the above curl requests piped into node?
I've been trying both Invoke-RestMethod and using the curl alias from within PowerShell, like
PS> curl https://unpkg.com/#pnpm/self-installer | node
but have been getting
SyntaxError: Invalid or unexpected token
Also from the curl docs, I know --location is needed.
As a best practice within scripts, I'd suggest explicitly using the parameter names and passing the correct type rather than letting the interpreter coerce for you (Uri takes a System.Uri and System is imported to PowerShell as a default):
$uri = [Uri]'https://unpkg.com/#pnpm/self-installer'
$js = Invoke-RestMethod -Uri $uri
The reason for your syntax error? the # symbol is special in PowerShell for a feature called Splatting.
When I ran the above, it spit out the contents of a js script to my console. It can then be assumed node takes cli, piped input and is in your PATH:
$js | node
Another assumption is you have an install in your PATH or the script creates some kind of interactive terminal:
$ install pnpm
--location isn't necessary here since Invoke-RestMethod will follow a redirect up to 5 hops by default (this can be configured with MaximumRedirection).

Change "curl" command to work with PowerShell Invoke-WebRequest (TeamForge API)

I am attempting to use the TeamForge API. This is my first dip into web requests so I am sure I am missing something obvious.
To even begin, I realize I need to request an oauth token. According to the documentation, I have to execute the following command:
# Base URL of TeamForge site.
site_url="https://teamforge.example.com"
# TeamForge authentication credentials.
username="foo"
password="bar"
# Requested scope (all)
scope="urn:ctf:services:ctf urn:ctf:services:svn urn:ctf:services:gerrit urn:ctf:services:soap60"
curl -d "grant_type=password&client_id=api-client&scope=$scope&username=$username&password=$password" $site_url/oauth/auth/token
Seems fairly straightforward. Knowing that curl is an alias for Invoke-WebRequest, I attempted to run the following in PowerShell:
$site="https://my.teamforge.site"
$user="myuser"
$pass="mypass"
$scope="urn:ctf:services:ctf"
curl "grant_type=password&client_id=api-client&scope=$scope&username=$user&password=$pass" -Uri $site/oauth/auth/token
What I got was an error:
Invoke-WebRequest : A positional parameter cannot be found that accepts argument
'grant_type=password&client_id=api-client&scope=urn:ctf:services:ctf&username= rest of line redacted for obvious reasons
I took this to mean I fudged the syntax. I have no clue where to start taking this appart and plugging it into Invoke-WebRequest command. Like I said, this is my first time attempting this. My searches for answers thus far has not been helpful. I think I am asking the wrong questions.
How do I deconstruct this curl command so that I can convert it to something I can use in PowerShell?