Create a Service Account to access Jenkins with cli
- Step 1: Create a service user account in the StackTrack Identity Service admin console.
- Step 2: Log in to Jenkins with the service account and create an API Token.
- Step 3: Create a role in Jenkins for the service account with the least privileges principle. Manage Jenkins -> Manage Roles.
- Step 4: Assign the new role created in Step 3 to the service account via the assign role menu in Jenkins. Assign Role Link.
- Step 5: Execute the Jenkins cli with the API Token and service user login information.
A link has been kindly shared of a resource that wraps the Jenkins CLI in a shell script. Here is a link to a gist which makes this process easier.
#!/bin/bash
# Jenkins-cli wrapper see. https://www.jenkins.io/doc/book/managing/cli/
#
# .installation:
# curl -o ~/bin/jcli-wrapper
# chmod +x ~/bin/jcli-wrapper
#
# .usage:
# jcli-wrapper Jenins-URL file-with-credentilas
#
# .example:
# jcli-wrapper https://jenkins.example.com $(realpath ~/.rcjenkins/jenkins) list-jobs
#
# .tip:
# you can create own wrapper with pre-defined values like:
# #file: ~/bin/jcli
# #!/bin/bash
# jcli-wrapper https://jenkins.example.com $(realpath ~/.rcjenkins/jenkins) $@
#
# .note:
# content of ~/.rcjenkins/jenkins is:
# {username}:{token|password}
# user:123456
jenkins_host=$1
shift 1
passwd_file=$1
shift 1
if [ ! -f ~/bin/jenkins-cli.jar ]
then
mkdir -p ~/bin
curl -o ~/bin/jenkins-cli.jar $jenkins_host/jnlpJars/jenkins-cli.jar
fi
java -jar ~/bin/jenkins-cli.jar -s ${jenkins_host} -webSocket -auth @${passwd_file} $@
Updated on: 01/11/2025
Thank you!