forked from Nietzen/k8s-cleanup
-
Notifications
You must be signed in to change notification settings - Fork 1
/
k8s-clean.sh
executable file
·38 lines (31 loc) · 1.15 KB
/
k8s-clean.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/bin/bash
# DAYS defaults to 7
max=$DAYS
# Get rs, filter by days, filter by empty rs and select rs older than $max days
emptyReplicaSets=$(kubectl get rs --all-namespaces | \
grep -oE '^[a-zA-Z0-9-]+\s+[a-zA-Z0-9-]+(\s+[0-9]+){4}d' | sed 's/d$//g' | \
grep -E '(0\s+){3}' | \
awk -v max=$max '$6 > max {print $1 "|" $2}')
# Loop through empty replica sets and delete them
for rs in $emptyReplicaSets; do
IFS='|' read namespace replicaSet <<< "$rs";
kubectl -n $namespace delete rs $replicaSet;
sleep 0.25
done
# Get finished jobs older than 1h
finishedJobs=$(kubectl get jobs --all-namespaces | awk 'IF $4 == 1 && $5 ~ /h|d/ {print $1 "|" $2}')
# Loop through jobs and delete them
for job in $finishedJobs; do
IFS='|' read namespace oldJob <<< "$job";
kubectl -n $namespace delete job $oldJob;
sleep 0.25
done
# Get unrecycled evicted pods older than 1h
evictedPods=$(kubectl get pods --all-namespaces | grep 'Evicted' | \
awk 'IF $6 ~ /h|d/ {print $1 "|" $2}')
# Loop through evicted pods and delete them
for pod in $evictedPods; do
IFS='|' read namespace evictedPod <<< "$pod";
kubectl -n $namespace delete pod $evictedPod;
sleep 0.25
done