Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 40 ยท Practice and Review

Practice Exercises with Solutions

Practice Jenkins pipelines with five scenarios: test and archive, a build matrix, a parameterised deploy, failure notification and a cron schedule, with solutions explained.

Reading about pipelines is easy; writing them from a blank file is the real skill. This lesson gives you five scenarios of increasing difficulty. For each one, try to write the Jenkinsfile yourself first, on paper or in an editor, before you open the solution. Then compare, and read the explanation of every line that differs from yours.

The pipelines are real declarative Jenkins code, so they are shown read-only. You cannot run Jenkins here, but you can run two stand-ins at the end: a structure checker that tests solution text for the features each exercise asks for, and a cron checker for the schedule exercise. They are simple text-based helpers, not Jenkins itself, so a pipeline that passes them can still fail on a real server.

Five scenarios

Test and archive Run tests, publish reports, keep a package.
Matrix One stage, many versions and platforms.
Parameterised deploy Choose a target, approve production.
Failure notification Tell the team when a build breaks.

A fifth exercise sets a nightly schedule.

1 / 2

Exercise 1: test and archive

Task. A Node project must run on any Linux agent. Install dependencies and run the tests, publish the JUnit report found at reports/junit.xml whether tests pass or fail, build a package with npm pack, and archive the resulting .tgz file only when the build succeeds. Abort the build after 15 minutes.

Hints. options { timeout(...) }, a post section inside the test stage, junit, archiveArtifacts.

Solution.

GROOVY
pipeline {
  agent { label 'linux' }
  options {
    timeout(time: 15, unit: 'MINUTES')
  }
  stages {
    stage('Test') {
      steps {
        sh 'npm ci && npm test'
      }
      post {
        always {
          junit 'reports/junit.xml'
        }
      }
    }
    stage('Package') {
      steps {
        sh 'npm pack'
      }
    }
  }
  post {
    success {
      archiveArtifacts artifacts: '*.tgz', fingerprint: true
    }
  }
}

Why. The report is published in post { always } of the test stage, because a failing test run is exactly when you need the report. The archive is in the pipeline-level post { success }, so a failed build does not leave a half-finished package. fingerprint: true lets Jenkins track where the file is used later (see Artifacts, Stash and Fingerprints).

Exercise 2: a build matrix

Task. Test on Node 20, 22 and 24 on both linux and windows agents, except the combination Node 20 on Windows, which is not supported.

Hints. matrix, axes, axis, excludes, and the axis values are available as environment variables inside.

Solution.

GROOVY
pipeline {
  agent none
  stages {
    stage('Test') {
      matrix {
        agent { label "${PLATFORM}" }
        axes {
          axis {
            name 'NODE_VERSION'
            values '20', '22', '24'
          }
          axis {
            name 'PLATFORM'
            values 'linux', 'windows'
          }
        }
        excludes {
          exclude {
            axis { name 'NODE_VERSION'; values '20' }
            axis { name 'PLATFORM'; values 'windows' }
          }
        }
        stages {
          stage('Run') {
            steps {
              echo "Node ${NODE_VERSION} on ${PLATFORM}"
            }
          }
        }
      }
    }
  }
}

Why. The matrix expands to 3 x 2 = 6 combinations, and the exclude removes one, leaving five parallel cells. agent none at the top means the cells choose their own agent through the axis value. See Stages, Parallel and Matrix.

Exercise 3: a parameterised deploy

Task. A deploy job takes three parameters: ENVIRONMENT (choice: staging or production), VERSION (text, default 1.0.0) and DRY_RUN (boolean, default true). When the environment is production, a person must approve before anything happens. When DRY_RUN is true, only print what would happen.

Hints. parameters, when { expression { ... } }, input.

Solution.

GROOVY
pipeline {
  agent { label 'linux' }
  parameters {
    choice(name: 'ENVIRONMENT', choices: ['staging', 'production'], description: 'Target')
    string(name: 'VERSION', defaultValue: '1.0.0', description: 'Version to deploy')
    booleanParam(name: 'DRY_RUN', defaultValue: true, description: 'Only print the plan')
  }
  stages {
    stage('Approve') {
      when { expression { params.ENVIRONMENT == 'production' } }
      steps {
        timeout(time: 1, unit: 'HOURS') {
          input message: "Deploy ${params.VERSION} to production?", ok: 'Deploy'
        }
      }
    }
    stage('Deploy') {
      steps {
        script {
          if (params.DRY_RUN) {
            echo "DRY RUN: would deploy ${params.VERSION} to ${params.ENVIRONMENT}"
          } else {
            sh './deploy.sh "$ENVIRONMENT" "$VERSION"'
          }
        }
      }
    }
  }
}

Why. The input step is wrapped in a timeout so a forgotten approval cannot hold the pipeline forever. The shell line uses single quotes, so the shell reads $ENVIRONMENT and $VERSION (parameters are also exported as environment variables) and a strange value cannot become part of the script text. Compare with the mistakes in Common Mistakes and Anti-Patterns.

On the very first run of a pipeline, Jenkins has not yet read the parameters block, so the job page may show "Build" instead of "Build with Parameters". After one run, the form appears.

Exercise 4: notify when a build fails

Task. Whenever the build fails, email [email protected] with the job name, build number and a link. Also send a message when a previously failing job returns to green.

Hints. post, the failure and fixed conditions, the mail step, env.BUILD_URL.

Solution.

GROOVY
pipeline {
  agent { label 'linux' }
  stages {
    stage('Build') {
      steps { sh 'make build' }
    }
  }
  post {
    failure {
      mail to: '[email protected]',
           subject: "FAILED: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
           body: "The build failed. Details: ${env.BUILD_URL}"
    }
    fixed {
      mail to: '[email protected]',
           subject: "FIXED: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
           body: "The build is green again. ${env.BUILD_URL}"
    }
  }
}

Why. failure runs when the build result is FAILURE. fixed runs when the current build succeeds and the previous one did not. The mail step needs a mail server configured in Jenkins. Chat tools such as Slack use a plugin step (for example slackSend) in the same place. Details of all post conditions are in Conditions and Post Actions.

Exercise 5: a nightly schedule

Task. Run the pipeline every weekday night around 2 a.m., spread over the hour so that many jobs do not all start at the same minute. Also check Git for new commits about every 5 minutes during the day (the second part is the older polling style).

Solution.

GROOVY
pipeline {
  agent { label 'linux' }
  triggers {
    cron('H 2 * * 1-5')
    pollSCM('H/5 * * * *')
  }
  stages {
    stage('Build') {
      steps { sh 'make build' }
    }
  }
}

Why. The five cron fields are minute, hour, day of month, month and day of week. H means "a hash-chosen value for this job", so H 2 * * 1-5 runs once during the 2 a.m. hour on Monday to Friday, at a minute that stays the same for this job but differs between jobs. H/5 * * * * means every 5 minutes with a job-specific offset. Webhooks are better than polling when you can use them: see Triggers: Webhooks, Polling and Schedules.

Stand-in 1: check your solution for required features

This helper tests solution text against a list of features per exercise. The model solutions are condensed into a few lines each. You can replace any entry in attempt with your own text and see which requirements are missing. It only checks that certain words appear, so it cannot tell whether your pipeline is correct in the real Jenkins sense.

JS Does the solution have the required features?

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

No output.

The condensed matrix attempt is missing its exclude block, which is exactly what the checker is for. Add one to the attempt text and run it again.

Stand-in 2: validate a cron schedule

This stand-in expands a cron expression into the values each field matches, so you can see what H, ranges and steps mean. The H value comes from a simple hash of a job name that I made up for this demo. Real Jenkins uses its own hash, so your real minute will differ, but the behavior is the same: a stable per-job value inside the range.

JS Expand and validate cron expressions

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

No output.

The two invalid lines show what a typo costs: hour 25 is out of range, and four fields instead of five is not a schedule. Jenkins reports such mistakes when you save the job, but catching them early is cheap.

How to practice further

  • Take any project you own and write its pipeline from scratch. Then compare it with the pipelines in Project: CI for a Java Application.
  • Change one exercise: make the matrix three axes, add a when to the notification, or split the schedule into two triggers.
  • Break each solution on purpose (remove the timeout, use double quotes in the deploy script) and run the stand-in linter from Common Mistakes and Anti-Patterns.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should junit be placed so reports are published even when tests fail?

    always runs regardless of the result, which is when you most need the report.
  2. 2. A matrix has axes of 3 and 2 values and one exclude. How many cells run?

    3 x 2 = 6 combinations, and the exclude removes one, so 5 cells.
  3. 3. What does H 2 * * 1-5 mean?

    H picks a stable hashed minute for the job, hour is 2, and 1-5 is Monday to Friday.
  4. 4. Why wrap an input step in timeout?

    Without a limit, a build waiting for approval can wait indefinitely.

Summary

  • Put report publishing in post { always } and package archiving in post { success }.
  • A matrix multiplies axis values, and excludes removes combinations.
  • Parameters, when with expression, and a guarded input give a safe deploy.
  • post { failure } and post { fixed } handle notifications; H in cron spreads load.
  • Practice by writing pipelines from scratch, then checking them against a linter.

Next, test your knowledge with Jenkins Interview Questions.