shell - 自动增加PDB

2023-10-26
#!/bin/bash
# 每日对所有副本数大于1的deployment自动创建PDB。
k8s_cluster="k8s-v6"
namespaces=$(/usr/local/bin/kubectl  --kubeconfig ~/.kube/${k8s_cluster} get namespaces | grep -v NAME| awk '{print $1}' | grep paas )
for namespace in ${namespaces}
do
    # 清理无效PDB
    /usr/local/bin/kubectl --kubeconfig ~/.kube/${k8s_cluster} -n ${namespace} get poddisruptionbudget | awk '$4==0' | awk '{print $1}' | while read pdb
    do
        /usr/local/bin/kubectl --kubeconfig ~/.kube/${k8s_cluster} -n ${namespace} delete poddisruptionbudget ${pdb}
    done
    # 多副本Deployment创建PDB
    /usr/local/bin/kubectl --kubeconfig ~/.kube/${k8s_cluster} -n ${namespace} get deployments.apps --show-labels | egrep -v "/1|/0|NAME" | awk '{print $1,$NF}' | while read deployments
    do
        name=$(echo $deployments | awk '{print $1}')
        labels=$(echo $deployments | awk '{print $2}')
        echo ${name} ${labels}
        /usr/local/bin/kubectl --kubeconfig ~/.kube/${k8s_cluster} -n ${namespace} get poddisruptionbudget ${name} >> /dev/null
        if [[ $? -ne 0 ]];then
            /usr/local/bin/kubectl --kubeconfig ~/.kube/${k8s_cluster} -n ${namespace} create poddisruptionbudget ${name} --selector=${labels} --min-available=1
        fi
        sleep 1
    done
done