βοΈ The Classic Workhorse: Understanding Jenkins Freestyle Project Architecture
Before the advent of modern Pipeline-as-Code (Declarative and Scripted Jenkinsfiles), Freestyle Projects formed the foundational core of Jenkins automation. A Freestyle Project is a web-configured, modular task orchestration model that executes a sequential set of steps inside a dedicated agent workspace. It combines six distinct operational phases: General Parameters & Execution Environment, Source Code Management (SCM), Build Triggers, Build Environment Preparation, Build Steps (Compilation, Testing, Packaging), and Post-Build Actions (Artifact Archiving, Test Result Publishing, Notifications, and Downstream Job Invocations). While modern microservices architectures favor version-controlled Jenkinsfiles, Freestyle Jobs remain vital in enterprise automation for utility jobs, scheduled system maintenance, artifact promotions, hardware-in-the-loop test benches, and legacy CI/CD maintenance.
FREESTYLE JOB EXECUTION LIFECYCLE:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TRIGGER PHASE (Event Detection) β
β Webhook (Push) / Poll SCM (Cron) / Scheduled (H/15 * * * *) / Upstream Job Done β
ββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β WORKSPACE ALLOCATION & PREPARATION β
β 1. Queue scheduler assigns job to target node (matching Node Label restriction) β
β 2. Allocate workspace: $JENKINS_HOME/workspace/job-name (or Agent remote root) β
β 3. Optional: Wipe out repository & clean workspace before build executes β
ββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SOURCE CODE MANAGEMENT (SCM) CHECKOUT β
β β’ Fetch repository: git fetch --tags --progress https://github.com/org/repo.git β
β β’ Checkout refspec: git checkout -b main origin/main --force β
β β’ Set Environment variables: $GIT_COMMIT, $GIT_BRANCH, $GIT_PREVIOUS_SUCCESSFUL_COMMITβ
ββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BUILD ENVIRONMENT PREPARATION β
β β’ Inject secret credentials (Username/Password, Secret Text, SSH Key) β
β β’ Add timestamps to console output (Timestamper plugin) β
β β’ Terminate build if hung (Build-timeout plugin) β
ββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SEQUENTIAL BUILD STEPS β
β Step 1: Execute Shell β mvn clean compile (Exit Code 0 β Next Step) β
β Step 2: Execute Shell β mvn test (Exit Code 0 β Next Step) β
β Step 3: Execute Shell β docker build -t app . (Non-zero Exit β Fail Build & Skip) β
ββββββββββββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β POST-BUILD ACTIONS (Always / On-Condition) β
β β’ Archive the artifacts: target/*.jar, dist/** β
β β’ Publish JUnit test result report: target/surefire-reports/*.xml β
β β’ Trigger parameterized downstream projects β
β β’ Dispatch Slack / Email notifications (BUILD_STATUS: SUCCESS, UNSTABLE, FAILURE) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
<!-- Git SCM Section in Freestyle Job XML Definition -->
<scm class="hudson.plugins.git.GitSCM" plugin="git@5.2.1">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<name>origin</name>
<refspec>+refs/heads/*:refs/remotes/origin/*</refspec>
<url>git@github.com:enterprise-org/payment-gateway.git</url>
<credentialsId>github-jenkins-deploy-ssh-key</credentialsId>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
<branches>
<hudson.plugins.git.BranchSpec>
<!-- Target specific branch, tag, or commit hash -->
<name>*/main</name>
</hudson.plugins.git.BranchSpec>
</branches>
<doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
<submoduleCfg class="empty-list"/>
<extensions>
<!-- Advanced Behavior: Wipe out workspace before checkout -->
<hudson.plugins.git.extensions.impl.WipeWorkspace/>
<!-- Advanced Behavior: Clone with shallow depth to speed up checkout -->
<hudson.plugins.git.extensions.impl.CloneOption>
<shallow>true</shallow>
<noTags>false</noTags>
<depth>1</depth>
<timeout>15</timeout>
</hudson.plugins.git.extensions.impl.CloneOption>
<!-- Advanced Behavior: Clean untracked files & build remnants -->
<hudson.plugins.git.extensions.impl.CleanBeforeCheckout/>
</extensions>
</scm>
BUILD TRIGGER TOPOLOGIES & CONFIGURATIONS:
1. GITHUB / SCM PUSH WEBHOOK (PUSH-BASED - ZERO DELAY):
β’ Checkbox: "GitHub hook trigger for GITScm polling"
β’ Mechanism: Remote repository sends an HTTP POST payload to:
https://jenkins.company.com/github-webhook/
β’ Processing: Jenkins reads the repository URL from payload, scans all registered
jobs referencing that URL, and triggers an immediate build.
2. POLL SCM (PULL-BASED - REVERSE POLLING):
β’ Checkbox: "Poll SCM"
β’ Schedule: H/5 * * * * (Checks every 5 minutes with randomized hash spread)
β’ Mechanism: Jenkins connects to Git remote repository and checks:
git ls-remote -h git@github.com:org/repo.git refs/heads/main
If remote SHA-1 != local SHA-1, a build is queued. If identical, zero work is executed.
3. BUILD PERIODICALLY (CRON SCHEDULE - UNCONDITIONAL):
β’ Checkbox: "Build periodically"
β’ Syntax: MINUTE (0-59), HOUR (0-23), DAY_OF_MONTH (1-31), MONTH (1-12), DAY_OF_WEEK (0-7)
β’ Enterprise Examples:
H 2 * * * β Run once daily between 02:00 and 02:59 (automatic load balance)
H(0-30) 22 * * 1-5 β Run nightly Monday to Friday between 22:00 and 22:30
H/15 * * * * β Run every 15 minutes past the hour (e.g., :07, :22, :37, :52)
4. TRIGGER BUILDS REMOTELY (VIA REST API SCRIPT):
β’ Checkbox: "Trigger builds remotely (e.g., from scripts)"
β’ Set Authentication Token: PROD_RELEASE_SECRET_KEY_9821
β’ Invocation via cURL:
curl -X POST https://jenkins.company.com/job/my-freestyle-job/build \
--user "automation_bot:11a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3" \
--data-urlencode json='{"parameter": [{"name":"ENV", "value":"staging"}]}' \
-H "Jenkins-Crumb: 4a3b2c1d0e9f8a7b6c5d4e3f2a1b0c9d"
#!/usr/bin/env bash
# ==============================================================================
# Production Build Step: Compile, Unit Test, Vulnerability Scan & OCI Package
# ==============================================================================
# Enforce strict error handling:
# -e: Exit immediately if any command exits with a non-zero status
# -u: Treat unset variables as an error and exit immediately
# -o pipefail: Pipeline exit status is the value of the last non-zero command
set -euo pipefail
echo "========================================================================"
echo " JOB: ${JOB_NAME} | BUILD: #${BUILD_NUMBER} | NODE: ${NODE_NAME}"
echo " GIT COMMIT: ${GIT_COMMIT:-Unknown} | BRANCH: ${GIT_BRANCH:-Unknown}"
echo " WORKSPACE: ${WORKSPACE}"
echo "========================================================================"
echo "[*] Step 1: Compiling application and running unit test suite..."
mvn clean compile test -Dmaven.test.failure.ignore=false
echo "[*] Step 2: Packaging application archive..."
mvn package -DskipTests=true
echo "[*] Step 3: Verifying build artifact presence..."
ARTIFACT_PATH="target/payment-gateway-service.jar"
if [ ! -f "${ARTIFACT_PATH}" ]; then
echo "[-] CRITICAL ERROR: Expected build artifact ${ARTIFACT_PATH} was not generated!"
exit 1
fi
echo "[+] Artifact confirmed: $(ls -lh ${ARTIFACT_PATH})"
echo "[*] Step 4: Building Docker Container Image..."
IMAGE_TAG="registry.company.com/finance/payment-service:${BUILD_NUMBER}"
docker build -t "${IMAGE_TAG}" .
echo "[*] Step 5: Scanning container image for critical CVEs..."
trivy image --severity CRITICAL --exit-code 1 "${IMAGE_TAG}"
echo "[*] Step 6: Pushing verified image to enterprise registry..."
docker push "${IMAGE_TAG}"
echo "[β] Build step completed successfully."
POST-BUILD ACTIONS INVENTORY & BEHAVIORS:
1. ARCHIVE THE ARTIFACTS:
β’ Purpose: Copies generated binary packages from the agent's transient workspace
to the controller's permanent storage ($JENKINS_HOME/jobs/.../builds/X/archive/).
β’ Files to archive: target/*.jar, target/*.war, dist/**, reports/**/*.html
β’ Advanced Options:
- "Fingerprint all archived artifacts": Enables SHA-1 cross-job provenance tracking.
- "Only keep the artifacts from the last successful build": Conserves disk storage.
2. PUBLISH JUNIT TEST RESULT REPORT:
β’ Purpose: Parses standard JUnit/xUnit XML test result files emitted by testing tools
(Maven Surefire, PyTest --junitxml, Jest-junit).
β’ Test report XMLs: target/surefire-reports/*.xml, test-results/**/*.xml
β’ Result Thresholds:
- If all tests pass β Build status remains SUCCESS (Blue/Green).
- If 1 or more tests fail β Build transitions to UNSTABLE (Yellow).
- If XML files are malformed or missing β Build transitions to FAILURE (Red).
3. SLACK / EMAIL NOTIFICATIONS:
β’ Email-ext plugin configuration:
- Trigger: "Failure - Any", "Success", "Fixed", "Still Failing"
- Recipients: Developer who committed the change ($CHANGES_OR_DEFAULT_ADDRESS)
- Content Template:
Project: $PROJECT_NAME - Build #$BUILD_NUMBER - Status: $BUILD_STATUS
Console URL: $BUILD_URL/console
Failed Tests: ${FAILED_TESTS}
PARAMETER DECLARATIONS & SHELL CONSUMPTION:
1. COMMON PARAMETER TYPES:
β’ String Parameter:
Name: TARGET_ENV | Default: staging | Description: Deployment target cluster
β’ Choice Parameter:
Name: LOG_LEVEL | Choices: INFO, DEBUG, WARN, ERROR (One per line)
β’ Boolean Parameter:
Name: RUN_SMOKE_TESTS | Default: true | Description: Toggle post-deploy verification
β’ Password Parameter:
Name: DB_SECRET | Default: [MASKED] | Description: Database migration key
β’ Git Parameter (Plugin):
Name: RELEASE_TAG | Parameter Type: Branch or Tag | Filter: *
2. CONSUMPTION INSIDE "EXECUTE SHELL" BUILD STEPS:
Jenkins automatically exposes all configured parameters as environment variables:
#!/bin/bash
set -eu
echo "Deploying to target environment: ${TARGET_ENV}"
echo "Active logging configuration : ${LOG_LEVEL}"
if [ "${RUN_SMOKE_TESTS}" = "true" ]; then
echo "[*] Initiating comprehensive API smoke test suite..."
mvn test -Dtest=SmokeTestSuite
else
echo "[!] Skipping smoke tests per build parameter override."
fi
# Accessing Git Parameter selection
git checkout "${RELEASE_TAG}"
MULTI-JOB CHAINING ARCHITECTURE:
[Job 1: payment-compile-and-unit-test]
β
β (On SUCCESS only)
βΌ
[Job 2: payment-docker-image-build] ββ (Passes: DOCKER_IMAGE_TAG=${BUILD_NUMBER})
β
β (On SUCCESS only)
βΌ
[Job 3: payment-deploy-to-staging] ββ (Deploys image to staging K8s namespace)
β
β (On SUCCESS only)
βΌ
[Job 4: payment-staging-api-smoke-test] (Triggers Newman / Playwright suites)
CONFIGURATION DETAILS:
1. Standard Chaining ("Build other projects"):
β’ Under Post-Build Actions: Select "Build other projects"
β’ Projects to build: payment-docker-image-build
β’ Trigger only if build is stable (recommended)
2. Advanced Parameterized Chaining ("Trigger parameterized build on other projects"):
β’ Requires Parameterized Trigger Plugin.
β’ Allows passing current job parameters, Git commit hashes, or properties files:
- "Current build parameters" (Passes all inputs forward)
- "Parameters from properties file": env_vars.properties
- "Predefined parameters":
UPSTREAM_BUILD_NUMBER=${BUILD_NUMBER}
SOURCE_BRANCH=${GIT_BRANCH}
WORKSPACE PROTECTION & TIMEOUT MANAGEMENT:
1. WORKSPACE CLEANUP PLUGIN (Pre-build & Post-build):
β’ Build Environment Checkbox: "Delete workspace before build starts"
- Deletes all legacy build outputs, temporary files, and downloaded dependencies.
- Ensures the build runs in a completely clean environment without leftover artifacts.
β’ Post-Build Action: "Delete workspace when build is done"
- Clears the workspace directory on the agent immediately after completion.
- Essential on shared static build agents to conserve disk space.
2. BUILD TIMEOUT PLUGIN:
β’ Problem: An unhandled prompt, frozen database query, or network hang blocks the executor indefinitely.
β’ Solution: Under Build Environment, enable "Abort the build if it's stuck"
β’ Strategies:
- Absolute Timeout: Abort after 30 minutes.
- Likely Stuck Timeout: Abort if build takes 150% of recent successful average duration.
- Action: Abort and restart, or Abort and mark build as FAILURE.
3. ADD TIMESTAMPS TO THE CONSOLE OUTPUT:
β’ Checkbox: "Add timestamps to the Console Output" (Timestamper plugin).
β’ Injects exact wall-clock UTC timestamps on every log line, making performance
bottleneck identification straightforward.
DIAGNOSTIC SCENARIOS & REMEDIATIONS:
1. ERROR: "Permission denied" during Execute Shell:
β’ Console Log: /tmp/jenkins82103819.sh: Permission denied
β’ Cause: The /tmp filesystem on the agent is mounted with the 'noexec' flag, or the
jenkins user lacks execution permissions on the allocated workspace directory.
β’ Solution:
- Remount /tmp with execution rights: sudo mount -o remount,exec /tmp
- Or configure Jenkins to use a custom temp directory:
Add JVM flag: -Djava.io.tmpdir=/var/lib/jenkins/tmp
2. ERROR: "Host key verification failed" during SCM Checkout:
β’ Console Log: Host key verification failed. fatal: Could not read from remote repository.
β’ Cause: The SSH host key of github.com is missing from the jenkins user's ~/.ssh/known_hosts file.
β’ Solution: Under Manage Jenkins β Security β Git Host Key Verification Configuration,
select "Accept first connection" or "Known hosts file".
3. ERROR: "No artifacts found that match the file pattern":
β’ Console Log: ERROR: Step βArchive the artifactsβ failed: No artifacts found that match
the file pattern "target/*.jar". Configuration error?
β’ Cause: The path specified is relative to the root of the workspace. If the build step
ran inside a subdirectory (e.g., cd backend && mvn package), the artifact resides
at backend/target/*.jar.
β’ Solution: Update artifact pattern to: **/target/*.jar
4. ERROR: "Command not found" for installed binaries (mvn, docker, node):
β’ Cause: The non-interactive shell invoked by Jenkins has a restricted PATH variable
(usually /usr/bin:/bin) and does not source /etc/profile or ~/.bashrc.
β’ Solution: Under Manage Jenkins β System, add an Environment Variable entry:
PATH = $PATH:/usr/local/bin:/opt/maven/bin:/usr/local/go/bin
FREESTYLE PROJECTS VS. PIPELINE-AS-CODE SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β ARCHITECTURAL ATTRIBUTE β FREESTYLE PROJECT (CLASSIC) β PIPELINE-AS-CODE (JENKINSFILE) β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββ€
β Configuration Storage β XML file on Controller disk β Version-controlled in Git repository β
β Version Control History β None (Overwritten on save) β Full Git commit tracking & audit log β
β Pipeline Resiliency β Fails if controller restarts β Resumes from suspended state on boot β
β Parallel Stage Support β Very difficult / multi-job β Native parallel directive β
β Code Review Process β Impossible (UI web forms) β Pull Request / Code Review workflow β
β Disaster Recovery β Requires $JENKINS_HOME backupβ Instantly rebuilt from repository β
β Multi-Branch Support β 1 Job per branch manually β Automated multi-branch indexing β
β Microservices Scaling β High management overhead β Reusable via Shared Libraries β
β Best Operational Fit β Simple utilities, cron jobs β Enterprise CI/CD delivery pipelines β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββ€
β TOP 5 CORE FREESTYLE BEST PRACTICES FOR SREs: β
β 1. Always enforce strict shell safety: Put 'set -euo pipefail' at the top of Execute Shell. β
β 2. Parameterize secrets: Never hardcode credentials, passwords, or tokens in shell blocks. β
β 3. Enable build timeouts: Prevent hung sub-processes from permanently consuming executors. β
β 4. Schedule with Hash spread: Use 'H/15 * * * *' instead of fixed minute offsets. β
β 5. Plan migration to Pipelines: Treat complex Freestyle job chains as technical debt. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ