Skip to content

Instantly share code, notes, and snippets.

@hui-zheng
Last active March 5, 2020 16:39
Show Gist options
  • Save hui-zheng/9a5e33c23d2aedc64de2e761c2842f09 to your computer and use it in GitHub Desktop.
Save hui-zheng/9a5e33c23d2aedc64de2e761c2842f09 to your computer and use it in GitHub Desktop.
kubernetes DevOps Operation Script
BY_LIST_FILE="NONE"
COMPLETED="1/."
AGE="3"
NAME_PATTERN=".*"
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-c|--completed)
COMPLETED="$2\/."
shift # past argument
shift # past value
;;
-t|--age)
AGE="$2"
shift # past argument
shift # past value
;;
-n|--name)
NAME_PATTERN="$2"
shift # past argument
shift # past value
;;
-l|--list)
BY_LIST_FILE="$2"
shift # past argument
shift # past value
;;
# -f|--force)
# FORCE="TRUE"
# shift # past argument
# ;;
# -p|--prep)
# PREP="$4"
# shift # past argument
# ;;
# --default)
# DEFAULT=YES
# shift # past argument
# ;;
*) # unknown option
POSITIONAL+=("$1") # save it in an array for later
shift # past argument
;;
esac
done
if [ "$BY_LIST_FILE" = "NONE" ]
then
AGE_PATTERN=$(echo "([$AGE-9]|[1-4][0-9]|50)d")
# if age = 0, then also remove jobs less than a day
if [ "$AGE" = "0" ]
then
AGE_PATTERN="${AGE_PATTERN}|."
fi
echo "CLEAN UP JOBS with COMPLETED=$COMPLETED; and AGE>=$AGE (AGE PATTERN $AGE_PATTERN); and job NAME PATTERN $NAME_PATTERN"
JOB_LIST=$(kubectl get jobs --sort-by=.metadata.creationTimestamp | awk -v completed="$COMPLETED" '$2 ~ completed' | awk -v pattern="$AGE_PATTERN" '$4 ~ pattern' | awk -v pattern="$NAME_PATTERN" '$1 ~ pattern' | awk '{print $1}')
else
JOB_LIST=$(cat $BY_LIST_FILE)
fi
l=1
size=128
TOTAL=$(echo $JOB_LIST | wc -w)
echo ">>>>>> To delete $TOTAL jobs in total"
while (( $(echo "$l <= $TOTAL" | bc -l) ))
do
le=$(echo "$l + $size" | bc -l)
echo ">>>>>> Fetching job $l to $le (size $size ) of $TOTAL"
#list jobs to delete
echo $JOB_LIST | cut -d' ' -f${l}-${le}
#delete jobs
kubectl delete --cascade=true --timeout=6s job $( echo $JOB_LIST | cut -d' ' -f${l}-${le} )
l=$(echo "$le + 1" | bc -l)
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment