Freestyle Jobs, Parameters, and Triggers
Build a real project as a Jenkins freestyle job: git checkout, shell steps, parameters, environment variables, cron and SCM triggers, artifacts, fingerprints and discarders.
By The Dark DebuggerUpdated 30 min read
This article builds a real project as a freestyle job: check it out from git, run its tests in a shell step, take parameters, react to triggers, archive and fingerprint the package, and keep the build history under control. You should have a controller running and the jcli CLI function from Installing Jenkins set up, and know the vocabulary from What Jenkins Is and How It Works. Shell steps are plain shell scripts, so Your First Scripts is useful background.
Why freestyle jobs are still worth learning
Pipelines are the modern way to build software in Jenkins, and the next article moves there. Freestyle jobs still matter for three reasons. Most long-lived Jenkins installations are full of them, and someone has to maintain them. Small operational tasks (a nightly report, a cleanup script with a "run now" button) are often clearer as a freestyle job than as a pipeline. And every Pipeline feature has a freestyle ancestor: once you have seen a parameter turn into an environment variable here, you know what params and env are doing later.
The project: logstats
Everything in this series builds one small Python tool, logstats, which summarises an nginx access log. It uses only the standard library, so any agent with python3 can build it. The repository looks like this:
cd ~/logstats
tree -a -I .git.
├── .gitignore
├── Jenkinsfile
├── logstats.py
├── sample
│ └── access.log
└── tests
├── junit_runner.py
└── test_logstats.py
3 directories, 6 filestests/junit_runner.py runs the unit tests and writes a JUnit XML report, the format Jenkins understands (with pytest installed, pytest --junitxml=FILE does the same). Before involving Jenkins at all, make sure the project builds by hand:
python3 logstats.py sample/access.log
python3 tests/junit_runner.py reports/junit.xmlrequests: 10 unparsed: 1
by class: 2xx=6 3xx=1 4xx=1 5xx=2
5xx rate: 20.0%
3 /api/orders
3 /api/checkout
1 /api/orders/1042
test_parses_a_combined_log_line (test_logstats.ParseTests.test_parses_a_combined_log_line) ... ok
test_returns_none_for_garbage (test_logstats.ParseTests.test_returns_none_for_garbage) ... ok
test_counts_status_classes (test_logstats.SummariseTests.test_counts_status_classes) ... ok
test_empty_input (test_logstats.SummariseTests.test_empty_input) ... ok
test_error_rate_is_a_percentage (test_logstats.SummariseTests.test_error_rate_is_a_percentage) ... ok
----------------------------------------------------------------------
Ran 5 tests in 0.001s
OKIf a project doesn't build from a clean checkout on the command line, it won't build in Jenkins either. Jenkins only runs your commands; it doesn't fix them.
Creating a freestyle job
In the web UI: New Item, type a name, choose Freestyle project, click OK. The configuration page has six sections, in this order: General (description, parameters, build discarder), Source Code Management, Triggers, Environment, Build Steps and Post-build Actions. Each setting you choose there is saved to the job's config.xml.
That file is also the fastest way to create a job without clicking. I created every job in this article from a config.xml with the CLI, and you can dump any job's XML back out the same way:
jcli create-job logstats-freestyle < logstats-freestyle.xml
jcli get-job logstats-freestyle | head -3<?xml version="1.1" encoding="UTF-8"?>
<project>
<description>Tests and packages logstats from the local git repository.</description>get-job followed by create-job is also how you copy a job between controllers. The XML snippets below are what Jenkins stored for each UI setting, so you can map one onto the other.
Checking out source code from git
Under Source Code Management, choose Git, set the Repository URL and the Branch Specifier. Jenkins stores it like this:
<scm class="hudson.plugins.git.GitSCM" plugin="git@5.11.0">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<url>file:///home/sid/logstats</url>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
<branches>
<hudson.plugins.git.BranchSpec>
<name>*/main</name>
</hudson.plugins.git.BranchSpec>
</branches>
<doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
<submoduleCfg class="empty-list"/>
<extensions/>
</scm>In real life the URL is an https:// or ssh:// address and you pick a credential next to it (Credentials and Secrets covers that). I used a file:// URL to a repository on the same machine so every example runs without a git server. The git plugin blocks local checkouts by default, for good reason: a job could otherwise read any repository on the controller. My lab controller was started with -Dhudson.plugins.git.GitSCM.ALLOW_LOCAL_CHECKOUT=true to allow it. Don't set that on a shared controller.
*/main means "the branch called main on any remote". Here is the checkout part of the first build:
Started logstats-freestyle #1
Started from command line by admin
Running as SYSTEM
Building in workspace /home/sid/.jenkins/workspace/logstats-freestyle
The recommended git tool is: NONE
No credentials specified
Cloning the remote Git repository
Cloning repository file:///home/sid/logstats
> git init /home/sid/.jenkins/workspace/logstats-freestyle # timeout=10
Fetching upstream changes from file:///home/sid/logstats
> git --version # timeout=10
> git --version # 'git version 2.43.0'
> git fetch --tags --force --progress -- file:///home/sid/logstats +refs/heads/*:refs/remotes/origin/* # timeout=10
> git config remote.origin.url file:///home/sid/logstats # timeout=10
> git config --add remote.origin.fetch +refs/heads/*:refs/remotes/origin/* # timeout=10
Avoid second fetch
> git rev-parse refs/remotes/origin/main^{commit} # timeout=10
Checking out Revision 65744506da9ad3361351ebcca1ce2d1243508d9c (refs/remotes/origin/main)
> git config core.sparsecheckout # timeout=10
> git checkout -f 65744506da9ad3361351ebcca1ce2d1243508d9c # timeout=10
Commit message: "Add Jenkinsfile"
First time build. Skipping changelog.Two things to notice. Jenkins checks out a specific commit (detached HEAD), not the branch, so the build is pinned to exactly what it tested. And every git command it ran is in the log, which makes checkout problems easy to reproduce by hand.
Shell build steps
Under Build Steps, Add build step → Execute shell gives you a text box for a shell script. Here is the one this job uses:
#!/bin/bash -e
echo "Commit ${GIT_COMMIT:0:7} of ${GIT_BRANCH}, target ${TARGET_ENV}"
if [ "$RUN_TESTS" = true ]; then
python3 tests/junit_runner.py reports/junit.xml
else
echo "RUN_TESTS=false: skipping unit tests"
fi
python3 logstats.py "$LOG_FILE" | tee report.txt
mkdir -p dist
echo "$BUILD_NUMBER $GIT_COMMIT" > VERSION
tar czf "dist/logstats-${BUILD_NUMBER}.tar.gz" logstats.py VERSION
ls -l distJenkins writes the script to a temporary file and runs it. The first line decides how. Without a #! line, Jenkins runs /bin/sh -xe, which on Debian and Ubuntu is dash: -x echoes each command with a + and -e stops at the first failure. With #!/bin/bash -e, Jenkins runs Bash instead, so ${GIT_COMMIT:0:7} (a Bash-only substring) works, and -x is gone because you didn't ask for it. Compare the two invocation lines from real builds:
[hello-freestyle] $ /bin/sh -xe /tmp/jenkins5975289855519858437.sh
[logstats-freestyle] $ /bin/bash -e /tmp/jenkins12730679133292440001.shThe step fails the build if the script exits non-zero. Here is the rest of build #1:
[logstats-freestyle] $ /bin/bash -e /tmp/jenkins12730679133292440001.sh
Commit 6574450 of origin/main, target staging
test_parses_a_combined_log_line (test_logstats.ParseTests.test_parses_a_combined_log_line) ... ok
test_returns_none_for_garbage (test_logstats.ParseTests.test_returns_none_for_garbage) ... ok
test_counts_status_classes (test_logstats.SummariseTests.test_counts_status_classes) ... ok
test_empty_input (test_logstats.SummariseTests.test_empty_input) ... ok
test_error_rate_is_a_percentage (test_logstats.SummariseTests.test_error_rate_is_a_percentage) ... ok
----------------------------------------------------------------------
Ran 5 tests in 0.001s
OK
requests: 10 unparsed: 1
by class: 2xx=6 3xx=1 4xx=1 5xx=2
5xx rate: 20.0%
3 /api/orders
3 /api/checkout
1 /api/orders/1042
total 4
-rw-r--r-- 1 sid sid 959 Nov 9 21:46 logstats-1.tar.gz
Archiving artifacts
Recording fingerprints
Recording test results
[Checks API] No suitable checks publisher found.
Triggering a new build of deploy-staging
Finished: SUCCESS
Completed logstats-freestyle #1 : SUCCESS(This first build ran before I added the VERSION line, so its tarball holds only logstats.py.) The lines after ls -l dist come from the post-build actions and the downstream trigger, which we'll get to. [Checks API] No suitable checks publisher found. is harmless: it means no GitHub or GitLab "checks" integration is configured to receive the test results.
My advice for shell steps: keep them short and put real logic in a script in the repository (./ci/build.sh). A script in the repo is versioned, reviewable and runnable on a laptop; a 60-line text box inside Jenkins is none of those.
Parameters
Tick This project is parameterized under General to make the build ask for input. The three everyday types are a string, a choice and a boolean:
<hudson.model.ParametersDefinitionProperty>
<parameterDefinitions>
<hudson.model.StringParameterDefinition>
<name>LOG_FILE</name>
<description>Access log to summarise, relative to the workspace</description>
<defaultValue>sample/access.log</defaultValue>
<trim>true</trim>
</hudson.model.StringParameterDefinition>
<hudson.model.ChoiceParameterDefinition>
<name>TARGET_ENV</name>
<description>Where this package is meant to go. The first choice is the default.</description>
<choices class="java.util.Arrays$ArrayList">
<a class="string-array">
<string>staging</string>
<string>production</string>
</a>
</choices>
</hudson.model.ChoiceParameterDefinition>
<hudson.model.BooleanParameterDefinition>
<name>RUN_TESTS</name>
<description>Run the unit tests before packaging</description>
<defaultValue>true</defaultValue>
</hudson.model.BooleanParameterDefinition>
</parameterDefinitions>
</hudson.model.ParametersDefinitionProperty>In the UI, Build Now becomes Build with Parameters and shows a form. From the CLI, pass -p NAME=value. Inside the build, every parameter becomes an environment variable with the same name, which is why the shell step can say $TARGET_ENV and $RUN_TESTS:
jcli build logstats-freestyle -s -v -p TARGET_ENV=production -p RUN_TESTS=falseStarted logstats-freestyle #2
Started from command line by admin
[…]
[logstats-freestyle] $ /bin/bash -e /tmp/jenkins7802416450286498268.sh
Commit 6574450 of origin/main, target production
RUN_TESTS=false: skipping unit tests
requests: 10 unparsed: 1
by class: 2xx=6 3xx=1 4xx=1 5xx=2
5xx rate: 20.0%
3 /api/orders
3 /api/checkout
1 /api/orders/1042
total 8
-rw-r--r-- 1 sid sid 959 Nov 9 21:46 logstats-1.tar.gz
-rw-r--r-- 1 sid sid 959 Nov 9 21:47 logstats-2.tar.gz
Archiving artifacts
Recording fingerprints
Recording test results
[Checks API] No suitable checks publisher found.
Triggering a new build of deploy-staging
Finished: SUCCESS
Completed logstats-freestyle #2 : SUCCESSLook at that ls -l dist: build #2 has two tarballs, one of them left over from build #1. That is a real bug, and it breaks the downstream job; it's the first entry in Common mistakes.
Jenkins validates parameters before queueing anything, which turns typos into clear errors instead of strange builds:
jcli build logstats-freestyle -s -p TARGET_ENV=qa
jcli build logstats-freestyle -s -p TARGTE_ENV=production
ERROR: Illegal choice for parameter TARGET_ENV: qa
ERROR: 'TARGTE_ENV' is not a valid parameter. Did you mean TARGET_ENV?
[…]The values each build received are recorded and visible through the API. Note the types: the boolean is a real boolean in JSON, but in the shell it is the string false, which is why the script compares with = true:
curl -g -sS -u "admin:$JENKINS_API_TOKEN" "http://localhost:8090/job/logstats-freestyle/lastBuild/api/json?tree=number,actions[parameters[name,value]]" | jq -c '[.actions[]?.parameters? // empty | .[]]'[{"_class":"hudson.model.StringParameterValue","name":"TARGET_ENV","value":"production"},{"_class":"hudson.model.BooleanParameterValue","name":"RUN_TESTS","value":false},{"_class":"hudson.model.StringParameterValue","name":"LOG_FILE","value":"sample/access.log"}]Never pass passwords as string parameters: they are stored in plain text in build.xml and shown on the build page. Use credentials instead.
Built-in environment variables
Jenkins also sets a batch of variables describing the build itself. A job that just prints them is the quickest reference for your own controller:
env | sort | grep -E '^(BUILD|JOB|JENKINS|NODE|EXECUTOR|WORKSPACE|GIT|TARGET)'BUILD_DISPLAY_NAME=#1
BUILD_ID=1
BUILD_NUMBER=1
BUILD_TAG=jenkins-env-vars-1
BUILD_URL=http://localhost:8090/job/env-vars/1/
EXECUTOR_NUMBER=0
GIT_BRANCH=origin/main
GIT_COMMIT=65744506da9ad3361351ebcca1ce2d1243508d9c
GIT_URL=file:///home/sid/logstats
JENKINS_HOME=/home/sid/.jenkins
JENKINS_SERVER_COOKIE=6f8956ad49bed559
JENKINS_URL=http://localhost:8090/
JOB_BASE_NAME=env-vars
JOB_DISPLAY_URL=http://localhost:8090/job/env-vars/display/redirect
JOB_NAME=env-vars
JOB_URL=http://localhost:8090/job/env-vars/
NODE_LABELS=built-in
NODE_NAME=built-in
TARGET_ENV=production
WORKSPACE=/home/sid/.jenkins/workspace/env-vars
WORKSPACE_TMP=/home/sid/.jenkins/workspace/env-vars@tmpThat ran as the build step of a job with git checkout and a TARGET_ENV choice parameter, built with -p TARGET_ENV=production. The ones you will use most:
| Variable | Typical use |
|---|---|
BUILD_NUMBER | Version numbers and artifact names (logstats-42.tar.gz) |
BUILD_TAG | A unique string per build, for temporary resource names (jenkins-<job>-<number>) |
BUILD_URL | Links in notifications ("see $BUILD_URL console") |
JOB_NAME | The full name, including folders (team/app/build); JOB_BASE_NAME drops the folders |
WORKSPACE | Absolute path of the build's working directory |
NODE_NAME, EXECUTOR_NUMBER | Which agent and slot ran the build, handy when only one agent misbehaves |
GIT_COMMIT, GIT_BRANCH, GIT_URL | Set by the git plugin after checkout |
BUILD_URL and JOB_URL are only set if the Jenkins URL is configured, one more reason to set it during installation.
Triggers
Without a trigger, a job runs only when someone clicks Build Now or calls the API. The Triggers section offers four common options.
Build periodically
Build periodically takes a cron-style schedule with five fields: minute, hour, day of month, month, day of week. Jenkins adds one important symbol, H, which means "a fixed value derived from a hash of the job name". H 2 * * * means "once a day, at some minute during the 02:00 hour", and that minute is different for every job. Without H, every nightly job on the controller starts at exactly 0 2 * * * and they all fight for executors.
The UI validates a schedule as you type and tells you when it would run. That check is a plain HTTP endpoint, so you can call it from the shell:
for spec in 'H 2 * * *' 'H/15 * * * *' '* * * * *' '@daily'; do
enc=$(jq -rn --arg s "$spec" '$s|@uri'); echo "--- [$spec]"
curl -sS -u "admin:$JENKINS_API_TOKEN" -X POST "http://localhost:8090/descriptorByName/hudson.triggers.TimerTrigger/checkSpec?value=$enc"; echo
done--- [H 2 * * *]
<div class="ok">Would last have run at Monday, November 9, 2026, 2:00:00 AM Eastern Standard Time; would next run at Tuesday, November 10, 2026, 2:00:00 AM Eastern Standard Time.</div>
--- [H/15 * * * *]
<div class="ok">Would last have run at Monday, November 9, 2026, 9:45:00 PM Eastern Standard Time; would next run at Monday, November 9, 2026, 10:00:00 PM Eastern Standard Time.</div>
--- [* * * * *]
<ul style='list-style-type: none; padding-left: 0; margin: 0'><li><div class="warning">Do you really mean "every minute" when you say "* * * * *"? Perhaps you meant "H * * * *" to poll once per hour</div></li><li><div class="ok">Would last have run at Monday, November 9, 2026, 9:50:00 PM Eastern Standard Time; would next run at Monday, November 9, 2026, 9:51:00 PM Eastern Standard Time.</div></li></ul>
--- [@daily]
<div class="ok">Would last have run at Monday, November 9, 2026, 12:00:00 AM Eastern Standard Time; would next run at Tuesday, November 10, 2026, 12:00:00 AM Eastern Standard Time.</div>Called this way, with no job attached, H hashes to 0, so the times land on the hour. On a job's configuration page the same check uses the job's name and shows the real minute. A few more rules:
- Times are in the controller's time zone (Eastern here). To pin a schedule to another zone, put a line such as
TZ=Europe/Londonabove the schedule. H/15means "every 15 minutes, starting at a hashed offset";H(0-5)limits the hash to a range.- Lines starting with
#are comments. Use them; in six months nobody will remember why the report runs at 02:00. - Aliases such as
@daily,@hourlyand@weeklyare hashed too:@dailybehaves likeH H * * *.
I gave the nightly-report job a temporary * * * * * schedule to watch it fire, then set the real one. The stored trigger and the timer-started build:
<triggers>
<hudson.triggers.TimerTrigger>
<spec># Summarise the access log every night, some time in the 02:00 hour.
# H spreads jobs out so they do not all start at 02:00 sharp.
H 2 * * *</spec>
</hudson.triggers.TimerTrigger>
</triggers>Started by timer
Running as SYSTEM
Building on the built-in node in workspace /home/sid/.jenkins/workspace/nightly-report
[…]
[nightly-report] $ /bin/sh -xe /tmp/jenkins17061908527521523755.sh
+ python3 logstats.py sample/access.log
requests: 10 unparsed: 1
by class: 2xx=6 3xx=1 4xx=1 5xx=2
5xx rate: 20.0%
3 /api/orders
3 /api/checkout
1 /api/orders/1042
Finished: SUCCESSPoll SCM
Poll SCM uses the same schedule syntax, but instead of building it asks the repository "anything new?" and builds only if the answer is yes. I set it to every minute on the logstats job. With nothing new, the job's polling log (at /job/<name>/scmPollLog/, linked from the job page while polling is enabled) said:
[…]
[poll] Latest remote head revision on refs/heads/main is: 65744506da9ad3361351ebcca1ce2d1243508d9c - already built by 8
Done. Took 0.26 sec
No changesThen I committed a change to the repository:
cd ~/logstats
echo '192.0.2.81 - - [09/Nov/2026:21:05:02 +0000] "GET /api/orders HTTP/1.1" 503 197 "-" "python-requests/2.31.0"' >> sample/access.log
git commit -qam "Add a 503 to the sample log"
git log --oneline -1fcc25fd Add a 503 to the sample logWithin a minute, a build started on its own:
Started by an SCM change
Running as SYSTEM
Building on the built-in node in workspace /home/sid/.jenkins/workspace/logstats-freestyle
[…]
Checking out Revision fcc25fd24122d756fbddfdaaef4cd887768bcf9d (refs/remotes/origin/main)
[…]
Commit message: "Add a 503 to the sample log"and its polling log recorded why:
Started on Nov 9, 2026, 9:53:14 PM
Using strategy: Default
[poll] Last Built Revision: Revision 65744506da9ad3361351ebcca1ce2d1243508d9c (refs/remotes/origin/main)
[…]
[poll] Latest remote head revision on refs/heads/main is: fcc25fd24122d756fbddfdaaef4cd887768bcf9d
Done. Took 0.11 sec
Changes foundPolling works anywhere, but it is wasteful (hundreds of jobs asking every few minutes) and slow (up to one interval of delay). If your git server can reach Jenkins, use a webhook so the server tells Jenkins about each push; Multibranch Pipelines and Webhooks sets that up. If you must poll, poll with H/5 or slower, never * * * * *.
Build after other projects are built
Build after other projects are built chains jobs: the deploy-staging job watches the build job and starts when it succeeds. Its first step, Copy artifacts from another project (Copy Artifact plugin), fetches the tarball the upstream build archived:
<triggers>
<jenkins.triggers.ReverseBuildTrigger>
<spec></spec>
<upstreamProjects>logstats-freestyle</upstreamProjects>
<threshold>
<name>SUCCESS</name>
<ordinal>0</ordinal>
<color>BLUE</color>
<completeBuild>true</completeBuild>
</threshold>
</jenkins.triggers.ReverseBuildTrigger>
</triggers>The Copy Artifact plugin runs in "production mode" by default (the controller log says CopyArtifact is set to Production mode. at start-up), which means the upstream job must explicitly allow other jobs to copy from it. I granted that in the build job's configuration (Permission to Copy Artifact, listing deploy-staging) before the first run. Here is a downstream build, after the workspace fix described in Common mistakes:
Started by upstream project "logstats-freestyle" build number 8
originally caused by:
Started from command line by admin
Running as SYSTEM
Building in workspace /home/sid/.jenkins/workspace/deploy-staging
[WS-CLEANUP] Deleting project workspace...
[WS-CLEANUP] Deferred wipeout is used...
[WS-CLEANUP] Done
Copied 1 artifact from "logstats-freestyle" build number 8
[deploy-staging] $ /bin/sh -xe /tmp/jenkins12599921240425900317.sh
+ DEPLOY_DIR=/home/sid/deploy/staging
+ mkdir -p /home/sid/deploy/staging
+ tar xzf incoming/logstats-8.tar.gz -C /home/sid/deploy/staging
+ ls -l /home/sid/deploy/staging
total 8
-rw-r--r-- 1 sid sid 43 Nov 9 21:50 VERSION
-rwxr-xr-x 1 sid sid 1661 Nov 9 21:46 logstats.py
+ cat /home/sid/deploy/staging/VERSION
8 65744506da9ad3361351ebcca1ce2d1243508d9c
Finished: SUCCESSoriginally caused by keeps the chain readable: you can always trace a deployment back to whoever started it.
Trigger builds remotely
Trigger builds remotely (e.g., from scripts) adds an authentication token, so an external system can start the job with a URL ending in ?token=.... I set the token logstats-7Hq2vX. The behaviour on a secured controller surprised me, so here is all of it.
With no Jenkins credentials, the token alone was not enough, whether I used GET or POST:
curl -sS -o /dev/null -w '%{http_code}\n' -X POST "http://localhost:8090/job/logstats-freestyle/build?token=logstats-7Hq2vX"
curl -sS -o /dev/null -w '%{http_code}\n' "http://localhost:8090/job/logstats-freestyle/buildWithParameters?token=logstats-7Hq2vX"403
403That is because this controller denies anonymous users even read access, and the build token doesn't override that. With an API token for a real user, the plain /build URL failed too, for a different reason:
curl -sS -X POST -u "admin:$JENKINS_API_TOKEN" "http://localhost:8090/job/logstats-freestyle/build?token=logstats-7Hq2vX" | sed -e 's/<[^>]*>/\n/g' | grep -v '^\s*$' | head -2Error 400 This page expects a form submission
HTTP ERROR 400 This page expects a form submissionA parameterized job must be started through buildWithParameters. That worked, returning the queue item's URL:
curl -sS -i -X POST -u "admin:$JENKINS_API_TOKEN" "http://localhost:8090/job/logstats-freestyle/buildWithParameters?token=logstats-7Hq2vX&TARGET_ENV=production&RUN_TESTS=false" | grep -iE '^(HTTP|Location)'HTTP/1.1 201 Created
Location: http://localhost:8090/queue/item/78/The build's cause was Started by remote host 127.0.0.1. When I left out the token parameter (API token only), the build also started, with the cause Started by user admin. With a wrong build token, Jenkins answered 403 even though the API token was valid.
My conclusion: on a controller that requires login, give the calling system its own Jenkins user with only the permissions it needs, and an API token. The build token adds little on top of that. (The Build Token Root plugin exists for the token-only case; it isn't installed on my lab controller, so I haven't tested it.)
Console output and the workspace
Every build's log is available as a page, as plain text at /job/<name>/<number>/consoleText, and through the CLI. The CLI's console command prints the raw log, including encoded console notes (the hyperlinks in the UI), so for scripts prefer consoleText:
jcli console logstats-freestyle 13 | head -1
curl -sS -u "admin:$JENKINS_API_TOKEN" http://localhost:8090/job/logstats-freestyle/13/consoleText | head -1Started by user [8mha:////4J23/Twi5fUXvrOD9gS3ZVzYR5nseNS4QHA/V+gbfYTxAAAAlx+LCAAAAAAAAP9b85aBtbiIQTGjNKU4P08vOT+vOD8nVc83PyU1x6OyILUoJzMv2y+/JJUBAhiZGBgqihhk0NSjKDWzXb3RdlLBUSYGJk8GtpzUvPSSDB8G5tKinBIGIZ+sxLJE/ZzEvHT94JKizLx0a6BxUmjGOUNodHsLgAzWEgZu/dLi1CL9xJTczDwAj6GcLcAAAAA=[0madmin
Started by user adminThe workspace is browsable in the UI (Workspace on the job page) and is just a directory on the agent. After build #2 it held the checkout plus everything the builds created:
ls -la ~/.jenkins/workspace/logstats-freestyletotal 48
drwxr-xr-x 8 sid sid 4096 Nov 9 21:46 .
drwxr-xr-x 23 sid sid 4096 Nov 9 21:47 ..
drwxr-xr-x 8 sid sid 4096 Nov 9 21:47 .git
-rw-r--r-- 1 sid sid 39 Nov 9 21:46 .gitignore
-rwxr-xr-x 1 sid sid 743 Nov 9 21:46 Jenkinsfile
drwxr-xr-x 2 sid sid 4096 Nov 9 21:46 __pycache__
drwxr-xr-x 2 sid sid 4096 Nov 9 21:47 dist
-rwxr-xr-x 1 sid sid 1661 Nov 9 21:46 logstats.py
-rw-r--r-- 1 sid sid 146 Nov 9 21:47 report.txt
drwxr-xr-x 2 sid sid 4096 Nov 9 21:46 reports
drwxr-xr-x 2 sid sid 4096 Nov 9 21:46 sample
drwxr-xr-x 3 sid sid 4096 Nov 9 21:46 testsdist/, reports/, report.txt and __pycache__/ are build output that git doesn't know about, and they survive into the next build. Keep that in mind; it's about to matter.
Artifacts, test results and fingerprints
The workspace is temporary; artifacts are the files you keep. Two post-build actions do the keeping:
<hudson.tasks.ArtifactArchiver>
<artifacts>dist/*.tar.gz, report.txt</artifacts>
<allowEmptyArchive>false</allowEmptyArchive>
<onlyIfSuccessful>true</onlyIfSuccessful>
<fingerprint>true</fingerprint>
<defaultExcludes>true</defaultExcludes>
<caseSensitive>true</caseSensitive>
<followSymlinks>false</followSymlinks>
</hudson.tasks.ArtifactArchiver>
<hudson.tasks.junit.JUnitResultArchiver plugin="junit">
<testResults>reports/*.xml</testResults>
<keepLongStdio>false</keepLongStdio>
<healthScaleFactor>1.0</healthScaleFactor>
<allowEmptyResults>true</allowEmptyResults>
</hudson.tasks.junit.JUnitResultArchiver>Archive the artifacts copies matching files into the build's own directory, so they outlive the workspace and stay attached to the build that made them. Publish JUnit test result report parses the XML report: the job then shows a test trend chart, and failing tests turn the build UNSTABLE (yellow) rather than FAILED. allowEmptyResults is on because a build with RUN_TESTS=false produces no report, and that shouldn't be an error.
Archived files live in the build directory:
ls -R ~/.jenkins/jobs/logstats-freestyle/builds/1/archive/home/sid/.jenkins/jobs/logstats-freestyle/builds/1/archive:
dist
report.txt
/home/sid/.jenkins/jobs/logstats-freestyle/builds/1/archive/dist:
logstats-1.tar.gzand are downloadable from a stable URL such as /job/<name>/lastSuccessfulBuild/artifact/dist/logstats-13.tar.gz, which is how other jobs and scripts fetch them.
Fingerprinting records the MD5 checksum of each archived file and, from then on, every build that touches a file with that checksum. Months later, "which build produced the tarball on the production server, and which deploy shipped it?" is one API call. I downloaded the artifact of build #13 and asked:
curl -sS -u "admin:$JENKINS_API_TOKEN" -fsO http://localhost:8090/job/logstats-freestyle/13/artifact/dist/logstats-13.tar.gz
md5sum logstats-13.tar.gz
curl -g -sS -u "admin:$JENKINS_API_TOKEN" "http://localhost:8090/fingerprint/59b499662e360d28cbf1874a783ae393/api/json?tree=original[name,number],usage[name,ranges[ranges[start,end]]]" | jq -c .59b499662e360d28cbf1874a783ae393 logstats-13.tar.gz
{"_class":"hudson.model.Fingerprint","original":{"name":"logstats-freestyle","number":13},"usage":[{"name":"logstats-freestyle","ranges":{"ranges":[{"end":14,"start":13}]}},{"name":"deploy-staging","ranges":{"ranges":[{"end":14,"start":13}]}}]}The file was created by logstats-freestyle #13 and used by deploy-staging #13 (ranges are half-open, so start 13, end 14 means build 13 only). The deploy job recorded its use because Copy Artifact fingerprints what it copies.
Keep history under control with a build discarder
Every build keeps its log, test results and artifacts forever unless you say otherwise, and that is how JENKINS_HOME fills a disk. Discard old builds (under General) sets limits. This job keeps 5 builds, and artifacts for only the newest 2:
<jenkins.model.BuildDiscarderProperty>
<strategy class="hudson.tasks.LogRotator">
<daysToKeep>-1</daysToKeep>
<numToKeep>5</numToKeep>
<artifactDaysToKeep>-1</artifactDaysToKeep>
<artifactNumToKeep>2</artifactNumToKeep>
</strategy>
</jenkins.model.BuildDiscarderProperty>-1 means "no limit". After build #7, on disk:
ls -l ~/.jenkins/jobs/logstats-freestyle/builds
cd ~/.jenkins/jobs/logstats-freestyle/builds && find . -path '*/archive/*' -type f | sorttotal 24
drwxr-xr-x 2 sid sid 4096 Nov 9 21:49 3
drwxr-xr-x 2 sid sid 4096 Nov 9 21:49 4
drwxr-xr-x 2 sid sid 4096 Nov 9 21:49 5
drwxr-xr-x 3 sid sid 4096 Nov 9 21:49 6
drwxr-xr-x 3 sid sid 4096 Nov 9 21:49 7
-rw-r--r-- 1 sid sid 126 Nov 9 21:49 permalinks
./6/archive/dist/logstats-6.tar.gz
./6/archive/report.txt
./7/archive/dist/logstats-7.tar.gz
./7/archive/report.txtBuilds 1 and 2 are gone, builds 3 to 5 kept their logs but lost their artifacts, and 6 and 7 are complete. The discarder runs after each build finishes. A build you have marked Keep this build forever is never deleted, which is how you protect a release build.
Why teams move to pipelines
Freestyle jobs did everything above, and you can see the cracks:
- The job definition lives in Jenkins, not in git. Nobody reviews a change to a shell step, and the
config.xmldiff isn't something you'd want to read. - The process is spread over several jobs. Build, deploy-to-staging and the chaining between them are three separate configurations. To understand the release, you click through all of them.
- No stages. One shell step runs the tests and packages; when it fails, you scroll the log to find out which part failed.
- Approvals, parallel work and retries need plugins and workarounds, each configured differently.
- A controller restart kills running freestyle builds; Pipeline builds are designed to resume.
Your First Pipeline rebuilds this same project as a Jenkinsfile, and the whole process fits on one screen.
Where you'll use this
Freestyle jobs remain a good fit for small, self-contained operational jobs. A realistic one is the nightly report from the triggers section, a complete job in one screen of XML: check out the tool, run it on a schedule with H, and keep the history visible. Here is the full stored configuration of nightly-report:
jcli get-job nightly-report<?xml version="1.1" encoding="UTF-8"?>
<project>
<description>Summarises the access log once a night.</description>
<keepDependencies>false</keepDependencies>
<properties/>
<scm class="hudson.plugins.git.GitSCM" plugin="git@5.11.0">
[…]
</scm>
<canRoam>true</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers>
<hudson.triggers.TimerTrigger>
<spec># Summarise the access log every night, some time in the 02:00 hour.
# H spreads jobs out so they do not all start at 02:00 sharp.
H 2 * * *</spec>
</hudson.triggers.TimerTrigger>
</triggers>
<concurrentBuild>false</concurrentBuild>
<builders>
<hudson.tasks.Shell>
<command>python3 logstats.py sample/access.log</command>
<configuredLocalRules/>
</hudson.tasks.Shell>
</builders>
<publishers/>
<buildWrappers/>
</project>The same pattern covers certificate-expiry checks, disk cleanups, database dumps and "rebuild the search index" buttons for a support team. Compared with a crontab entry, you get a log per run, a history, a parameter form, email or chat notification plugins, and a Build Now button that doesn't require SSH access to a server. For production use, add a build discarder and a credential for anything the script needs to log in to.
Common mistakes
Stale files in the workspace get archived. This is the bug from the parameters section. Build #2 archived both logstats-1.tar.gz and logstats-2.tar.gz, because dist/ survived from build #1. The deploy job copied dist/*.tar.gz, got two files, and its tar xzf incoming/logstats-*.tar.gz expanded to two arguments:
Started by upstream project "logstats-freestyle" build number 2
originally caused by:
Started from command line by admin
Running as SYSTEM
Building in workspace /home/sid/.jenkins/workspace/deploy-staging
Copied 2 artifacts from "logstats-freestyle" build number 2
[deploy-staging] $ /bin/sh -xe /tmp/jenkins12762825981985367570.sh
+ DEPLOY_DIR=/home/sid/deploy/staging
+ mkdir -p /home/sid/deploy/staging
+ tar xzf incoming/logstats-1.tar.gz incoming/logstats-2.tar.gz -C /home/sid/deploy/staging
tar: incoming/logstats-2.tar.gz: Not found in archive
tar: Exiting with failure status due to previous errors
Build step 'Execute shell' marked build as failure
Finished: FAILUREAnd because that failure skipped the rm -rf incoming at the end of the deploy script, every later deploy build failed as well. Stale state in one job's workspace broke the next job, and then that job broke itself.
The fix is to start every build from a clean workspace. For the git job, add Additional Behaviours → Clean before checkout under the git settings, which runs git clean -fdx (removing untracked and ignored files):
[…]
Fetching changes from the remote Git repository
> git config remote.origin.url file:///home/sid/logstats # timeout=10
Cleaning workspace
> git rev-parse --verify HEAD # timeout=10
Resetting working tree
> git reset --hard # timeout=10
> git clean -fdx # timeout=10For the deploy job, which has no git checkout, tick Delete workspace before build starts under Environment (from the Workspace Cleanup plugin). That's the [WS-CLEANUP] block in the downstream log shown earlier. After both changes, every build archived exactly one tarball and every deploy succeeded.
Bash syntax in a step that runs /bin/sh. This step has no #! line, so it runs under dash:
echo "TARGET_ENV is $TARGET_ENV"
if [[ "$TARGET_ENV" == production ]]; then
echo "Running production smoke tests"
fi
echo "done"[…]
[bashism] $ /bin/sh -xe /tmp/jenkins17979318635865454030.sh
+ echo TARGET_ENV is production
TARGET_ENV is production
+ [[ production == production ]]
/tmp/jenkins17979318635865454030.sh: 3: [[: not found
+ echo done
done
Finished: SUCCESSRead that twice: the build is green, and the production smoke tests never ran. [[ failed with "not found", and because a failing if condition doesn't trigger -e, dash took the false branch and carried on. Either start the step with #!/bin/bash -e or stick to POSIX syntax ([ "$TARGET_ENV" = production ]). Your First Scripts explains the difference between [ and [[.
Branch specifier that doesn't exist. Many examples online say */master; this repository's branch is main:
[…]
> git rev-parse refs/remotes/origin/master^{commit} # timeout=10
> git rev-parse origin/master^{commit} # timeout=10
ERROR: Couldn't find any revision to build. Verify the repository and branch configuration for this job.
Finished: FAILURERun git ls-remote --heads <url> to see the real branch names, and fix the Branch Specifier.
A schedule with four fields. Forgetting one field is easy. The check endpoint (and the UI field) rejects it before you save:
<div class="error">Invalid input: "*/15 * * *": line 1:10: mismatched input '<EOF>' expecting {WS, '/', ','} </div>[…]Summary
- A freestyle job is a UI form stored as
config.xml;jcli get-jobandjcli create-jobcopy and version it. - Shell steps run
/bin/sh -xeunless the first line is a#!line. On Ubuntu that is dash, so Bash syntax fails, sometimes without failing the build. - Every parameter becomes an environment variable of the same name. Booleans arrive in the shell as the strings
trueandfalse. Jenkins rejects unknown parameters and illegal choices before queueing. BUILD_NUMBER,BUILD_URL,JOB_NAME,WORKSPACEand the git plugin'sGIT_COMMITare the built-in variables you will use constantly.- Use
Hin schedules to spread load; prefer webhooks to polling; chain jobs with Build after other projects are built; trigger remotely as a dedicated user with an API token. - Archive what you want to keep and fingerprint it, so you can trace any artifact to the build that made it and the jobs that used it.
- Workspaces persist between builds. Clean them, or old files will end up in new artifacts.
- Always set a build discarder.
Exercises
Write Build periodically schedules for: (a) once every weekday at some point in the 06:00 hour, (b) every 30 minutes, (c) once a month on the 1st, at a time Jenkins chooses. Check each one with the checkSpec endpoint.
Show Solution
for spec in 'H 6 * * 1-5' 'H/30 * * * *' 'H H 1 * *'; do
enc=$(jq -rn --arg s "$spec" '$s|@uri'); echo "--- [$spec]"
curl -sS -u "admin:$JENKINS_API_TOKEN" -X POST "http://localhost:8090/descriptorByName/hudson.triggers.TimerTrigger/checkSpec?value=$enc"; echo
done--- [H 6 * * 1-5]
<div class="ok">Would last have run at Monday, November 9, 2026, 6:00:00 AM Eastern Standard Time; would next run at Tuesday, November 10, 2026, 6:00:00 AM Eastern Standard Time.</div>
--- [H/30 * * * *]
<div class="ok">Would last have run at Monday, November 9, 2026, 10:00:00 PM Eastern Standard Time; would next run at Monday, November 9, 2026, 10:30:00 PM Eastern Standard Time.</div>
--- [H H 1 * *]
<div class="ok">Would last have run at Sunday, November 1, 2026, 12:00:00 AM Eastern Daylight Time; would next run at Tuesday, December 1, 2026, 12:00:00 AM Eastern Standard Time.</div>Without a job context H hashes to 0, so the times sit on the hour; on a job's configuration page you would see that job's own minute. Notice the time-zone change in (c): schedules follow the controller's local time, daylight saving included.
Create a freestyle job that checks out logstats, takes a string parameter MAX_5XX_RATE (default 30), runs logstats.py on the sample log, and fails the build if the reported 5xx rate is above the parameter. Run it once with the default and once with MAX_5XX_RATE=20.
Hint
The shell can't compare decimals with [; awk can. Make the step's last command decide the exit status.
Show Solution
The build step:
#!/bin/bash -e
rate=$(python3 logstats.py sample/access.log | awk '/^5xx rate:/ { sub("%", "", $3); print $3 }')
echo "5xx rate ${rate}% (budget ${MAX_5XX_RATE}%)"
if awk -v r="$rate" -v max="$MAX_5XX_RATE" 'BEGIN { exit !(r > max) }'; then
echo "5xx rate is over budget"
exit 1
fijcli build ex-budget -s -v
jcli build ex-budget -s -v -p MAX_5XX_RATE=20[…]
[ex-budget] $ /bin/bash -e /tmp/jenkins12300710550515820131.sh
5xx rate 25.0% (budget 30%)
Finished: SUCCESS
Completed ex-budget #1 : SUCCESS
[…]
[ex-budget] $ /bin/bash -e /tmp/jenkins11268915343887879774.sh
5xx rate 25.0% (budget 20%)
5xx rate is over budget
Build step 'Execute shell' marked build as failure
Finished: FAILURE
Completed ex-budget #2 : FAILUREexit !(r > max) makes awk exit 0 (success) when the rate is over budget, which is what the if tests. The CLI's exit code also follows the result (0 and 2 here), so other scripts can react to it.
From a script, start logstats-freestyle with TARGET_ENV=staging through the REST API, then find out which build number Jenkins gave it.
Hint
The Location header points at a queue item. Queue items gain an executable field once the build has started.
Show Solution
LOC=$(curl -sS -i -X POST -u "admin:$JENKINS_API_TOKEN" "http://localhost:8090/job/logstats-freestyle/buildWithParameters?TARGET_ENV=staging" | awk 'tolower($1)=="location:" {print $2}' | tr -d '\r')
echo "Location: $LOC"
for i in $(seq 1 30); do
OUT=$(curl -g -sS -u "admin:$JENKINS_API_TOKEN" "${LOC}api/json?tree=executable[number,url]")
[ "$(echo "$OUT" | jq -r '.executable.number // empty')" != "" ] && break
sleep 1
done
echo "$OUT" | jq .Location: http://localhost:8090/queue/item/234/
{
"_class": "hudson.model.Queue$LeftItem",
"executable": {
"_class": "hudson.model.FreeStyleBuild",
"number": 13,
"url": "http://localhost:8090/job/logstats-freestyle/13/"
}
}You need the loop. On my first attempt I queried once after a fixed sleep 8 and got a Queue$WaitingItem with no executable yet. LeftItem means the item has left the queue and become a build.
Given only a tarball, logstats-13.tar.gz, find which build produced it and which deploy builds used it, without knowing the build number in advance.
Show Solution
The checksum is the key:
md5sum logstats-13.tar.gz
curl -g -sS -u "admin:$JENKINS_API_TOKEN" "http://localhost:8090/fingerprint/59b499662e360d28cbf1874a783ae393/api/json?tree=original[name,number],usage[name,ranges[ranges[start,end]]]" | jq -c .59b499662e360d28cbf1874a783ae393 logstats-13.tar.gz
{"_class":"hudson.model.Fingerprint","original":{"name":"logstats-freestyle","number":13},"usage":[{"name":"logstats-freestyle","ranges":{"ranges":[{"end":14,"start":13}]}},{"name":"deploy-staging","ranges":{"ranges":[{"end":14,"start":13}]}}]}Build 13 of the freestyle job produced it, and build 13 of the deploy job used it. This only works because both jobs fingerprint. It is also why I added the VERSION file to the tarball: before that, consecutive builds produced byte-identical tarballs (same file, same gzip output), so they shared one fingerprint, and the record pointed at whichever build archived it first.
Tested with: Jenkins 2.580.2 (LTS), Git plugin 5.11.0, Copy Artifact and Workspace Cleanup plugins, on OpenJDK 21.0.13 (Temurin), Ubuntu 24.04 (WSL2), November 2026. Every job was created from config.xml with the CLI and every build, trigger and API call above was run against that controller; logs are trimmed where marked […]. UI labels were checked against the same version's configuration pages over HTTP rather than clicked through. The timer and Poll SCM demos used a temporary every-minute schedule that I removed afterwards. Two things surprised me: a build token alone could not start a job on a controller that denies anonymous read, and the [[ mistake produced a green build. Paths from the test machine's scratch directories are shown shortened to /home/sid/…. Job, node and credential names are shown without the test run's prefixes.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Jenkins tutorial here is tested end to end before publishing.