Skip to content

Instantly share code, notes, and snippets.

@jcjveraa
Last active November 9, 2024 21:03
Show Gist options
  • Save jcjveraa/c4c0989a3d4e27d59f0fb221ccc48421 to your computer and use it in GitHub Desktop.
Save jcjveraa/c4c0989a3d4e27d59f0fb221ccc48421 to your computer and use it in GitHub Desktop.
Change the default storage class in kubernetes with a single command
#!/bin/bash
## When doing some experimenting, it can be usefull to be able to quickly change the default storage class in k8s.
## This script does that - it will change the default storage class to the one supplied on the commandline, erroring out
## in case this storage class does not exist, or if the changing of the storage class failed.
## Disclaimer/for openness: I thought of creating this script, but ChatGPT did most of the grunt work of realizing it.
# Check if storage class name is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <storage-class-name> - this storage class will be set as the default kubernetes storage class, and the previous default is removed"
exit 1
fi
NEW_DEFAULT_STORAGE_CLASS=$1
# Check if the new default storage class exists
if kubectl get storageclass "$NEW_DEFAULT_STORAGE_CLASS" &> /dev/null; then
echo "Storage class '$NEW_DEFAULT_STORAGE_CLASS' exists."
else
echo "Error: Storage class '$NEW_DEFAULT_STORAGE_CLASS' does not exist."
exit 1
fi
# Find the current default storage class, if any
CURRENT_DEFAULT_STORAGE_CLASS=$(kubectl get storageclass -o jsonpath='{.items[?(@.metadata.annotations.storageclass\.kubernetes\.io/is-default-class=="true")].metadata.name}')
if [ -n "$CURRENT_DEFAULT_STORAGE_CLASS" ]; then
echo "Current default storage class is '$CURRENT_DEFAULT_STORAGE_CLASS'. Removing default annotation..."
# Remove the default annotation from the current default storage class
kubectl patch storageclass "$CURRENT_DEFAULT_STORAGE_CLASS" \
-p '{"metadata": {"annotations": {"storageclass.kubernetes.io/is-default-class": "false"}}}'
echo "Default annotation removed from '$CURRENT_DEFAULT_STORAGE_CLASS'."
else
echo "No current default storage class found."
fi
# Set the new storage class as default
echo "Setting '$NEW_DEFAULT_STORAGE_CLASS' as the new default storage class..."
kubectl patch storageclass "$NEW_DEFAULT_STORAGE_CLASS" \
-p '{"metadata": {"annotations": {"storageclass.kubernetes.io/is-default-class": "true"}}}'
CURRENT_DEFAULT_STORAGE_CLASS=$(kubectl get storageclass -o jsonpath='{.items[?(@.metadata.annotations.storageclass\.kubernetes\.io/is-default-class=="true")].metadata.name}')
if [ "$NEW_DEFAULT_STORAGE_CLASS" == "$CURRENT_DEFAULT_STORAGE_CLASS" ]; then
echo "'$NEW_DEFAULT_STORAGE_CLASS' is now the default storage class."
else
echo "Error: Expected '$NEW_DEFAULT_STORAGE_CLASS' to be the default storage class, but '$CURRENT_DEFAULT_STORAGE_CLASS' was found as the default storage class."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment