How to Perform an Interactive Kubernetes Deployment Rollback: A Step-by-Step Guide

How to Perform an Interactive Kubernetes Deployment Rollback: A Step-by-Step Guide
Photo by Growtika / Unsplash

When deploying applications in Kubernetes, unexpected issues can sometimes arise. Knowing how to perform a quick and efficient rollback is essential for maintaining the stability and reliability of your services. In this blog post, we'll explore how to create an interactive bash script for rolling back Kubernetes deployments, ensuring you're prepared to handle any deployment hiccups.

Why Rollbacks are Crucial in Kubernetes

Rollbacks allow you to revert to a previous version of your application quickly. This is especially important in production environments where uptime and reliability are critical. By having an automated and interactive rollback script, you can minimize downtime and ensure your applications continue running smoothly.

Creating an Interactive Rollback Script

To streamline the rollback process, we'll create a bash script that guides you through each step, ensuring you select the correct namespace, deployment, and revision. This interactive approach minimizes errors and speeds up the rollback process.

Step 1: Setting Up ANSI Colors and Styles

First, we define ANSI colors and styles for stylish output, making it easier to read and understand the script's prompts and messages.

#!/bin/bash

# ANSI colors and styles for stylish output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
UNDERLINE='\033[4m'
NC='\033[0m' # No Color

Step 2: Print Styled Messages and Headers

We create functions to print messages and headers in different styles and colors, enhancing the user experience.

# Function to print styled messages
print_message() {
  color="$1"
  text="$2"
  echo -e "${color}${text}${NC}"
}

# Function to print section headers
print_header() {
  echo -e "${BLUE}${BOLD}${UNDERLINE}$1${NC}"
}

Step 3: Namespace Selection

The script prompts the user to enter a Kubernetes namespace or use 'default' if none is specified. It validates the namespace to ensure it exists.

# Function to get namespace and validate it
get_namespace() {
  print_header "Namespace Selection"
  print_message "$YELLOW" "Enter the Kubernetes namespace or press Enter for 'default':"
  read namespace
  if [ -z "$namespace" ]; then
    namespace="default"
  fi
  # Check if the namespace exists
  if ! kubectl get namespace "$namespace" > /dev/null 2>&1; then
    print_message "$RED" "Namespace '$namespace' does not exist. Please enter a valid namespace."
    get_namespace
  else
    print_message "$GREEN" "Using namespace '$namespace'."
  fi
}

Step 4: Listing and Validating Deployments

Next, the script lists all deployments in the selected namespace and prompts the user to select one. It validates the selection to ensure the deployment exists.

# Function to list deployments in the namespace
list_deployments() {
  print_header "Available Deployments"
  if ! kubectl get deployments -n "$namespace" --no-headers | awk '{print $1}'; then
    print_message "$RED" "No deployments found in namespace '$namespace'."
    exit 1
  fi
}

# Function to get deployment name and validate it
get_deployment_name() {
  print_message "$YELLOW" "Enter the name of the Kubernetes deployment you want to rollback:"
  read deployment
  # Check if the deployment exists in the given namespace
  if ! kubectl get deployment "$deployment" -n "$namespace" > /dev/null 2>&1; then
    print_message "$RED" "Deployment '$deployment' does not exist in namespace '$namespace'. Please enter a valid deployment name."
    get_deployment_name
  else
    print_message "$GREEN" "Selected deployment: $deployment"
  fi
}

Step 5: Listing and Validating Revisions

The script lists all available revisions for the selected deployment and prompts the user to enter the desired revision number. It validates the revision number to ensure it is numeric.

# Function to list revisions
list_revisions() {
  print_header "Deployment Revisions"
  kubectl rollout history deployment "$deployment" -n "$namespace"
}

# Function to get revision number and validate it
get_revision_number() {
  print_message "$YELLOW" "Enter the revision number to which you want to rollback:"
  read revision
  # Simple numeric check
  if ! [[ "$revision" =~ ^[0-9]+$ ]]; then
    print_message "$RED" "Please enter a valid numeric revision."
    get_revision_number
  else
    print_message "$GREEN" "Selected revision: $revision"
  fi
}

Step 6: Confirming and Performing the Rollback

The script confirms with the user before performing the rollback, ensuring that the user has reviewed and approved the action.

# Function to confirm and perform rollback
confirm_and_rollback() {
  print_header "Rollback Confirmation"
  print_message "$YELLOW" "Confirm rollback of $deployment to revision $revision in namespace $namespace? (yes/no)"
  read confirmation
  if [[ "$confirmation" == "yes" ]]; then
    print_message "$YELLOW" "Rolling back $deployment to revision $revision in namespace $namespace..."
    kubectl rollout undo deployment "$deployment" -n "$namespace" --to-revision="$revision"
    print_message "$GREEN" "Rollback completed."
  else
    print_message "$RED" "Rollback canceled."
  fi
}

Step 7: Monitoring Deployment Status

After initiating the rollback, the script monitors the deployment status to ensure it completes successfully. If the deployment fails, the script offers the option to rollback to a previous stable state.

# Function to monitor the deployment status
monitor_deployment() {
  print_header "Monitoring Deployment Status"
  kubectl rollout status deployment "$deployment" -n "$namespace"
  if [ $? -eq 0 ]; then
    print_message "$GREEN" "Deployment is successful."
  else
    print_message "$RED" "Deployment failed. Initiate rollback? (yes/no)"
    read rollback_confirmation
    if [[ "$rollback_confirmation" == "yes" ]]; then
      confirm_and_rollback
    else
      print_message "$RED" "No rollback performed."
    fi
  fi
}

Putting It All Together

The complete interactive rollback script integrates all these functions, providing a seamless and user-friendly experience for rolling back Kubernetes deployments.

# Main function to perform the rollback
rollback_deployment() {
  get_namespace
  list_deployments
  get_deployment_name
  list_revisions
  get_revision_number
  monitor_deployment
}

# Start the script
rollback_deployment

Conclusion

By following this step-by-step guide and using the provided bash script, you can efficiently manage rollbacks in your Kubernetes deployments. This interactive approach ensures that you make informed decisions during rollbacks, reducing the risk of errors and maintaining the stability of your applications.

Remember, having a rollback strategy is essential for any robust deployment pipeline. Implementing scripts like this one can save you time and headaches when things go south. Stay prepared, and keep your Kubernetes deployments running smoothly!

Subscribe to codingwithalex

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe