Skip to main content
In this guide, we’ll enhance a Jenkins pipeline to deploy a Kubernetes application with proper rollout checks and automatic rollback on failure. By combining vulnerability scanning, dynamic image updates, and robust deployment scripts, you ensure that failed releases don’t leave your cluster in an unhealthy state.

Problem Statement

Our initial pipeline applied an updated Deployment manifest (including runAsUser: 100), but we never verified the rollout status. The kubectl apply command succeeded, yet the pods failed to start due to a misconfiguration. We need to:
  • Scan manifests for security issues
  • Apply or update the deployment
  • Monitor rollout status
  • Roll back automatically on failure

Kubernetes Manifest: k8s_deployment_service.yaml

Initial Jenkinsfile Stages

Without kubectl rollout status, Kubernetes errors during pod startup don’t fail the pipeline, leading to “silent” broken deployments.

Enhanced Jenkinsfile: Parallel Deploy and Rollout

We replace the simple apply step with two parallel branches:
  1. Deployment: applies or updates the manifest
  2. Rollout_Status: monitors the rollout and triggers rollback on failure

Deployment Script: k8s-deployment.sh

This script replaces the placeholder image name, then either creates a new Deployment or updates the existing one with --record=true to capture change-cause.
Ensure the Jenkins service account has get, create, update, and rollout permissions on the target namespace.

Rollout Status Script: k8s-deployment-rollout-status.sh

After a short wait, this script checks the rollout status with a timeout. On failure, it issues a rollback to the previous revision.

Jenkinsfile Environment Variables

Define all deployment-specific variables at the top of your Jenkinsfile for easy maintenance:

Pushing Changes

Once scripts and Jenkinsfile are updated, commit and push:
The image shows a GitHub Desktop interface with a repository named "devsecops-k8s-demo" and a notification indicating that changes are being pushed to the origin. The desktop taskbar is visible at the bottom.

Pipeline & Cluster Verification

In the pipeline logs for k8s-deployment.sh:
The rollout branch confirms:
On the Kubernetes cluster:
If a pod fails to become Running, the rollback script will revert to the previous revision.

Viewing Rollout History

Inspect recorded change causes for debugging:
Using --record=true captures the exact kubectl command and Git commit, making audits and rollbacks straightforward.

Watch Video

Practice Lab