Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 40 ยท Deployment and Delivery

Deployment Pipelines and Approvals

Build a Jenkins deployment pipeline with environments, input approvals, milestones, locks, rollback, release tags, notifications and artifact promotion.

Continuous integration answers "does the code build and pass its tests". Continuous delivery answers the next question: "can we put this build in front of users safely, repeatably and on demand". A deployment pipeline is the sequence of stages that takes one tested build through environments such as staging and production, with checks, approvals and a way back.

This lesson shows the building blocks Jenkins gives you: stages per environment, the input step for human approval, milestone and lock to avoid collisions, rollback, release tagging and notifications. The real commands are read-only; the runnable examples are Node stand-ins for the control flow, because Jenkins and your servers cannot run on this site.

One build, many environments

Build once Create one artifact and reuse it.
Staging Deploy automatically and test.
Approval A person confirms production.
Production Same artifact, new target.

Never rebuild between environments.

1 / 2

Build once, promote the same artifact

The most important rule: the thing you deploy to production is the thing you tested in staging. If each environment rebuilds the code, a changed dependency or a new base image can sneak in between, and your tests no longer prove anything. So the build stage creates one immutable artifact (a jar, a tarball or a container image with a unique tag), and later stages only deploy it.

Common ways to carry the artifact forward are archiving it (see Artifacts, Stash and Fingerprints), pushing it to a registry with a version tag, or uploading it to an artifact repository. Promotion then means "point the next environment at that same version", not "build again".

Give every artifact a traceable version, such as the build number plus the short commit hash. You will use it for deployment, rollback and the release tag.

Environments as stages

A simple delivery pipeline has one stage per environment. The environment name and target come from variables, so the deploy script is the same everywhere (read-only):

GROOVY
pipeline {
  agent { label 'deploy' }
  options { timeout(time: 1, unit: 'HOURS') }
  environment {
    VERSION = "${env.BUILD_NUMBER}"
  }
  stages {
    stage('Build') {
      steps {
        sh './build.sh "$VERSION"'
        archiveArtifacts artifacts: 'dist/*.tar.gz', fingerprint: true
      }
    }
    stage('Deploy to staging') {
      steps {
        sh './deploy.sh staging "$VERSION"'
        sh './smoke-test.sh https://staging.example.com'
      }
    }
    stage('Approve production') {
      steps {
        input message: "Deploy version ${VERSION} to production?",
              ok: 'Deploy',
              submitter: 'release-managers'
      }
    }
    stage('Deploy to production') {
      steps {
        lock('production') {
          sh './deploy.sh production "$VERSION"'
          sh './smoke-test.sh https://www.example.com'
        }
      }
    }
  }
}

The smoke-test.sh after each deploy is what turns "the command exited 0" into "the service actually answers". Without a check like that, a broken deployment is only found by users.

The input step: human approval

input pauses the pipeline and shows a prompt on the build page. Someone with permission clicks the button (or aborts) to continue. Useful options:

  • message is the question shown to the approver.
  • ok changes the label of the confirm button.
  • submitter limits who may approve, as a comma-separated list of user names or groups.
  • parameters asks for values at approval time, for example a ticket number or a choice of region.
GROOVY
def answers = input(
  message: 'Release details',
  ok: 'Go',
  parameters: [
    string(name: 'TICKET', description: 'Change ticket'),
    booleanParam(name: 'NOTIFY_CUSTOMERS', defaultValue: false)
  ]
)
echo "Approved with ticket ${answers.TICKET}"

Two practical rules. First, do not hold an agent while waiting. A human may take hours, and the executor would sit idle. Declare agent none at the top and allocate agent only for the stages that need a machine, or place the input in a stage with agent none:

GROOVY
stage('Approve production') {
  agent none
  options { timeout(time: 4, unit: 'HOURS') }
  steps {
    input message: 'Deploy to production?', submitter: 'release-managers'
  }
}

Second, always wrap approvals in a timeout, so an unanswered request ends cleanly instead of waiting for weeks. When a timeout expires, the build is aborted.

Milestones and locks

Two steps protect you from deployment collisions.

lock (from the Lockable Resources plugin) lets only one build use a named resource at a time. Two pipelines deploying to production take turns instead of running over each other. A job can wait for the lock, and you can limit how long it waits.

milestone is built into Pipeline. Once a newer build passes a milestone, older builds that have not yet reached it are aborted. This stops an out-of-date build 41 from overtaking build 42 and deploying old code last:

GROOVY
stage('Deploy to staging') {
  steps {
    milestone(ordinal: 10, label: 'before staging')
    sh './deploy.sh staging "$VERSION"'
  }
}

Use milestones around stages where order matters, and put the lock around the deploy itself.

Rollback

Things go wrong, so decide the way back before you need it. The reliable pattern follows from "build once":

  • Keep the previous versions available (registry tags, archived artifacts).
  • Make the deploy script take a version. A rollback is then just the same script with an older version.
  • Verify after rollback with the same smoke tests.

You can run it automatically in post { failure { ... } } for the deploy stage, or offer it as a parameterized job so an operator can run it by hand:

GROOVY
parameters {
  string(name: 'VERSION_TO_DEPLOY', description: 'Version to deploy or roll back to')
}

Databases are the hard part. A schema change that removes a column cannot simply be undone by deploying old code, so make migrations backward compatible (add first, remove later) and treat them as a separate, reviewed step.

Release strategies in one page

How the new version replaces the old matters as much as when:

  • Rolling replaces instances a few at a time. Simple, and the default in many platforms.
  • Blue-green runs two identical environments. You deploy to the idle one, test it, then switch traffic over. Rollback is switching back.
  • Canary sends a small share of traffic (say 5%) to the new version, watches errors and latency, then increases the share.

Jenkins is the orchestrator: it runs the commands that call your load balancer, Kubernetes or deployment tool. See the Git deployment strategies lesson for how the branch side of this looks.

Tagging and notifications

After a successful production deployment, tag the commit so you can find exactly what was released:

GROOVY
post {
  success {
    sh '''
      git tag -a "release-${VERSION}" -m "Production release ${VERSION}"
      git push origin "release-${VERSION}"
    '''
  }
}

(Pushing needs credentials in the job, see Credentials and Secrets.) People should also learn the outcome without watching the console. With the Slack plugin you can call slackSend, and the built-in mail step sends email:

GROOVY
post {
  success {
    slackSend channel: '#releases', color: 'good',
              message: "Deployed ${env.JOB_NAME} ${VERSION} to production"
  }
  failure {
    mail to: '[email protected]',
         subject: "Deploy failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
         body: "See ${env.BUILD_URL}"
  }
}

Keep notifications short and link to the build. Notify on state changes and failures; a message on every build is noise people stop reading. For more on post, see Conditions and Post Actions.

A stand-in deployment pipeline with an approval gate

The first stand-in models the flow: build, deploy to staging, smoke test, wait for an approval from an allowed person, deploy to production. A function plays the part of the human. It does not talk to any server; it shows how a gate stops or releases the flow, including the rule that only a named submitter may approve.

JS A stand-in pipeline with an approval gate

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

No output.

Only build 42 reaches production. Build 43 is blocked because sam is not a submitter, 44 times out, and 45 never gets to the approval because staging failed first. That ordering is the value of a pipeline: each gate protects the next one.

A stand-in for milestones and rollback

The second stand-in shows what milestone does and how a rollback is "the same deploy with an older version". Build 41 and 42 start close together; 42 passes the milestone first, so 41 is cancelled. Then production fails after a deploy and the pipeline restores the previous version from a list of known releases.

JS A stand-in for milestones and rollback

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

No output.

The rollback needed no special tooling because the earlier version still existed and the deploy script takes a version as input.

Rehearse the rollback in staging on a normal day. A rollback you have never run will fail at the worst moment.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should production receive the same artifact that passed staging?

    A rebuild can pull in different dependencies or base images. Promoting one immutable artifact keeps the test results meaningful.
  2. 2. What does the 'submitter' option of the input step do?

    submitter takes users or groups who are allowed to answer the input prompt.
  3. 3. What problem does 'milestone' solve?

    After a newer build passes a milestone, older builds that have not yet reached it are cancelled. lock is the tool for mutual exclusion.
  4. 4. Why should an approval stage use 'agent none' and a timeout?

    A person may take hours to answer. Without an agent the executor is free for other builds, and the timeout prevents a build from waiting forever.
  5. 5. In a blue-green deployment, what is a rollback?

    The old environment is still running, so sending traffic back to it restores the previous version quickly.

Summary

  • Build once, then promote the same versioned artifact through the environments.
  • Use one stage per environment, run smoke tests after each deploy, and keep the deploy script identical across environments.
  • input adds a human approval (with submitter, ok and parameters); keep it off agents and wrap it in a timeout.
  • lock serializes deployments to a resource, and milestone stops older builds from overtaking newer ones.
  • Plan rollback as "deploy the previous version", tag releases, and send short notifications with slackSend or mail.

Next, see how Jenkins compares with other CI systems in Jenkins vs GitHub Actions, GitLab CI and Others.