Rollback a K8S deployment


This is a nice ’lil script for rolling back a k8s deployment, using the excellent fzf utility.

If you don’t have access to fzf, the bash select compound command can be used instead, though you do lose the nice declarative style seen below.

#!/usr/bin/env bash

# choose a context
ctx=$(
  kubectl config get-contexts -o name |
    awk '{print $1}' |
    fzf --prompt "Select a k8s context "
)
[[ -z "$ctx" ]] && echo "No k8s context selected, exiting." && exit 0

# choose a namespace
name_space=$(
  kubectl --context "$ctx" get namespace |
    awk 'NR!=1 {print $1}' |
    fzf --prompt "Select a k8s namespace "
)
[[ -z "$name_space" ]] && echo "No k8s namespace selected, exiting." && exit 0

# pick a deployment
k8s_deployment=$(
  kubectl --context "$ctx" -n "$name_space" get deployments |
    awk 'NR!=1 {print $1}' |
    fzf --prompt "Select a k8s deployment "
)
[[ -z "$k8s_deployment" ]] && echo "No k8s deployment selected, exiting." && exit 0

# pick a revision to roll back to
k8s_revision=$(
  kubectl --context "$ctx" -n "$name_space" rollout history deployment "$k8s_deployment" |
    # show the full deployments history menu to the user, so they have context
    fzf --tac --prompt "Select a revision number to roll back to (highest number is most recent deployment) " |
    # get the first column, which is the revision number
    awk '{print $1}'
)
[[ -z "$k8s_revision" ]] && echo "No k8s revision selected, exiting." && exit 0

# generate the command to undo the deployment
final_command="kubectl --context=$ctx -n=$name_space rollout undo deployment/$k8s_deployment --to-revision=$k8s_revision"
echo "Copy and run this command to undo the deployment:"
echo "$final_command"

# exit cleanly
exit 0