Using Jenkins Cli to manage jobs and credentials

Jenkins has a built-in command line interface that allows users and administrators to access Jenkins from a script or shell environment. This can be convenient for scripting of routine tasks, bulk updates, troubleshooting, and more.

The command line interface can be accessed over SSH or with the Jenkins CLI client, a .jar file distributed with Jenkins.

Downloading the client

To download the client:

curl -LO http://remote.jenkins.ci:8080/jnlpJars/jenkins-cli.jar

Please note that if you are using a remote jenkins with username and password you need to authenticate as follows:

java -jar jenkins-cli.jar -auth username:password -s http://remote.jenkins.ci:8080/ <command>

# Example
java -jar jenkins-cli.jar -auth username:password -s http://remote.jenkins.ci:8080/ help

Add this -logger FINE to turn on logging.

Basic commands

# who-am-i - gets info about the current user's credentials and permissions
java -jar jenkins-cli.jar who-am-i

# list-jobs
java -jar jenkins-cli.jar list-jobs

# Download job called 'Build SanEclipse' to local xml file
java -jar jenkins-cli.jar get-job 'Build SanEclipse' > Build_San_Eclipse.xml

# create job from the xml file
cat Build_San_Eclipse.xml | java -jar jenkins-cli.jar  create-job 'Build San Eclipse'
java -jar jenkins-cli.jar create-job 'Build San Eclipse' < Build_San_Eclipse.xml

# list credentials
java -jar jenkins-cli.jar list-credentials system::system::jenkins

# list-credentials-providers
java -jar jenkins-cli.jar list-credentials-providers

# get-credentials-as-xml - github-token
java -jar jenkins-cli.jar get-credentials-as-xml system::system::jenkins _ github-token

# creating credentials from xml
java -jar jenkins-cli.jar create-credentials-by-xml  system::system::jenkins _ < github-token.xml

Job creation can also be done using ansible.

ansible-galaxy collection install community.general
ansible-galaxy collection install --ignore-certs community.general

The yaml file

- hosts: localhost
  connection: local
  gather_facts: False
  vars:
    jenkins_host: http://127.0.0.1:8080/
    username: <username>
    password: <password>
  tasks:
    - name: Create Build San Eclipse job
      community.general.jenkins_job:
        user: "{{ username }}"
        password: "{{ password }}"
        name: Build-San-Eclipse
        url: "{{ jenkins_host }}"
        config: "{{ lookup('file', 'Build_San_Eclipse.xml') }}"

This is how to use it

ansible-playbook create-san-eclipse-job.yaml -vvv
Last updated on Oct 14, 2024 11:46 +0300
comments powered by Disqus
Citizix Ltd
Built with Hugo
Theme Stack designed by Jimmy