Cancelling Jenkins Job from Command line (CLI) - jenkins

Just like 'build' command is used to start a job from Jenkins CLI, is there a way to cancel a long running job using CLI or any other command line technique. This I am trying in a windows machine and I am not looking to directly kill the process from task manager or shut down the jenkins.
Please suggest.

You can stop a Jenkins execution by calling JOB_URL/lastBuild/stop

Jenkins built-in Command Line tool does not provide a way to cancel/stop/abort a running build. But fortunately jenkins has provided other script API like Python API and Ruby API which have such ability.
Python API
class jenkinsapi.build.Build(url, buildno, job, depth=1)
stop()
Stops the build execution if it’s running :
return boolean True if succeded
False otherwise or the build is not running
API Link:https://jenkinsapi.readthedocs.org/en/latest/build.html
Ruby API
Class: JenkinsApi::Client::Job
#stop_build(job_name, build_number = 0) ⇒ Object (also: #stop, #abort)
Stops a running build of a job This method will stop the current/most recent build if no build number is specified.
API Link: http://www.rubydoc.info/gems/jenkins_api_client/1.4.2/JenkinsApi/Client/Job

This option assumes you have access to the Jenkins installation.
In Jenkins >2.195 you can do this using the Jenkins CLI jar:
# Export JENKINS_URL or add -s http://localhost[:port]/path/to/jenkins to the commands
export JENKINS_URL=http://localhost:8080/jenkins
# Get the name of the job you want to cancel
java -jar /path/to/jenkins-cli.jar -auth user:secret list-jobs
# Cancel the job
java -jar /path/to/jenkins-cli.jar -auth user:secret stop_builds <job_name>
# You can also disable the job, if needed
java -jar /path/to/jenkins-cli.jar -auth user:secret disable_job <job_name>

Related

How to build Jenkins job through command line by passing password parameter

I need to invoke a jenkins job via mac terminal using jenkins cli.
java -jar jenkins-cli.jar -s <jenkin_server> -auth username:token build myjobname -s -v -p param1=hello
This works perfectly
However, in the job if param1 is a password parameter, I am getting below error:
ERROR: CLI parameter submission is not supported for the class com.michelin.cio.hudson.plugins.passwordparam.PasswordParameterDefinition type. Please file a bug report for this
How do I invoke a jenkins job using cli, passing password parameters?
I see this issue being reported here but no solutions yet - https://issues.jenkins.io/browse/JENKINS-55925
If this is not possible, is there any other workaround?

Temporarily stop all scheduled jobs in Jenkins from running

I'm in the process of migrating Jenkins from one server to another. I've no issues with the migration process.
But sooner I start my new server the scheduled jobs start executing, which is proving to be dangerous. I need to make sure that everything is in place before activating the new server.
Is there any way to deter any of the jobs from executing while the new server is active?
execute an '/script':
Jenkins.instance.getAllItems(org.jenkinsci.plugins.workflow.job.WorkflowJob.class).each {i -> i.setDisabled(true); i.save() }
Jenkins.instance.getAllItems(hudson.model.AbstractProject.class).each {i -> i.setDisabled(true); i.save() }
Not my idea, from jenkins wiki
Setup a post-initialization script that puts Jenkins into quiet mode right after startup.
https://wiki.jenkins.io/display/JENKINS/Post-initialization+script
Try using https://wiki.jenkins.io/display/JENKINS/Exclusive+Execution+Plugin. You can keep jenkins in shutdown or Quiet mode for some time till your new instance is ready to function.
Use the Jenkins CLI
To prevent any jobs from being run, use quiet-down:
java -jar jenkins-cli.jar -s http://localhost:9090 -auth user:token quiet-down
To re-enable job scheduling:
java -jar jenkins-cli.jar -s http://localhost:9090 -auth user:token cancel-quiet-down
Scheduled jobs will be added to the queue during the quiet-down time, and will be run after canceling the quiet-down. If that's not what you want, you may use clear-queue before canceling the quiet-down.
There is a little downside: in the GUI, Jenkins will announce that it is preparing for shutdown, which wouldn't be true in this case. I find that acceptable, because we use it during backup at night when no one will read the announcement anyway. However, another option would be to take nodes offline, then online again using offline-node and online-node.
Quick Setup
Only if you haven't set up Jenkins CLI already:
You can obtain the Jenkins CLI from your Jenkins server by downloading it from <your_jenkins_url>/jnlpJars/jenkins-cli.jar
Instead of using your actual password to authenticate, obtain a token from <your_jenkins_url>/me/configure
For more details, refer to the Jenkins Handbook: Jenkins CLI
Referencie: https://xanderx.com/post/cancel-all-queued-jenkins-jobs/
Run this in Manage Jenkins > Script Console:
Jenkins.instance.queue.clear()

Jenkins pipeline job gets triggered as anonymous but not as an user/Admin

Jenkins Pipeline job doesn't trigger pipeline job using jenkins cli. When i run jenkins as anaonymous this works, but when i create a user/admin it fails.
I have a job A which has parameters and passes the same to Pipeline Job. This is a Master-slave setup. This is how i run:
sudo java -jar /home/user/jenkins-cli.jar -s $JENKINS_URL build pipeline_job -p parameter_Name="$parameter_Name" -p parameter_Name2="$parameter2_Name"
1.) I tried using options, "-auth" , "-username -password" but doesn't work.
errors:
No such command: -auth
No such command: -ssh
2.) Another option is paste the public key in SSH section http://jenkin_url/me/configure , but still it fails
error:
java.io.IOException: Invalid PEM structure, '-----BEGIN...' missing
Is there i am missing anything ?
I Found the solution,
1.) used SSH CLI.
In my case i was using master-slave environment, connection was made using SSH keys vice-versa. In order to trigger the build using Jenkins CLI, place the SSH keys both public & private and place them in http://jenkinsURL/user/username/configure
Here username= the one used to connect the nodes.
Trigger the job as below:
java -jar /home/username/jenkins-cli.jar -s $JENKINS_URL -i /home/username/.ssh/id_rsa build JOBNAME
Note: This is one way but cloudbees doesn't encourage this approach.
2.) There is new approach i.e., using API token authentication.
Go to http://jenkinsURL/user/username/configure
Copy the API token
trigger the build as below:
java -jar /home/username/jenkins-cli.jar -s $JENKINS_URL -auth username:apitoken /home/username/.ssh/id_rsa build JOBNAME
Note: For using API token option, download the latest jar file

Can Jenkins return 0 and 1 after test suites completed?

My query is related to Jenkins server.
I have made one API to hit the Jenkins server where Jenkins starts test suites.
My question is: can Jenkins server return 0 if any test case fail, and 1 otherwise?
The API URL is in the form
JENKINS_URL/job/Encore_Automation/build?token=TOKEN_NAME
By looking at Build Triggers / Trigger builds remotely (e.g., from scripts) it seems like this option only supports queuing a project and it does not let you retrieve results.
Jenkins REST API
After build has been triggered from REST API call, you could start making consecutive REST API calls to check it status.
Jenkins CLI
However Jenkins offers a jenkins-cli tool which let you not only to trigger the build but also to wait until its completion:
java -jar jenkins-cli.jar -s http://localhost:8080/ build JOB [-c] [-f] [-p] [-r N] [-s] [-v] [-w]
Starts a build, and optionally waits for a completion.
Aside from general scripting use, this command can be
used to invoke another job from within a build of one job.
With the -s option, this command changes the exit code based on
the outcome of the build (exit code 0 indicates a success)
and interrupting the command will interrupt the job.
With the -f option, this command changes the exit code based on
the outcome of the build (exit code 0 indicates a success)
however, unlike -s, interrupting the command will not interrupt
the job (exit code 125 indicates the command was interrupted).
With the -c option, a build will only run if there has been
an SCM change.
JOB : Name of the job to build
-c : Check for SCM changes before starting the build, and if there's no
change, exit without doing a build
-f : Follow the build progress. Like -s only interrupts are not passed
through to the build.
-p : Specify the build parameters in the key=value format.
-s : Wait until the completion/abortion of the command. Interrupts are passed
through to the build.
-v : Prints out the console output of the build. Use with -s
-w : Wait until the start of the command

Is there any way to start appium server silently?

Use case: I need to start appium server on CI Jenkins and run tests right after that. Tests don't start because appium server starting in debug mode and doesn't switch to another command.
So i have jenkins on Windows machine with the following build steps (as Windows batch command):
start /B node path_to_appium_server\appium.js --address 127.0.0.1 --port 4723
timeout 10
"path_to_tests_runner\vstest.console.exe" "path_to_dll\test.dll"
And in this case, my tests cannot started because jenkins terminate first process (with appium).
Basic issue was with permissions for '*.dll' file which contains tests and which cannot be ran with bat file without 'runas' command (which is waiting for password) from Jenkins.
So my Jenkins job contains 3 Build steps:
execute Windows batch command
start node path_to_appium_server\appium.js --address 127.0.0.1 --port 4723
Run unit tests with VSTest.console (to get this build option you need install VSTest Runner plugin)
specify path to dll and command line parameters
execute Windows batch command
taskkill /F /IM node.exe
Second step resolve permission issue for dll file.
It depends on how are you starting it. In most situations if on Jenkins you have 2 ways:
Start appium and tests in different build "shell execution" steps
If you want to do it in the same build step, just start it in a background with "START /B program".
Requirement
Installed Node.js 0.10 or greater.
At least an appium server instance installed via npm.
using javaclient 3.2.0
AppiumDriverLocalService service =AppiumDriverLocalService.buildDefaultService();
service.start();
service.stop();

Resources