Ravindra BagaleCourses & study guides मराठी

Chapter 21: Jenkins Pipeline and Jenkinsfile

21.12 Options: timeout, retry, timestamps, one build at a time

Why: the problem

A pipeline that works once is not enough. It must also behave well on bad days. Think of Swiggy at lunch time. A test hangs because a network call never returns. Without a timeout, the build waits for hours and blocks others. A flaky npm download fails once in fifty runs. Without retry, a developer loses time for nothing. Two builds start together and both copy to the same live folder. Files get mixed. Without one-build-at-a-time, you get a half new, half old site. The options block fixes all of this in a few lines. In this lesson you will cause each problem on purpose and then fix it with timeout, retry, timestamps and disableConcurrentBuilds, at pipeline level and at stage level.

What we will build

You will make a step hang, a step fail randomly, and two builds overlap. Then you will add timeout, retry, timestamps, disableConcurrentBuilds and quietPeriod, and see the logs change.

What: every term in plain English

  • timeout — Stops a build or step after a set time.
  • retry — Runs a block again if it fails, up to N times.
  • timestamps — Adds the time to each log line.
  • disableConcurrentBuilds — Only one build of this job runs at a time.
  • abortPrevious — Option of disableConcurrentBuilds that cancels the older build.
  • quietPeriod — Waits a few seconds before starting, to batch pushes.
  • skipDefaultCheckout — Do not clone automatically.
  • Flaky — A step that sometimes fails for no code reason.
Make a hang Add timeout Make a flaky step Add retry Overlap two builds Add one at a time
Bad day problems and their options

How: step by step

  1. Make a hang

    sh "sleep 600"
    

    What it does: Simulates a stuck test.

    Output

    (waits)
    
  2. Add timeout

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

    What it does: Build aborts after 2 minutes.

    Output

    Timeout has been exceeded
    
  3. Make a flaky step

    sh 'test $((RANDOM % 2)) -eq 0'
    

    What it does: Fails half the time.

    Output

    script returned exit code 1
    
  4. Add retry

    retry(3) { sh ... }
    

    What it does: Tries up to three times.

    Output

    Retrying
    
  5. Overlap two builds

    Click Build Now twice fast
    

    What it does: Two builds run together.

    Output

    #7 and #8 running
    
  6. Add one at a time

    options { disableConcurrentBuilds() }
    

    What it does: Second build waits.

    Output

    Waiting for previous build to finish
    

Example 1: Timeout at pipeline and step level

Stack. Jenkins options

Goal. Timeout at pipeline and step level.

Jenkinsfile

pipeline {
  agent any
  options {
    timeout(time: 10, unit: 'MINUTES')
    timestamps()
  }
  stages {
    stage('Slow test') {
      steps {
        timeout(time: 30, unit: 'SECONDS') {
          sh 'echo start; sleep 600; echo never'
        }
      }
    }
  }
}

What each line does

  • pipeline timeout 10 min — Safety net for the whole build.
  • step timeout 30 s — Tight limit just for the risky step.
  • sleep 600 — Our fake hang.
  • timestamps — Shows exactly when it was killed.

Green output

11:02:00  + echo start
11:02:00  start
11:02:00  + sleep 600
11:02:30  Cancelling nested steps due to timeout
11:02:30  Sending interrupt signal to process
11:02:30  Timeout has been exceeded
Finished: ABORTED

Expected result. Killed after 30 seconds, not 10 minutes. Times prove it.

Example 2: Retry a flaky download

Stack. Jenkins retry

Goal. Retry a flaky download.

Jenkinsfile

pipeline {
  agent any
  stages {
    stage('Install') {
      steps {
        retry(3) {
          sh 'echo try; test $((RANDOM % 2)) -eq 0 && npm ci'
        }
      }
    }
    stage('Whole stage retry') {
      options { retry(2) }
      steps { sh 'npm test' }
    }
  }
}

What each line does

  • retry(3) { } — Repeat the block up to 3 times total.
  • RANDOM % 2 — Bash random, fails half the time.
  • stage options retry — Retry the whole stage.
  • Warning — Retry hides real bugs. Use only for network steps.

Green output

+ echo try
try
ERROR: script returned exit code 1
Retrying
+ echo try
try
added 276 packages in 7s
[Pipeline] stage (Whole stage retry)
Tests: 2 passed, 2 total
Finished: SUCCESS

Expected result. The flaky step passed on the second try.

Example 3: One build at a time and quiet period

Stack. Jenkins options

Goal. One build at a time and quiet period.

Jenkinsfile

pipeline {
  agent any
  options {
    disableConcurrentBuilds(abortPrevious: true)
    quietPeriod(10)
    buildDiscarder(logRotator(numToKeepStr: '15', artifactNumToKeepStr: '5'))
  }
  stages {
    stage('Live') {
      steps {
        sh 'sleep 20; mkdir -p "$HOME/lab-live/badge-node"; date | tee "$HOME/lab-live/badge-node/version.txt"'
      }
    }
  }
}

What each line does

  • abortPrevious: true — A new build cancels the older running build.
  • quietPeriod(10) — Waits 10 seconds so quick pushes become one build.
  • artifactNumToKeepStr — Keeps artifacts only for the last 5 builds.
  • version.txt — Shows which build wrote last.

Green output

#9  Started by user admin
#10 Started by user admin
#9  Superseded by #10
#9  Finished: NOT_BUILT
#10 Sun Oct 25 11:10:40 IST 2026
#10 Finished: SUCCESS

Expected result. Only the newest build updated Live. No mixed files.

Example 4: Lock a shared lab folder across two different jobs

Stack. Lockable Resources plugin

Goal. Lock a shared lab folder across two different jobs.

Jenkinsfile (both jobs)

pipeline {
  agent any
  stages {
    stage('Live') {
      options { lock(resource: 'lab-live-folder') }
      steps {
        sh 'echo "$JOB_NAME writing"; sleep 15; date | tee "$HOME/lab-live/last-writer.txt"'
      }
    }
  }
}

What each line does

  • lock(resource: ...) — From the Lockable Resources plugin. Only one build in the whole Jenkins holds it.
  • Two jobs — disableConcurrentBuilds works per job; lock works across jobs.
  • Stage level — Only the Live stage waits, tests still run in parallel.
  • last-writer.txt — Shows who wrote last.

Green output

badge-scm #20   Lock acquired on [lab-live-folder]
badge-docs #4   Trying to acquire lock on [lab-live-folder]
badge-docs #4   Found 0 available resource(s). Waiting for correct amount: 1.
badge-scm #20   Lock released on resource [lab-live-folder]
badge-docs #4   Lock acquired on [lab-live-folder]
Finished: SUCCESS

Expected result. Two jobs never write the folder at the same time. Use this for one test database or one lab server.

Verify: did it work?

  1. Check build queue

    Jenkins home > Build Queue
    

    What it does: Shows waiting builds.

    Output

    badge-scm #11 (pending, waiting for previous)
    
  2. See retries

    Pipeline Steps view
    

    What it does: Shows each retry attempt.

    Output

    sh (failed), sh (success)
    

When it is red 1

Timeout has been exceeded

Cause. A step is too slow or stuck.

Fix, step by step

  1. Find it with timestamps.
  2. Fix the cause, then set a fair limit.

When it is red 2

Retry hides a real test failure

Cause. retry used on tests.

Fix, step by step

  1. Remove retry from tests.
  2. Fix the flaky test.

When it is red 3

Invalid option type 'disableConcurentBuilds'

Cause. Spelling.

Fix, step by step

  1. Copy from the generator.

When it is red 4

No such DSL method 'lock' found

Cause. Lockable Resources plugin is missing.

Fix, step by step

  1. Install it.
  2. Add the resource name under Manage Jenkins > Lockable Resources, or let Jenkins create it.

Cleanup

  1. Remove the hang

    Delete the sleep step and push
    

    What it does: Back to normal.

    Output

    (file saved)
    
  2. Clear live

    rm -f $HOME/lab-live/badge-node/version.txt
    

    What it does: Cleans the lab.

    Output

    (no output)
    

Ravindra Bagale's Tip

timeout nasel tar build tasan-tas atakto. retry fakt network sathi. Lakshat theva!

Practice tasks

Easy Add timestamps

Why: Free speed for debugging.

What to do: Add timestamps().

How:
  1. Run.

Check: Times in log.

Medium Timeout a hang

Why: Stop wasted hours.

What to do: Step timeout 30s.

How:
  1. sleep 600.

Check: ABORTED in 30s.

Hard Safe live copy

Why: Mixed files break sites.

What to do: disableConcurrentBuilds.

How:
  1. Build twice.

Check: Only one runs.

Easy Say pipeline options in two lines

Why: If you can say it simply, you understand it. Juniors and interviewers want the short version first.

What to do: Write two short lines about pipeline options for a fresher who knows only Linux basics.

How:
  1. Write what problem it solves.
  2. Write the one command or menu you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Start a fresh lab Jenkins

Why: Practice needs a throwaway Jenkins. If you break it, you delete it and start again.

What to do: Run Jenkins LTS in Docker with a named volume.

How:
  1. docker volume create jenkins_home
  2. docker run -d --name jenkins -p 8080:8080 -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts-jdk17
  3. docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword

Check: The Jenkins unlock page opens on localhost:8080.

Medium Break it on purpose

Why: You must know the red message by face. During an outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using only the steps, without searching the web.

Medium Write a one-page runbook

Why: At 2 a.m. nobody remembers where a file lives. A short page saves the on-call person.

What to do: Write a runbook page for this lesson.

How:
  1. Title, when to use, exact command, how to check, how to undo.

Check: A teammate can follow it alone.

Medium Repeat it on a cloud VM

Why: A laptop is not a server. Real Jenkins runs on EC2 or a company VM.

What to do: Do the main steps of this lesson again on a small Ubuntu 22.04 EC2 instance.

How:
  1. Launch t3.small with 20 GB disk.
  2. Open port 22 only to your IP.
  3. Repeat the steps and compare the output.

Check: Same green output on the VM as on your laptop.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the command you ran, and one error you hit.

Check: Your answer has a real command and a real error message.

Hard Draw the flow top to bottom

Why: A drawing shows who talks to whom and in what order.

What to do: Draw this lesson as boxes from top to bottom.

How:
  1. Start at the developer push, go through the controller and agent, end at the result.

Check: Each box matches a real thing you saw on screen.

Homework: try at home

Try at home

At home, make one hang, one flaky step and two overlapping builds, then fix each with options. Keep the logs.

Recap

  • timeout stops hangs.
  • retry only for network steps.
  • timestamps help debugging.
  • disableConcurrentBuilds protects shared folders.
  • quietPeriod batches pushes.

FAQ

Pipeline or step timeout?

Both. A wide pipeline limit and tight step limits.

Does retry wait between tries?

Not by default. Add sleep inside, or use retry(count: 3, conditions: ...) in newer versions.

Does abortPrevious lose work?

The old build stops, which is fine for a deploy that the new build will redo.

Why buildDiscarder?

Old builds fill the controller disk.

What unit options exist?

SECONDS, MINUTES, HOURS.

lock or disableConcurrentBuilds?

disableConcurrentBuilds is for one job. lock protects a thing shared by many jobs.

Interview questions

  1. How do you stop stuck builds?

    timeout in options and around risky steps.

  2. When to use retry?

    For flaky network actions like downloads, not for tests.

  3. How do you stop two deploys at once?

    disableConcurrentBuilds, or lock from the Lockable Resources plugin.

  4. How do you save disk on Jenkins?

    buildDiscarder with logRotator.

  5. Build aborted after 30 seconds. Why?

    A timeout fired; check timestamps for the slow step.

  6. How do you protect a shared test server used by many jobs?

    Use lock from Lockable Resources around the stage that uses it.

  7. Why not retry tests?

    Retry hides flaky tests. Fix or quarantine them instead.

Quick quiz

Q1. Which option stops a hung build?

timeout.

Q2. Where should you use retry?

Network steps only.

Q3. What does abortPrevious do?

Cancels the older running build.

Q4. Why timestamps?

To see when things happened.

Q5. What does quietPeriod do?

Waits before starting.

Samajla ka?

Ravi Sir's Cards for this lesson

मराठी cards