Pratik Jaiswal Pratik Jaiswal - 5 months ago 38
PHP Question

Build Jenkins job with parameters from CURL / HTTP POST



I am making an AJAX request to invoke a

PHP(preferably) or similar
file and want that code to
trigger jenkins job remotely
. Also I would like to pass
parameters
to the job that will get triggered. For example, along with AJAX request, my
data
will be holding the value of some vars such as
job
name,
runid
, etc. as shown below:

$.ajax({
url: 'runjob.php',
type: "GET",
data: { job : job, runid : id },
success: function(data) {
....
}


As per https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API, I have written a small PHP code below:

runjob.php

<?php

curl -X POST http://mobile-jenkins.testzynx.com:8080/job/trserver-git/build \
--data token=12981209380192380129802 \
--data-urlencode json='{"parameter": [{"name":"id","value":runid}, {"name":"profile", "value":"tr-flex.properties"}]}'

?>


where
runid
is the var that I will have in my AJAX request code and
trserver-git
is the name of jenkins job.

which follows the syntax as shown in the actual URL:

syntax from above url


curl -X POST JENKINS_URL/job/JOB_NAME/build \
--data token=TOKEN \
--data-urlencode json='{"parameter": [{"name":"id", "value":"123"}, {"name":"verbosity", "value":"high"}]}'

?>


where token is the user API token that I got from my properties in Jenkins.

However, this code(
runjob.php
) does not seem to work and
I am not able to trigger jobs and hence no parameters
.

Later once I am able to trigger the job with parameters passed,
I want to read those parameters to a shell scipt that runs as a part of jenkins job.
For example,

./runTest.sh -Drunid=$id -Dprofile=$profile
like maven parameters.

Is there a good example on how to achieve this remote parameterized jenkins job trigger and read parameters scenario?
PHP preferred
.

Answer

Here is my solution and this worked for me:

$url = "http://build:f9280f75396f83a0@mobile-jenkins.domain.com:8080/job/android-test/buildWithParameters";     
$data = "POST_RESULTS=true&RUN_ID=".$testrun_id."&CHECK_NAME=SampleAutomatedPlan";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch);    
Comments