Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 40 ยท Practice and Review

Common Mistakes and Anti-Patterns

Learn the Jenkins mistakes that cause slow, insecure and fragile CI: builds on the controller, secrets in logs, missing timeouts, giant Jenkinsfiles, and how to fix each one.

Most Jenkins installations that people complain about are not suffering from Jenkins. They are suffering from a handful of habits that look harmless in week one and hurt in month six. This lesson collects the common ones, explains why each is a problem, and shows the fix. Reading it now is cheaper than learning it from a 3 a.m. incident.

The examples here are real Jenkins and Groovy code, shown read-only because they need a server. At the end you will run a small linter written in JavaScript that scans Jenkinsfile text for several of these mistakes. It is a teaching stand-in built from simple text patterns: useful as a habit-builder, but far weaker than reviewing a pipeline with a human or with a proper static analysis tool.

Where things go wrong

Structure Logic in the UI, giant files, no review.
Security Secrets in logs, builds on the controller.
Reliability No timeouts, dirty workspaces, unpinned plugins.

Almost every mistake is about missing limits or missing isolation.

1 / 2

1. Real logic in freestyle jobs

A freestyle job keeps its configuration in the web form. There is no history of who changed the shell step, no code review, and no way to copy the job to a new project except by cloning and editing by hand. After fifty jobs, nobody knows why the staging job differs from staging-2.

Fix. Put the build in a Jenkinsfile in the repository (see Pipeline Basics and the Jenkinsfile). The pipeline then lives next to the code it builds, changes go through pull requests, and a new branch gets the right pipeline automatically with a multibranch job.

2. Building on the controller

If the controller has executors, a job with agent any may run on it. Build code can then read files in JENKINS_HOME, including credentials and encryption keys, and a runaway build can starve the web interface.

GROOVY
// Risky: may land on the controller
pipeline { agent any ... }

// Better: ask for a specific kind of agent
pipeline { agent { label 'linux && docker' } ... }

Fix. Set the controller's executor count to 0 and always request labeled agents. See Jenkins Architecture for the reasoning.

3. Secrets in logs and in the Jenkinsfile

Two separate mistakes share one root cause: treating a secret like an ordinary string.

GROOVY
// Mistake A: the secret lives in the repository
environment { API_TOKEN = 'sk_live_abc123456789' }

// Mistake B: Groovy interpolates the secret into the command text
withCredentials([string(credentialsId: 'api-token', variable: 'API_TOKEN')]) {
  sh "curl -H 'Authorization: Bearer ${API_TOKEN}' https://example.com"
}

In mistake B, the double-quoted Groovy string is expanded by Jenkins before the shell runs, so the secret becomes part of the script text. Jenkins masks known secret values in the console, but masking is a best-effort filter: encoding or splitting a secret can defeat it, and Jenkins itself warns about this pattern.

GROOVY
// Fix: single quotes, so the shell reads the variable at run time
withCredentials([string(credentialsId: 'api-token', variable: 'API_TOKEN')]) {
  sh 'curl -H "Authorization: Bearer $API_TOKEN" https://example.com'
}

Fix. Store secrets in the Jenkins credentials store, bind them with withCredentials, and use single-quoted sh so the shell expands them (see Credentials and Secrets). If a secret was ever committed, rotate it: deleting the line does not remove it from Git history.

Also watch for user-controlled text. sh "deploy ${params.TARGET}" lets anyone who can set the parameter inject shell commands. Pass such values as environment variables and quote them inside the script.

4. No timeouts

A test that waits for a network port that never opens will wait forever, hold an executor forever, and block everything queued behind it.

GROOVY
options {
  timeout(time: 20, unit: 'MINUTES')
}

Fix. Put a global timeout in options, and use tighter ones around steps that are known to hang (input, network calls, deployments). Add buildDiscarder(logRotator(numToKeepStr: '30')) in the same block so history does not eat the disk.

5. Dirty workspaces

Workspaces are reused between builds on the same agent. A file left by build 41 (a generated report, a stale node_modules, a lock file) can make build 42 pass or fail for the wrong reason, and the failure will not reproduce on another agent.

Fix. Start from a clean state, either with cleanWs() in a post { cleanup { ... } } block, or by building in a fresh container. Cache dependencies on purpose, with a key, rather than by accident.

6. Unpinned plugins, libraries and images

Clicking "update all" on a Friday, or using FROM jenkins/jenkins:lts and rebuilding without checking, changes plugin versions underneath working pipelines. The same applies to @Library('ci-lib') with no version and Docker images tagged latest.

GROOVY
@Library('[email protected]') _          // pinned
agent { docker { image 'maven:3.9.9-eclipse-temurin-21' } }   // pinned

Fix. Pin the library version, pin image tags, and keep plugins in a versioned list (see Plugins). Update in a staging controller first.

7. One giant Jenkinsfile

A 900-line Jenkinsfile with copy-pasted stages is a program nobody wants to touch. Every project that copies it forks the mistakes.

Fix. Extract repeated steps into a shared library, keep the Jenkinsfile as a short description of what the pipeline does, and keep build logic in scripts or build tools (Maven, Gradle, make) that also run on a laptop.

8. Piping the internet into a shell

curl https://example.com/install.sh | sh runs whatever that URL returns today, on an agent with your credentials nearby. Fix: download a pinned, checksummed artifact, or bake the tool into the agent image.

A stand-in linter

The first TryIt scans Jenkinsfile text for several of the mistakes above using simple patterns. It reports a severity, the line number and a hint. Remember its limits: a regular expression sees text, not meaning, so it will miss some problems and may flag harmless code.

JS A pattern-based Jenkinsfile linter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The sample file deliberately commits almost every sin. Notice that the linter points at line numbers, so it can be wired into a pull request check. In real life you would also run Jenkins' own validator, which understands the real grammar.

The fixed version

A cleaned-up pipeline addresses each finding: a labeled agent, credentials from the store, single quotes, a timeout, retention, a pinned library and image. Run the same linter on it to see the findings disappear.

JS Lint the improved Jenkinsfile

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A clean result does not prove the pipeline is correct. It only proves these specific patterns are absent. Treat any linter as a smoke detector, not as a fire inspector.

Make the cure automatic. Run the pipeline linter and Jenkins' own validation on pull requests to the Jenkinsfile, so mistakes are caught in review rather than at deploy time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is sh "curl -H 'Authorization: Bearer ${API_TOKEN}' ..." a problem?

    Double-quoted Groovy strings are interpolated by Jenkins. Use a single-quoted sh so the shell reads the variable instead.
  2. 2. What is the main risk of running builds on the controller?

    The controller holds secrets and configuration. Keep builds on isolated agents and set the controller to zero executors.
  3. 3. Which option best prevents a hung test from blocking an executor forever?

    timeout aborts the build after a limit. buildDiscarder limits stored history, and cleanWs cleans files; neither stops a hang.
  4. 4. Why pin a shared library with @Library('[email protected]')?

    A version pin means pipelines only change when you choose to upgrade.

Summary

  • Keep pipelines in code, reviewed and versioned; avoid logic in freestyle forms.
  • Never build on the controller; request labeled agents and use zero controller executors.
  • Keep secrets in the credentials store, bind them with withCredentials, and use single-quoted sh.
  • Add timeouts and retention, clean workspaces, and pin plugins, libraries and images.
  • Split giant Jenkinsfiles with shared libraries, and lint pipelines in review.

Now practice what you have learned in Practice Exercises with Solutions.