The web interface is for people, and the configuration as code from the previous lesson is for describing what Jenkins looks like. There is a third kind of interaction left: that of programs that ask Jenkins about its state or ask it to do something. A dashboard showing the latest build of each service, a script that triggers the CD pipeline for a version and waits until it reaches the approval, an incident tool that looks up which version was deployed and when... All of that is built on top of the Jenkins REST API and its CLI. You have already used them in passing: the remote trigger in 02-03, the linter in 03-06, the metrics in 05-05 and wfapi/describe in 07-02. In this lesson you will study them in depth: you will create the automation technical user with minimal permissions, query the API with tree and depth, trigger builds and follow the queue through to their result, write TecnoShop's pipeline-status.sh and trigger-cd.sh scripts and a Python example, see why creating jobs with config.xml is possible but not advisable, and tour the jenkins-cli.jar CLI, including the most dangerous command of all: groovy.
REST API, CLI and Script Console: When to Use Each One
| Tool | What it is | Use it for | Do not use it for |
|---|---|---|---|
| REST API | Almost any Jenkins page accepts /api/json; there are also endpoints to trigger, stop, create... |
Queries and integrations from any language (curl, Python, another tool) |
Configuring Jenkins (that is what JCasC and Job DSL are for, 08-03) |
CLI (jenkins-cli.jar) |
A Java client with administration and operations commands | Operations tasks from the terminal: trigger and wait, console, take nodes offline, safe restart, linter | Long-running integrations (the API is lighter and does not need Java) |
Script Console (and the groovy command) |
Running Groovy inside the controller | One-off troubleshooting that no other route allows | Anything repeatable: it ends up as unversioned configuration with full access |
All three use the same permissions as the interface: what a user cannot do on the web, they cannot do through the API either.
The automation Technical User and Its Token
Platform scripts should not use Laura's account: if the token leaked, the attacker would be an administrator, and the day Laura changes roles the scripts would stop working. Following the pattern of the metrics user from 05-05, TecnoShop creates an automation technical user with just what it needs:
| Need | Permission | Scope |
|---|---|---|
| See the Dashboard and the root API | Overall/Read, View/Read | Already granted by the user global role to all of authenticated |
| Read TecnoShop jobs and builds | Job/Read | `(orders |
Trigger the orders-api CD |
Job/Build | Only orders-delivery/orders-api-cd |
No Job/Configure, no Job/Cancel, no credentials, no Overall/Administer. And, above all, no permission to approve the production input: the submitter is still laura,production-approvers (07-03). A script can take a version to staging, never to production.
Since security already lives in casc/jenkins.yaml, adding the user is a PR to jenkins-config:
securityRealm:
local:
users:
# ... laura, diego, marta, metrics ...
- id: "automation"
name: "Technical user for the platform scripts"
password: "${AUTOMATION_PASSWORD}" # long and random; only used to create the token
authorizationStrategy:
roleBased:
roles:
items:
# ... existing roles ...
- name: "automation-read"
description: "Platform scripts: read TecnoShop jobs and builds"
pattern: "(orders|catalog)-.*"
permissions:
- "Job/Read"
entries:
- user: "automation"
- name: "automation-cd"
description: "Platform scripts: trigger the orders-api CD (never approve production)"
pattern: "orders-delivery/orders-api-cd"
permissions:
- "Job/Build"
entries:
- user: "automation"- Item roles add up:
automationreads everything belonging to TecnoShop and can trigger only one job. - The
orders-delivery/orders-api-cdpattern is matched against the full name; it does not includeorders-api-rollback. A rollback is triggered by a person.
The API Token
Log in as automation in a private window, open the user menu → Security (in earlier versions, Configure) → API Token → Add new Token, give it a name that says what it is for and since when (platform-scripts-2026-11) and click Generate. Copy the value right then: it will not be shown again.
Remember from 05-02 that:
- A token replaces the password for the API and the CLI, and it can be revoked without changing the password.
- With a token, POST requests do not need a CSRF crumb (03-06).
- If usage statistics are enabled (Manage Jenkins → Security → API Token), Jenkins shows when each token was last used and how many times: the way to spot forgotten tokens.
Where to Store It
The token is not written in scripts or on the command line (curl -u user:token shows up in the shell history and in the process list). For curl, use a netrc file with permissions 600:
mkdir -p ~/.config/tecnoshop && chmod 700 ~/.config/tecnoshop
cat > ~/.config/tecnoshop/jenkins.netrc <<'EOF'
machine localhost
login automation
password 11ff22ee33dd44cc55bb66aa77fake00
EOF
chmod 600 ~/.config/tecnoshop/jenkins.netrcmachineis the host name from the URL (localhostin the lab,jenkins.tecnoshop.localat TecnoShop).- The token in the example is fake. On a scripts server or in another CI system, the value would come from the secret manager and be written to the file when the process starts.
Every example in this lesson uses a small function:
export JENKINS_URL=http://localhost:8080
api() { curl --fail --silent --show-error --netrc-file ~/.config/tecnoshop/jenkins.netrc "$@"; }
api "$JENKINS_URL/whoAmI/api/json" | jq '{name, authenticated, authorities}'/whoAmI/api/json tells you who you are to Jenkins: the first check in any script.
The REST API: /api/json, tree and depth
Appending /api/json to almost any Jenkins URL returns that page's data as JSON:
| URL | Returns |
|---|---|
$JENKINS_URL/api/json |
The controller: root jobs, views, mode, executors... |
$JENKINS_URL/job/orders-api/api/json |
The multibranch job: its branches and PRs (as jobs) |
$JENKINS_URL/job/orders-api/job/main/api/json |
The main branch job: builds, last build, health... |
$JENKINS_URL/job/orders-api/job/main/lastBuild/api/json |
A build: number, result, duration, causes, artifacts, changes |
$JENKINS_URL/queue/api/json |
The queue |
$JENKINS_URL/computer/api/json |
The nodes and their executors |
The /api/xml variants (which support XPath filtering, with security restrictions) and /api/python (a Python literal) exist for compatibility; JSON is the natural choice today. And plain /api/ shows the API documentation for that page.
tree: Ask Only for What You Need
Without filters, the response includes everything Jenkins exports at that level. The tree parameter selects fields, with square brackets for nesting:
api --get --data-urlencode 'tree=jobs[name,url,color]' "$JENKINS_URL/api/json" | jq .
api --get --data-urlencode 'tree=builds[number,result,duration]{0,5}' \
"$JENKINS_URL/job/orders-api/job/main/api/json" | jq .jobs[name,url,color]: for each job, only those three fields.colorsums up the status (bluegreen,redred,yellowunstable,notbuilt,disabled, with the_animesuffix if a build is in progress).builds[...]{0,5}: the first five elements of the list (the most recent builds). Curly braces limit long lists.--get --data-urlencode:curlappends the parameter to the URL encoded; unencoded square brackets and braces cause errors in some clients.
depth: Watch the Depth
depth=1 (or 2...) expands nested objects that normally only appear as references. It is handy for exploring, but on a Jenkins with many jobs and builds, $JENKINS_URL/api/json?depth=2 can generate tens of MB and keep the controller busy for seconds or minutes. The rule: in scripts, always tree, never depth without a filter.
Reading the State of Jenkins
Useful operational queries:
# Latest build of main and its result
api --get --data-urlencode 'tree=number,result,building,duration,timestamp' \
"$JENKINS_URL/job/orders-api/job/main/lastBuild/api/json"
# What is in the queue and why it is waiting
api --get --data-urlencode 'tree=items[id,task[name],why,inQueueSince]' "$JENKINS_URL/queue/api/json" | jq .
# Nodes, whether they are connected and how many executors they have
api --get --data-urlencode 'tree=computer[displayName,offline,temporarilyOffline,numExecutors,idle]' \
"$JENKINS_URL/computer/api/json" | jq .
# A specific artifact from the last successful build (plain text)
api "$JENKINS_URL/job/orders-api/job/main/lastSuccessfulBuild/artifact/build-info.txt"- The permalinks from 02-01 (
lastBuild,lastSuccessfulBuild,lastFailedBuild...) work the same way in the API. - Branch names containing
/are encoded twice in the URL:feature/filter-orders-by-statusis the jobfeature%2Ffilter-orders-by-status, reached at/job/feature%252Ffilter-orders-by-status/. Use the URL returned by the API itself (url) instead of building it. - The
timestampfield is in milliseconds since 1970 (UTC);duration, in milliseconds.
Triggering Builds and Following the Queue
# Without parameters
api -X POST "$JENKINS_URL/job/orders-api/job/main/build"
# With parameters (the response includes the Location header)
api -X POST -D - -o /dev/null \
--data-urlencode 'VERSION=1.2.0' --data-urlencode 'SHA256=' \
"$JENKINS_URL/job/orders-delivery/job/orders-api-cd/buildWithParameters"Triggering a build does not create a build: it creates a queue item. Jenkins responds with 201 Created and a Location header pointing to that item:
sequenceDiagram
participant S as Script
participant J as Jenkins
S->>J: POST .../buildWithParameters
J-->>S: 201 + Location: /queue/item/1842/
loop Until there is a build
S->>J: GET /queue/item/1842/api/json
J-->>S: why: "Waiting for next available executor"
end
J-->>S: executable: {number: 43, url: .../orders-api-cd/43/}
loop Until it finishes (or waits for approval)
S->>J: GET .../43/wfapi/describe
J-->>S: status: IN_PROGRESS / PAUSED_PENDING_INPUT / SUCCESS / FAILED
end
The queue item has fields that change depending on its state:
| Field | Meaning |
|---|---|
why |
Why it is waiting: quiet period, no free executors, a lock... |
executable |
null while it waits; once it starts, the build's {number, url} |
cancelled |
true if someone canceled it in the queue |
Jenkins keeps the queue item for a few minutes after the build starts; a script that takes too long to ask may get a 404. That is why the polling loop must start right away.
Other actions (all POST, each with its own permission): .../43/stop (stop, Job/Cancel), .../disable and .../enable (Job/Configure), .../43/submitDescription (change the description, Run/Update).
Following a Build: consoleText, progressiveText and wfapi
B="$JENKINS_URL/job/orders-api/job/main/lastBuild"
api "$B/consoleText" | tail -n 30 # the full log, in plain text
api "$B/wfapi/describe" | jq -r '.status, (.stages[] | "\(.name): \(.status) \(.durationMillis/1000|floor) s")'consoleText: the whole log at once. For a finished build it is the simplest option.wfapi/describe: the Pipeline API (the one behind Stage View): the overall status and that of each stage with its duration. It is the way to find out which stage a pipeline is in, and itsPAUSED_PENDING_INPUTstatus means it is waiting on aninput.wfapi/runsgives the same for a job's latest builds, which you used in 07-02 to measure feedback time.
For a build in progress, logText/progressiveText returns the log starting from an offset, like a tail -f:
START=0
while :; do
api -D headers.txt "$B/logText/progressiveText?start=$START"
START=$(tr -d '\r' < headers.txt | sed -n 's/^[Xx]-[Tt]ext-[Ss]ize: //p')
tr -d '\r' < headers.txt | grep -qi '^x-more-data: true' || break
sleep 3
donestart=N: returns the text from byte N.X-Text-Sizeheader: the size read so far; it is thestartfor the next request.X-More-Data: trueheader: the build is still writing. When it disappears, the log is complete.
pipeline-status.sh: The Latest Build of Each Job
TecnoShop's first script, in jenkins-config/scripts/ (versioned, without credentials), reports the latest build of every job that automation can see:
#!/bin/sh
# pipeline-status.sh - Latest build of each TecnoShop job, from the Jenkins REST API.
# Usage: JENKINS_URL=http://localhost:8080 ./pipeline-status.sh
# Auth: netrc file in $JENKINS_NETRC (default ~/.config/tecnoshop/jenkins.netrc), permissions 600.
# Output: a sorted table; exit code 1 if any main branch is in FAILURE.
set -eu
JENKINS_URL="${JENKINS_URL:?Set JENKINS_URL}"
NETRC="${JENKINS_NETRC:-$HOME/.config/tecnoshop/jenkins.netrc}"
FIELDS='fullName,lastBuild[number,result,building,timestamp,duration]'
TREE="jobs[${FIELDS},jobs[${FIELDS},jobs[${FIELDS}]]]"
DATA=$(curl --fail --silent --show-error --netrc-file "$NETRC" \
--get --data-urlencode "tree=${TREE}" "${JENKINS_URL%/}/api/json")
echo "$DATA" | jq -r '
[.. | objects | select(.lastBuild? != null)]
| sort_by(.fullName)[]
| [ .fullName,
"#\(.lastBuild.number)",
(if .lastBuild.building then "RUNNING" else (.lastBuild.result // "-") end),
(.lastBuild.timestamp / 1000 | strflocaltime("%Y-%m-%d %H:%M")),
"\(.lastBuild.duration / 1000 | floor) s" ]
| @tsv' | column -t -s "$(printf '\t')"
BROKEN=$(echo "$DATA" | jq -r '[.. | objects | select(.lastBuild? != null)
| select((.fullName | endswith("/main")) and .lastBuild.result == "FAILURE") | .fullName] | join(", ")')
if [ -n "$BROKEN" ]; then
echo "WARNING: main is broken in: $BROKEN"
exit 1
fiPiece by piece:
- The three-level tree: the root has folders and multibranch jobs (
orders-delivery,orders-api,catalog-web); the second level, their jobs (orders-api/main,orders-delivery/orders-api-cd); a third level is requested in case nested folders appear. A single request, with only the fields needed. fullName: the full name including folders, the same one the roles andbuild job:use.[.. | objects | select(.lastBuild? != null)]: injq,..walks the whole document; it keeps the objects that have a last build (folders and multibranch jobs do not have one; jobs without builds have it set tonull).strflocaltime: converts the seconds into a date in the local time zone.column -t: aligns the output in columns.- The exit code: 1 if any
mainbranch is broken. That way the script also works as a periodic check (a cron job that sends an alert, or a dashboard).
Typical output:
catalog-web/main #88 SUCCESS 2026-11-28 09:12 412 s orders-api/PR-41 #3 RUNNING 2026-11-28 10:02 0 s orders-api/main #214 SUCCESS 2026-11-28 09:48 524 s orders-api/v1.2.0 #1 SUCCESS 2026-11-27 17:30 611 s orders-delivery/orders-api-cd #43 SUCCESS 2026-11-27 18:05 2940 s
trigger-cd.sh: Trigger the CD and Wait
The second script triggers orders-delivery/orders-api-cd for a version and follows it until it reaches the production approval (where a person takes over) or fails:
#!/bin/sh
# trigger-cd.sh - Triggers orders-delivery/orders-api-cd for a version and waits for the result.
# Usage: ./trigger-cd.sh 1.2.0 [SHA256]
# Output: 0 if the build finishes successfully or is left waiting for the production approval;
# 1 if it fails, is canceled or does not progress in time.
set -eu
VERSION="${1:?Usage: $0 VERSION [SHA256]}"
SHA256="${2:-}"
JENKINS_URL="${JENKINS_URL:?Set JENKINS_URL}"
NETRC="${JENKINS_NETRC:-$HOME/.config/tecnoshop/jenkins.netrc}"
JOB="${JENKINS_URL%/}/job/orders-delivery/job/orders-api-cd"
api() { curl --fail --silent --show-error --netrc-file "$NETRC" "$@"; }
echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || { echo "ERROR: VERSION must be X.Y.Z"; exit 1; }
# 1. Trigger: the response carries the queue item in the Location header
QUEUE_ITEM=$(api -X POST -D - -o /dev/null \
--data-urlencode "VERSION=$VERSION" --data-urlencode "SHA256=$SHA256" \
"$JOB/buildWithParameters" | tr -d '\r' | sed -n 's/^[Ll]ocation: //p')
[ -n "$QUEUE_ITEM" ] || { echo "ERROR: Jenkins did not return the queue item"; exit 1; }
echo "==> Queued: $QUEUE_ITEM"
# 2. Wait for the queue to assign a build (5 minutes at most)
BUILD=""
for i in $(seq 1 60); do
ITEM=$(api "${QUEUE_ITEM}api/json")
if [ "$(echo "$ITEM" | jq -r '.cancelled // false')" = "true" ]; then
echo "ERROR: the item was canceled in the queue"; exit 1
fi
BUILD=$(echo "$ITEM" | jq -r '.executable.url // empty')
[ -n "$BUILD" ] && break
echo " waiting: $(echo "$ITEM" | jq -r '.why // "-"')"
sleep 5
done
[ -n "$BUILD" ] || { echo "ERROR: the build did not start within 5 minutes"; exit 1; }
echo "==> Build: $BUILD"
# 3. Follow the pipeline (60 minutes at most)
LAST_STAGE=""
for i in $(seq 1 360); do
DESCRIBE=$(api "${BUILD}wfapi/describe")
STATUS=$(echo "$DESCRIBE" | jq -r '.status')
STAGE=$(echo "$DESCRIBE" | jq -r '[.stages[] | select(.status == "IN_PROGRESS")][0].name // empty')
if [ -n "$STAGE" ] && [ "$STAGE" != "$LAST_STAGE" ]; then
echo " stage: $STAGE"; LAST_STAGE="$STAGE"
fi
case "$STATUS" in
SUCCESS)
echo "==> orders-api $VERSION deployed to production"; exit 0 ;;
PAUSED_PENDING_INPUT)
echo "==> staging and acceptance OK. Production approval pending at ${BUILD}input/"
exit 0 ;;
FAILED|ABORTED|UNSTABLE|NOT_EXECUTED)
echo "ERROR: the build ended in $STATUS. Last lines of the log:"
api "${BUILD}consoleText" | tail -n 40
exit 1 ;;
*)
sleep 10 ;;
esac
done
echo "ERROR: the build is still running after 60 minutes: $BUILD"; exit 1The script's design decisions:
- Validate the version before triggering: the pipeline does it too (07-03), but it is better not to waste a build on a typo.
-D - -o /dev/null:curlwrites the headers to standard output and discards the body;sedextractsLocation.tr -d '\r'removes the carriage return that HTTP puts at the end of each header.${QUEUE_ITEM}api/json: theLocationURL ends in/, so appendingapi/jsonis enough.PAUSED_PENDING_INPUTis a success for the script: its job ends where the human decision begins. The script prints the link to theinputpage for whoever has to approve.- Explicit time limits: an automation script never waits "forever".
- The build is attributed to
automation: the build page will show Started by user automation, and so will Audit Trail. If you want to know which person requested it, add a parameter or use the build description.
The Same Flow in Python with requests
When the automation is part of a larger tool (a bot, a dashboard, another platform), Python is more convenient than the shell:
#!/usr/bin/env python3
"""trigger_build.py - Triggers a Jenkins job with parameters and waits for its result.
Usage: JENKINS_URL=... JENKINS_USER_ID=automation JENKINS_API_TOKEN=... \
python3 trigger_build.py orders-delivery/orders-api-cd VERSION=1.2.0 SHA256=
"""
import os
import sys
import time
from urllib.parse import quote
import requests
FINAL_STATES = {"SUCCESS", "FAILED", "ABORTED", "UNSTABLE", "NOT_EXECUTED"}
def job_url(base: str, full_name: str) -> str:
"""orders-delivery/orders-api-cd -> <base>/job/orders-delivery/job/orders-api-cd"""
return base + "".join(f"/job/{quote(part, safe='')}" for part in full_name.split("/"))
def wait_for_build(session: requests.Session, queue_url: str, max_wait: int = 300) -> str:
deadline = time.monotonic() + max_wait
while time.monotonic() < deadline:
item = session.get(f"{queue_url}api/json", timeout=15).json()
if item.get("cancelled"):
raise RuntimeError("the item was canceled in the queue")
if item.get("executable"):
return item["executable"]["url"]
print(f" waiting: {item.get('why')}")
time.sleep(5)
raise TimeoutError("the build did not start in time")
def wait_for_result(session: requests.Session, build_url: str, max_wait: int = 3600) -> str:
deadline = time.monotonic() + max_wait
while time.monotonic() < deadline:
status = session.get(f"{build_url}wfapi/describe", timeout=15).json()["status"]
if status in FINAL_STATES or status == "PAUSED_PENDING_INPUT":
return status
time.sleep(10)
raise TimeoutError("the build did not finish in time")
def main() -> int:
base = os.environ["JENKINS_URL"].rstrip("/")
job, *pairs = sys.argv[1:]
params = dict(pair.split("=", 1) for pair in pairs)
with requests.Session() as session:
session.auth = (os.environ["JENKINS_USER_ID"], os.environ["JENKINS_API_TOKEN"])
response = session.post(f"{job_url(base, job)}/buildWithParameters",
data=params, timeout=30)
response.raise_for_status()
build_url = wait_for_build(session, response.headers["Location"])
print(f"==> Build: {build_url}")
status = wait_for_result(session, build_url)
print(f"==> Status: {status}")
return 0 if status in {"SUCCESS", "PAUSED_PENDING_INPUT"} else 1
if __name__ == "__main__":
sys.exit(main())requests.Sessionwithauth: basic authentication with the user and token on every request, reusing the connection.quote(part, safe=''): encodes each folder or job name for the URL.data=params: the parameters go as a form in the POST body, just like--data-urlencode.raise_for_status(): a 403 (no permission) or 404 (nonexistent job) becomes a clear exception.- The credentials come from environment variables filled in by whoever runs the program (the secret manager, another CI system), never from the code. The
JENKINS_USER_IDandJENKINS_API_TOKENvariables are the same ones the CLI reads. - There are client libraries, such as
python-jenkins, that wrap these endpoints. For just a few of them,requestsis enough and adds no dependencies.
Creating and Modifying Jobs with config.xml, and Why Not to Do It
Each job is stored in Jenkins as a config.xml file, and the API lets you read and write it:
# Read (requires Job/ExtendedRead or Job/Configure)
api "$JENKINS_URL/job/lab-docker/config.xml" -o lab-docker.xml
# Create a new job from an XML file (Job/Create)
api -X POST -H 'Content-Type: application/xml' --data-binary @lab-docker.xml \
"$JENKINS_URL/createItem?name=lab-docker-2"
# Copy an existing job
api -X POST "$JENKINS_URL/createItem?name=lab-docker-3&mode=copy&from=lab-docker"
# Replace a job's configuration (Job/Configure)
api -X POST -H 'Content-Type: application/xml' --data-binary @lab-docker.xml \
"$JENKINS_URL/job/lab-docker-2/config.xml"
# Delete (Job/Delete)
api -X POST "$JENKINS_URL/job/lab-docker-3/doDelete"These calls need permissions that automation does not have (you will get a 403): try them with your own user, on lab jobs. They work, and in the past they were the usual way to "version" jobs. But:
Problem with config.xml |
The alternative |
|---|---|
| It is an internal format: it depends on plugin versions and changes when they are upgraded | Job DSL describes the intent and generates the right XML for your versions |
| Unreadable in a PR: hundreds of lines of XML for a one-option change | Ten lines of Job DSL |
| It can contain values encrypted with the key of that installation | JCasC with ${...} |
It competes with the seed job: the next run of seed-jobs overwrites whatever you uploaded |
A single owner for each job: jobs/ in jenkins-config |
Reasonable uses: troubleshooting (comparing the config.xml of two jobs), migrating old jobs to Job DSL (reading them to write their equivalent) or recovering a specific job from a backup (05-03).
The CLI: jenkins-cli.jar
The CLI is downloaded from your own Jenkins, so that the client version matches the controller's:
mkdir -p ~/.local/lib
curl -fsSL -o ~/.local/lib/jenkins-cli.jar "$JENKINS_URL/jnlpJars/jenkins-cli.jar"
printf 'automation:%s\n' '11ff22ee33dd44cc55bb66aa77fake00' > ~/.config/tecnoshop/jenkins-cli.auth
chmod 600 ~/.config/tecnoshop/jenkins-cli.auth
jcli() {
java -jar ~/.local/lib/jenkins-cli.jar -s "$JENKINS_URL" -webSocket \
-auth "@$HOME/.config/tecnoshop/jenkins-cli.auth" "$@"
}
jcli who-am-i
# The same function with Laura's personal token (a separate file, also 600), for administration only
jcli-laura() {
java -jar ~/.local/lib/jenkins-cli.jar -s "$JENKINS_URL" -webSocket \
-auth "@$HOME/.config/tecnoshop/jenkins-cli-laura.auth" "$@"
}-auth @file: readsuser:tokenfrom a file, without the token appearing on the command line. The alternative is theJENKINS_USER_IDandJENKINS_API_TOKENvariables from 03-06. (-auth user:tokenalso works, with the history problems already mentioned.)- The connection mode:
| Mode | Option | When |
|---|---|---|
| HTTP | -http (the default mode) |
Direct connection to the controller |
| WebSocket | -webSocket |
Through reverse proxies: the nginx from 05-02 already forwards WebSocket for the agents. TecnoShop always uses it |
| SSH | -ssh -user <user> |
Requires the Jenkins SSH server (section 14) |
- After every Jenkins upgrade, download
jenkins-cli.jaragain.
Useful CLI Commands
jcli help lists every command that your user can run, and jcli help <command> explains its options. The most useful ones:
| Command | What it does | Permission |
|---|---|---|
who-am-i, version |
Identity and controller version | Overall/Read |
list-jobs [folder] |
Lists the jobs (at the root or in a folder) | Overall/Read + Job/Read |
build <job> -p K=V -s -v |
Triggers a build; -s waits for it to finish and returns its result as the exit code, -v shows the log |
Job/Build |
console <job> [build] -f |
Shows a build's log; -f follows it while it is being written |
Job/Read |
declarative-linter < Jenkinsfile |
Validates a declarative Jenkinsfile (03-06) |
Overall/Read |
offline-node <node> -m "reason", online-node <node> |
Takes a node offline or brings it back (05-01) | Agent/Disconnect, Agent/Connect |
quiet-down, cancel-quiet-down |
Equivalent to Prepare for Shutdown and to canceling it (05-04) | Overall/Manage or Administer |
safe-restart |
Restarts once there are no builds in progress | Overall/Administer |
reload-jcasc-configuration |
Applies JCasC again (08-03) | Overall/Administer |
reload-configuration |
Rereads all the configuration from disk, discarding what is in memory | Overall/Administer |
list-plugins, install-plugin |
Lists and installs plugins | Overall/Read, Overall/Administer |
get-job, create-job, update-job |
config.xml through the CLI, with the same caveats as section 10 |
Job/ExtendedRead, Job/Create, Job/Configure |
groovy, groovysh |
Run Groovy on the controller (section 13) | Overall/Administer |
Examples with automation and with Laura's account:
jcli list-jobs orders-delivery
jcli build orders-delivery/orders-api-cd -p VERSION=1.2.0 -p SHA256= -w # -w: returns as soon as it starts
jcli console orders-delivery/orders-api-cd -f # and follows its log
# With Laura's (administrator) account, during a maintenance window:
jcli-laura offline-node linux-agent-01 -m "Upgrading tecnoshop/linux-agent to version 3"
jcli-laura quiet-down
jcli-laura safe-restartbuild ... -sis tempting for the CD, but it would also wait through the 24 hours of the approval. For the CD,trigger-cd.shis more precise.install-pluginexists, but at TecnoShop plugins change only throughplugins.txt(05-04): use it, at most, onjenkins-test.reload-configurationis an emergency command: if someone has changed files inJENKINS_HOMEby hand, it reloads them; any change made in the interface and not saved is lost. Do not confuse it withreload-jcasc-configuration.
groovy: The Script Console from a Distance
cat > last-result.groovy <<'EOF'
// Read-only: last result of each job that has builds
Jenkins.instance.getAllItems(Job).each { job ->
def last = job.lastBuild
if (last) {
println "${job.fullName}\t#${last.number}\t${last.result ?: 'RUNNING'}"
}
}
EOF
jcli-laura groovy = < last-result.groovygroovy =reads the script from standard input and runs it inside the controller, just like the Script Console from 05-02. There is also thePOST /scriptTextREST endpoint.- This example only reads, but the same mechanism can read and decrypt every credential, read and write any file in
JENKINS_HOME, run processes on the controller machine or change the security settings. That is why it requires Overall/Administer.
TecnoShop's rules for remote Groovy:
- Platform team only, and only with their personal accounts (never with a technical user).
- Only for troubleshooting or for emergencies that have no other route; anything repeatable becomes JCasC, Job DSL or a library step.
- The scripts are kept in
jenkins-config/scripts/groovy/, reviewed, and run from there. - Audit Trail records the execution; whoever runs it notes the reason in the team channel.
The CLI over SSH
Jenkins can act as an SSH server for the CLI: in Manage Jenkins → Security → SSH Server, you set a port (for example, 2222), each user registers their public key in their profile (SSH Public Keys), and you run:
It needs neither Java nor the jar download, but it opens one more port and requires managing keys per user. TecnoShop keeps it disabled: jenkins-cli.jar over WebSocket covers the same needs through the existing HTTPS proxy.
Automation Security
| Practice | How TecnoShop applies it |
|---|---|
| Technical users with least privilege | metrics (metrics only) and automation (read and trigger the CD); neither is an administrator |
| One named token per use | platform-scripts-2026-11, prometheus; revoking one does not break the others |
| Rotation | Every three months, or when someone leaves the platform team: create the new one, roll it out, revoke the old one. Depending on the version, Jenkins may not expire tokens on its own; rotation is your responsibility |
| Never in versioned files | Not in scripts, not in the Jenkinsfile, not in the documentation; gitleaks (07-05) keeps watch |
| Never on the command line | netrc or -auth @file with permissions 600; environment variables filled in by a secret manager |
| No legacy tokens | Manage Jenkins → Security → API Token: no legacy tokens and no automatic generation for new users |
| Review usage | Token usage statistics and Audit Trail; a token unused for 90 days is revoked |
| Remote Groovy = full access | Platform team only, reviewed scripts, every execution logged |
| HTTPS | Outside the lab, the API only over https:// (the proxy from 05-02): over HTTP, the token travels in clear text |
| From pipelines, no API | To trigger jobs from a pipeline, use the build step (07-02), not curl with a token stored in a credential |
Common Mistakes and Tips
403 No valid crumb was included in the request: you are authenticating with a password (or not at all) on a POST. Use an API token.403with a correct token: a permission is missing.whoAmI/api/jsonshows who you are; compare it with the roles. The error usually says which permission is missing (automation is missing the Job/Build permission).404on/queue/item/N/: the item left the queue a while ago. Query the queue as soon as you trigger the build.- Building URLs by hand for branches with
/:feature/xisfeature%252Fxin the URL. Use theurlfield from the API. depth=2in a periodic script: it keeps the controller busy every time it runs. Usetree.- The CD script that waits indefinitely: always with a time limit, and treating
PAUSED_PENDING_INPUTas a state of its own. - Copying a
config.xmlbetween two Jenkins instances with different plugin versions: the job may load only partially or with unexpected default values. Go through Job DSL. - Tip:
$JENKINS_URL/<any page>/api/documents that page's data and actions. For your version, it is more reliable than any example on the internet.
Exercises
Exercise 1. Create the automation user and its roles (with JCasC or, if you are not using it yet, through the interface), its token and the netrc file. Check with curl that it can read orders-api/main/lastBuild, that it can trigger orders-delivery/orders-api-cd, and that it can not trigger orders-delivery/orders-api-rollback or read jenkins-config. Note the HTTP codes for each case.
Exercise 2. Extend pipeline-status.sh with a -r option that shows, for each job, the stage in which its latest build failed if the result is FAILURE (using wfapi/describe).
Exercise 3. Write a four-command CLI procedure for the maintenance window from 05-04: warn people, prevent new builds, wait for the running ones to finish and restart. Which account should run it, and why not automation?
Solutions
Solution 1. Reading the latest build of orders-api/main: 200 with the JSON. POST .../orders-api-cd/buildWithParameters: 201 with Location. POST .../orders-api-rollback/buildWithParameters: 403, because the automation-cd pattern is exactly orders-delivery/orders-api-cd (it can see the rollback, through automation-read, but not trigger it). GET /job/jenkins-config/api/json: 404, not 403: without Job/Read or Job/Discover, Jenkins does not reveal that the job exists. If you get a 401 in any case, the netrc is not being read (check machine and the file's permissions).
Solution 2. After reading DATA, if -r was passed, go through the jobs with FAILURE and query their wfapi/describe:
if [ "${1:-}" = "-r" ]; then
echo "$DATA" | jq -r '.. | objects | select(.lastBuild?.result == "FAILURE") | .fullName' |
while read -r NAME; do
JOB_PATH=$(echo "$NAME" | sed 's|/|/job/|g')
STAGE=$(curl --fail --silent --netrc-file "$NETRC" \
"${JENKINS_URL%/}/job/$JOB_PATH/lastBuild/wfapi/describe" |
jq -r '[.stages[] | select(.status == "FAILED")][0].name // "(no stages: not a pipeline)"')
echo "$NAME → failed in: $STAGE"
done
fised 's|/|/job/|g' turns orders-api/main into orders-api/job/main. For branches with / in the name, the name would have to be encoded (better still, also request url in the tree and use it). Freestyle jobs have no wfapi: the // "..." covers that case.
Solution 3.
jcli-laura quiet-down # 1. Prepare for Shutdown: no new builds start
# 2. Notice in #ci-orders and #ci-catalog (with the system message or Slack)
jcli-laura quiet-down -block -timeout 1800000 # 3. Wait (30 min max) for the running builds to finish
jcli-laura safe-restart # 4. Restart without interrupting buildsquiet-down -block waits until no build is left running (with -timeout in milliseconds; check the options with jcli help quiet-down on your version). Laura should run it with her own account: quiet-down and safe-restart require administration permissions, and granting them to automation would turn a token stored on a scripts server into a key to stop all of Jenkins. Maintenance operations are infrequent, are done with a person at the keyboard and are recorded under that person's name.
Conclusion
You can now automate Jenkins from the outside, with good judgment. The automation technical user reads TecnoShop's jobs and can only trigger orders-delivery/orders-api-cd, never approve production, with a named token stored in a netrc file with permissions 600. You know how to query any page with /api/json, filtering with tree (and why to avoid depth); read the queue, the nodes and the artifacts; trigger builds with /build and /buildWithParameters; follow the queue item from the Location header through to executable.url; and follow the build with consoleText, logText/progressiveText and wfapi/describe. pipeline-status.sh summarizes the latest build of each job and warns if main is broken; trigger-cd.sh and its Python equivalent take a version up to the production approval and stop there. You know createItem and config.xml, and why TecnoShop leaves jobs to Job DSL. With jenkins-cli.jar over WebSocket and -auth @file you operate Jenkins from the terminal, and you know that groovy is the Script Console under another name. With Jenkins described as code and automatable, what remains is the question that comes up when everything works and more and more teams use it: what happens when the queue grows, or the controller falls short or goes down. You will answer it in Scaling Jenkins.
