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¶m2=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¶m_name1=value¶m_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¶m1_name=$PARAM1_VALUE¶m2_name=$PARAM2_VALUE"
Related
Important is separate Jenkins master.
I expecting something like
script { build job: 'https://second_instance_jenkins.mycompany.com/jobs/alt_build_job', parameters: [] }
However this does not work, I cannot connect to other master server, neither I know how to properly AUTH using this syntax. There are tons of examples how to invoke another job within same Jenkins, but not at separate independent Jenkins master!
Thanks.
You could enable the option Trigger builds remotely to trigger your job through the Jenkins API. Once you check the option, you will get the url you need to call in order to trigger the build
Use the following URL to trigger build remotely: JENKINS_URL/job/BranchDiffTests/build?token=TOKEN_NAME
Detailed instructions can be found here.
Once you have the job properly configured, you can send a GET request with the token as a parameter, and have the job executed remotely. Use Bash, Powershell, or whatever scripting language you use within your pipeline to create an API call to this endpoint, and once the call is made, the job should start running.
Found it.
I have to use Parameterized-Remote-Trigger as described here
https://www.jenkins.io/doc/pipeline/steps/Parameterized-Remote-Trigger/
I also going to post my working pipeline step. I wish there are more examples in manual.
steps {
triggerRemoteJob auth: CredentialsAuth(credentials: '7f89634523-1b42-440d-8053-aa3d523523441d'),
enhancedLogging: true,
job: 'Build/my-integration',
remoteJenkinsUrl: 'https://second_instance_jenkins.mycompany.com/',
useCrumbCache: true,
httpGetReadTimeout: 600,
httpPostReadTimeout: 600,
useJobInfoCache: true,
parameters: '''
PROJECT_NAME=core
BUILD_TYPE=Debug
PLATFORM=Linux
'''
}
I have a requirement where i need to trigger the build jobs remotely using curl command. I am unable to pass the branch/tag name as a parameter to trigger the build.
I used the below command :
& $CURLEXE -k -X POST $dst_job_url --user username:token --data-urlencode json='{"parameters": [{"name":"branch","branch":"branches"}]}'
If i run the above command it was triggers the build for the trunk ( default ).
You omitted the URL, so it's hard to be certain. Jenkins has two urls for building: "build" and "buildWithParameters". If you're not using buildWithParameters, switching to it will probably help.
See:
How to trigger Jenkins builds remotely and to pass parameters
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 ¶m=value
Executing upstream job called "A". On success of A executing test cases which is downstream project "B". But while sending mail from B we have to incorporate upstream project details (upstream project name, build no) in mail. So we can easily map / corelate the test run with respective upstream job.
In downstream project dashboard below details are displaying.
Started by upstream project Dev_RM_3.0_CI_Test build number 10
originally caused by:
I checked in https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project. but couldnt find anything to inherit in downstream.
Created sample job with below details to display the current job details.
echo $BUILD_NUMBER
echo $JOB_NAME
echo $BUILD_ID
But the output is
Building on master in workspace /var/lib/jenkins/workspace/env
[env] $ /bin/sh -xe /tmp/hudson970280339057643719.sh
+ echo 1
1
+ echo env
env
+ echo 1
1
Finished: SUCCESS
Any help to inherit upstream details in downstream job?
How to get current job details?
The message that you refer to your question "Started by upstream project "Chained/1-First" build number 34" for example, is available in the jenkins Cause.
Jenkins keeps the upstream build info in it's cause object. If your are using build DSL or Pipelines you may get it in groovy. Alternatively you can curl the job url and use jq to get the Cause
For example curl http://localhost:8080/job/Chained/job/2-Second/17/api/json
"_class": "org.jenkinsci.plugins.workflow.job.WorkflowRun",
"actions": [{
"_class": "hudson.model.CauseAction",
"causes": [{
"_class": "hudson.model.Cause$UpstreamCause",
"shortDescription": "Started by upstream project \"Chained/1-First\" build number 34",
"upstreamBuild": 34,
"upstreamProject": "Chained/1-First",
"upstreamUrl": "job/Chained/job/1-First/"
}]
}
Or from the pipeline for example:
node() {
stage('downstream') {
def upstream = currentBuild.rawBuild.getCause(hudson.model.Cause$UpstreamCause)
echo upstream?.shortDescription
}
}
You can get a bunch of information out of Cause, pending all the script approvals or a global shared step. You will get a null if a different cause triggers this build, eg commit, or user.
You can pass in the upstream variables via build parameters to the downstream job and then you can access them (in the downstream job) using things such as ${MyParameter1} and ${MyParameter2}.
You would need to:
Add build parameters to the downstream job. For example, a string parameter named "ParentJobName".
Add a post build "Trigger downstream parameterized builds on other projects" to the upstream job.
Add something like "Current Build parameters" or "Predefined parameters" to the #2 and pass in whatever you need. For example:
ParentJobName=${JOB_NAME}
Access the parameters as you would other build variables. e.g. ${ParentJobName}
You should be able to pass in the basic stuff that way. Anything more complicated than that and you will probably be better off using a plugin like Copy Artifacts Plugin to copy files or using the Jenkins API in a system groovy step to get/modify the upstream build, etc.
You can simply use params.variableName in your downstream job to retrieve the parameters passed from your upstream parameter job. Your downstream job need not necessarily be a parameterized job.
Extending #razboy answer:
this is good way if Cause cannot be whitelisted in sandbox. I forgot about Jenkins API and used current build console to look for string about trigger cause. You can try to fetch data from API as #razboy or get current console and grep it if you need simple stuff. Jenkins API is more flexible for more complex logic. To get API help,append /api to your build url: <jenkins_url>/job/<buildUrl>/<buildNumber>/api
def buildUrl = env.BUILD_URL
sh "wget $buildUrl -O currentConsole.txt"
statusCode = sh returnStatus: true,script: 'cat currentConsole.txt | grep -q "Started by upstream project"'
boolean startedByUpstream= statusCode==0
MeowRude's answer helped me. To repcap it, in upstream job:
build job: 'mail-test', parameters: [[$class: 'StringParameterValue', name: 'VERSION_NUMBER', value: '1.0.0.0']]
And in downstream job:
echo "${params.VERSION_NUMBER}"
You may have to have certain plugins installed, but
def causes = currentBuild.getBuildCauses()
will return an ArrayList of objects that will most likely provide the necessary details, for example upstreamProject for the full project name and upstreamBuild for the build number. Then you can correlate results between up- and downstream builds easily.
Source: link to pipeline-examples in razboy's comment above
I am new to Jenkins, and I'm not sure if this is possible, but I would like to set up a web interface where somebody could click "Start Job" and this will tell Jenkins to start a particular build job.
Does Jenkins have a webservice that would allow such a thing? If so, what would be a simple example?
Here is a link to the documentation: Jenkins Remote Access API.
Check out the Submitting jobs section.
In your job configuration you setup a token and then create a POST request to JENKINS_URL/job/JOBNAME/build?token=TOKEN. That's probably the most basic usage.
Jenkins has support for parameterized build as well.
So, if you want to pass parameters for configurable build generation, you can pass them by posting it while invoking Jenkins build request with http://YOURHOST/jenkins/job/PROJECTNAME/buildWithParameters.
Aha, I found it in the documentation. So simple:
http://YOURHOST/jenkins/job/PROJECTNAME/build
I needed to add parameters and I wanted to do it over https. It took me a while but the following worked for me:
curl --request POST --url 'https://HOST_NAME/job/JOB_NAME/buildWithParameters?token=TOKEN' --header 'cache-control: no-cache' --header 'content-type: application/x-www-form-urlencoded' --data 'name1=value1&name2=value2'
Use:
http://some server/job/myjob/buildWithParameters?token=TOKEN&PARAMETER=Value
You can take a look at this documentation: Parameterized Build
curl -H POST http://USERNAME:PASSWORD#JENKINS_HOST:PORT/job/JOB_NAME/build?token=YOUR_TOKEN
Set YOUR_TOKEN at job configuration -> build triggers -> Trigger builds remotely.
There is a good sample of using the above API from Python. The project is called Python Jenkins, and you may find it here: link
Jenkins has a documented REST API. You can make your little web service invoke it.
With curl if you have multiple arguments to pass like a token and a parameter you might have to quote on Linux shell:
curl -H POST "http://USERNAME:PASSWORD#JENKINS_HOST:PORT/job/JOB_NAME/build?token=YOUR_TOKEN&PARAMETER=VALUE"
Install Generic Webhook Trigger plugin.
Select generic webhook trigger in build trigger actions. Generate a random string and paste in token.
Now your job can be triggered with a http request to the following url.
http://JENKINS_URL/generic-webhook-trigger/invoke?token=TOKEN_VALUE
replace your jenkins url and token value