How to trigger multiple Jenkins jobs remotely using an HTTP request - jenkins

Is it possible to trigger multiple Jenkins jobs remotely using only jenkins url http://xxxxxx/?
Job name and parameters should be passed as script or json format.

You need to configure the jobs to enable the option named Trigger builds remotely (e.g., from scripts) under Build triggers where you need to enable the option and choose some authentication token.
You will also need to get the API token for your user to trigger the job. Log in to your Jenkins and in top-right corner click on your username and hit Configure button and create a new API token.
You can then invoke your job for example with curl:
curl -u <user>:<api_token> "http://<jenkins_url>/job/<job_name>/build?token=<job_token>"
To build the job with parameters, substitute /build with /buildWithParameters and pass the parameters in form of =, e.g.:
curl -u <user>:<api_token> "http://<jenkins_url>/job/<job_name>/buildWithParameters?token=<job_token>&<param1_name>=<param1_value>&<param2_name>=<param2_value>"...

Related

Trigger another jenkins job execute shell

How to trigger a jenkins job from another freestyle job execute shell section? For pipeline jobs we have groovy which makes it easy.
Two ways to do.
1 - Add a post-build step to build another project
2 - Create a user in jenkins to build remotely jobs (example remoteUser). Create a API TOken for this user. Edit the project to be triggered and make the option “Trigger Builds Remotely”, add an authentication token (IT'S NOT THE TOKEN OF THE USER, YOU CAN GENERATE A NEW FOR THIS).
Now can just use curl to start the job
curl -X POST HTTP://remoteUser:{remoteUser_API_TOKEN}#jenkins.domain/project/my_project/build?token=TOKEN

Establish relationship between two Jenkins Jobs available on different Jenkins server

I am building Jenkins for Test / QA automation scripts, lets name it TEST_JOB. For application, I have application source code Jenkins build, name it DEV_JOB.
My scenario is when DEV_JOB completes execution (successfully), execute TEST_JOB immediately. I am aware about setting up project upstream / downstream [ Build after other projects are built ] to accomplish this task. But here, Problem is DEV_JOB is on different server than TEST_JOB. Due to which, TEST_JOB fails to recognize DEV_JOB.
Now, how would I achieve this scenario?
You can use Jenkins API for remote trigger of Job.
Say you have job on DEV_JOB on JENKINS_1, add a penultimate step(or upstream/downstream project having only this step) which invokes TEST_JOB using remote API call of JENKINS_2 server.
Example command would be
$(curl --user "username:password" "http://JENKINS_2/job/TEST_JOB/buildWithParameters?SOMEPARAMETER=$SOMEPARAMETER")
username:password is a valid user on JENKINS_2.
Avoid using your own account here but rather a 'build trigger' account that only has permissions to start those jobs.

How to build with parameters in Jenkins from Gitlab push?

I have GitLab Community Edition 8.15.2 successfully trigger pipeline projects in Jenkins 2.32.1 using a webhook. I want the gitlab push to trigger a build with parameters but the parameter value is null when it comes through so the build fails.
The gitlab webhook looks like:
http://jenkins.server:8080/project/project-a/buildWithParameters?MYPARAM=foo
In my pipeline project I echo the parameter value out with
echo "MYPARAM: ${MYPARAM}"
and it's not set to anything. Any ideas on where I've gone wrong?
UPDATE
The actual code I'm using in the pipeline is:
node {
try {
echo "VM_HOST: ${VM_HOST}"
echo "VM_NAME: ${VM_NAME}"
stage('checkout') {
deleteDir()
git 'http://git-server/project/automated-build.git'
}
stage('build') {
bat 'powershell -nologo -file Remove-MyVM.ps1 -VMHostName %VM_HOST% -VMName "%VM_NAME%" -Verbose'
}
...
}
}
The parameter VM_HOST has a default value but VM_NAME doesn't. In my Console output in Jenkins I can see:
[Pipeline] echo
VM_HOST: HyperVHost
[Pipeline] echo
VM_NAME:
I have been struggling with this for weeks. I had it working once, but I couldn't get it to work again, untill today. And the solution was mindblowingly obvious ofcourse...
Automatically for each pipeline job I ticked the following box:
Build when a change is pushed to GitLab. GitLab CI Service URL:
http://jenkins.dev:8080/project/MyProject
Then from GitLab I used the webhook to trigger the above.
Like you I tried to add /buildWithParameters and tried many other things that didn't work.
The problem was, I ticked the wrong checkbox!
Since I trigger the build from a GitLab webhook, the above checkbox (build when a...) does not have to be checked at all.
What needs to be checked is:
Trigger builds remotely (e.g., from scripts)
That checkbox provides you with a new URL:
Use the following URL to trigger build remotely:
JENKINS_URL/job/MyProject/build?token=TOKEN_NAME or
/buildWithParameters?token=TOKEN_NAME
Like all the documentation I came along states and as you can see, the URL now no longer starts with /project, but with /job instead!
So tick that box and change your URL accordingly:
http://jenkins.server:8080/**job**/project-a/buildWithParameters?token=TOKEN_NAME&MYPARAM=foo
Least I want to mention the token:
In the GitLab webhook there is a seperate field for "token", which states:
Use this token to validate received payloads. It will be sent with the request in the X-Gitlab-Token HTTP header.
So, the token provided there will be sent along the request as a HTTP header.
This is the token which can be provided globally in the Jenkins setup.
The token you must provide in the Jenkins job when ticking the box Use the following URL to trigger build remotely must be send in the URL as GET parameter, just like the example shows.
Final note: personally I have never got this working completely, because I don't get the Jenkins CSRF protection off my back. Disabling it gives me another error. However, hopefully the above does fix the problem for you and others.
GitLab plugin does not allow you to pass arbitrary parameters. In their project there is an open issue for it that deserves to be upvoted.
My convoluted solution was to use the desired values for the push trigger as the default parameters of the job. Then I used the Parameterized Scheduler plugin to use other values in the scheduled executions.
The problem is that I got a bad usability for the job when it was manually run, since the default parameters were appropriate for the push hook.
I found the solution here https://www.jittagornp.me/blog/jenkins-gitlab-webhook/
I verified it with Jenkins 2.263.1 and GitLab Community Edition 13.6.1
Your webhook url will look like
https://hunter:11a403302a4f01b9b4975c0ac27441a5cc#jenkinsservername.com/job/yourjenkinsproject/buildWithParameters?token=Aju9ryHUu6t7W8wLSeCWtY2bWjzQduYNPyY7B3gs&yourparam=yourvalue
"hunter" ist your username in Jenkins.
The following is the Jenkins API Token you have to create in your Jenkins User Managment independent of the project.
The last Token is the one you specify in the jenkins project options under "Trigger builds remotely (e.g., from scripts)"
The last thing is to add your Parameter and value to the url with &param=value

How to trigger Jenkins builds remotely and to pass parameters

I am invoking a Jenkins job remotely using:
wget http://<ServerIP>:8080/job/Test-Jenkins/build?token=DOIT
Here Test-Jenkins job is invoked and DOIT is the security token that I have used.
Now I need to pass some parameters to the build.xml file of this job i.e. Test-Jenkins.
I have not yet figured out how to pass the variables yet.
See Jenkins documentation: Parameterized Build
Below is the line you are interested in:
http://server/job/myjob/buildWithParameters?token=TOKEN&PARAMETER=Value
In your Jenkins job configuration, tick the box named "This build is parameterized", click the "Add Parameter" button and select the "String Parameter" drop down value.
Now define your parameter - example:
Now you can use your parameter in your job / build pipeline, example:
Next to trigger the build with own/custom parameter, invoke the following URL (using either POST or GET):
http://JENKINS_SERVER_ADDRESS/job/YOUR_JOB_NAME/buildWithParameters?myparam=myparam_value
To add to this question, I found out that you don't have to use the /buildWithParameters endpoint.
In my scenario, I have a script that triggers Jenkins to run tests after a deployment. Some of these tests require extra info about the deployment to work correctly.
If I tried to use /buildWithParameters on a job that does not expect parameters, the job would not run. I don't want to go in and edit every job to require fake parameters just to get the jobs to run.
Instead, I found you can pass parameters like this:
curl -X POST --data-urlencode "token=${TOKEN}" --data-urlencode json='{"parameter": [{"name": "myParam", "value": "TEST"}]}' https://jenkins.corp/job/$JENKINS_JOB/build
With this json=... it will pass the param myParam with value TEST to the job whenever the call is made. However, the Jenkins job will still run even if it is not expecting the parameter myParam.
The only scenario this does not cover is if the job has a parameter that is NOT passed in the json. Even if the job has a default value set for the parameter, it will fail to run the job. In this scenario you will run into the following error message / stack trace when you call /build:
java.lang.IllegalArgumentException: No such parameter definition: myParam
I realize that this answer is several years late, but I hope this may be useful info for someone else!
Note: I am using Jenkins v2.163
You can simply try it with a jenkinsfile. Create a Jenkins job with following pipeline script.
pipeline {
agent any
parameters {
booleanParam(defaultValue: true, description: '', name: 'userFlag')
}
stages {
stage('Trigger') {
steps {
script {
println("triggering the pipeline from a rest call...")
}
}
}
stage("foo") {
steps {
echo "flag: ${params.userFlag}"
}
}
}
}
Build the job once manually to get it configured & just create a http POST request to the Jenkins job as follows.
The format is http://server/job/myjob/buildWithParameters?PARAMETER=Value
curl http://admin:test123#localhost:30637/job/apd-test/buildWithParameters?userFlag=false --request POST
To pass/use the variables, first create parameters in the configure section of Jenkins. Parameters that you use can be of type text, String, file, etc.
After creating them, use the variable reference in the fields you want to.
For example: I have configured/created two variables for Email-subject and Email-recipentList, and I have used their reference in the EMail-ext plugin (attached screenshot).
When we have to send multiple trigger parameters to jenkins job, the following commands works.
curl -X POST -i -u "auto_user":"xxxauthentication_tokenxxx" "JENKINS_URL/view/tests/job/helloworld/buildWithParameters?param1=162&param2=store"
You can trigger Jenkins builds remotely and to pass parameters by using the following query.
JENKINS_URL/job/job-name/buildWithParameters?token=TOKEN_NAME&param_name1=value&param_name1=value
JENKINS_URL (can be) = https://<your domain name or server address>
TOKE_NAME can be created using configure tab
curl -X POST -u Admin:<api_token> http://localhost:8080/job/<job_name>/buildWithParameters\?ColorValue\=sddddsd
curl -H "Jenkins-Crumb: <your_crumb_data>" -u "<username>:<password>" "http://<your_jenkins_url>?buildWithParameters?token=<your_remote_api_name>?<parameterA>=<val_parameter_A>&<parameterB>=<val_parameterB>"
You can change following parameters as you want:
<your_crumb_data>
<username>
<password>
<your_jenkins_url>
<your_remote_api_name>
<parameterA>
<parameterB>
<val_parameter_A>
<val_parameter_B>
Note: Placing double quotes may be critical. Pay attention, please.
2023 Update
It has now changed how Jenkins Authenticates.
You need to pass 2 tokens to execute your job remotely.
You need:
apiToken to authenticate your identity. This value is created from JENKINS_URL/me/configure . Also check here for documentation
Another Job authentication token which you create when you enable 'Trigger builds remotely'.
Below is a sample you can tweak to get it done.
PARAM1_VALUE=<param1_value>
PARAM2_VALUE=<param2_vale>
USERNAME=dummy_user_name
JENKINS_URL="http://10.xxx.x.xxx:8080"
JOB_TOKEN="<value>" # you create this token when you enable Job>Configure>Build Triggers>Trigger builds remotely
LOGIN_API_TOKEN="<value>" #get this value from JENKINS_URL/me/configure
curl -L --user $USERNAME:$LOGIN_API_TOKEN "$JENKINS_URL/job/JobName/buildWithParameters?token=$JOB_TOKEN&param1_name=$PARAM1_VALUE&param2_name=$PARAM2_VALUE"

Can one Jenkins Trigger a job on a remote jenkins

I have 2 Jenkins hosts, and would like First Jenkins to trigger a job on remote Jenkins based on "SUCCESS" in result on the first one.
I have looked at various plugins , but they all seem to indicate ONE Jenkins host, where multiple jobs can be chained in this manner.
Meanwhile, a jenkins plugin became available which makes it a lot easier:
https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+Remote+Trigger+Plugin
It's very easy to do using cURL requests, no need for plugins or master>slave relations. It took me 5 minutes from beginning to start.
Use the following manual:
https://www.nczonline.net/blog/2015/10/triggering-jenkins-builds-by-url/
You could set up a downstream job on host1 that only builds if first job on host1 succeeds.
In this job you would trigger a remote build much like i described it in this answer
Step 1: Install following plugins in both Jenkins.
Generic Webhook Trigger: Job can be triggered from http request.
HTTP Request Plugin: To send http request as build step
Any Build Step Plugin: To use any build step in post-build action.
Step 2: Configure job to be triggered(Jenkins B).
Select generic webhook trigger in build trigger and generate a token and paste.
After saving this job can be triggered by sending a http request to
http://JENKINS_B_URL/generic-webhook-trigger/invoke?token=TOKEN_VALUE
Step 3: In master Jenkins(Jenkins A) configure flexible publish settings in configure system to allow use all build steps as post build actions.
Step 4: In post build actions add another step “Flexible publish”.
Using this any build action can be used as post-build action. Add a HTTP Request action.
Provide Jenkins B webhook url in url field and save.
Yes. Configure your Jenkins nodes and label them, say masterand slave (Manage Jenkins -> Manage Nodes).
1) Configure Job A and specify that it can only run on master ("Restrict where this project can be run" and in the label field put master).
2) Configure Job B so that it is only triggered if Job A is successful:
"Post-build Actions" -> "Trigger only if build succeeds"
3) Pin Job B to slave similar to step 1.

Resources