shell - k8s平滑移除node

2021-07-05
#!/bin/bash
node_name=$1
if [[ -z ${node_name} ]];then
    echo "please input node name"
    exit
fi
node_ip=$(kubectl get node -o wide | grep ${node_name} | awk '{print $6}')

kubectl cordon ${node_name}
namespaces=$(kubectl get namespaces | awk '{print $1}' )

for namespace in ${namespaces}
do
    kubectl -n ${namespace} get pods -o wide | grep ${node_name} |  awk '$6!="'${node_ip}'"' | grep Running | awk '{print $1}' | while read line
    do
        last_one_split_name=$(echo ${line} | awk -F '-' '{print $NF}')
        last_two_split_name=$(echo ${line} | awk -F '-' '{print $(NF-1)}')
        if [[ $(echo ${last_one_split_name} | wc -c) -gt 2  ]];then
            deployment_name=$(echo ${line} | sed "s/-${last_two_split_name}-${last_one_split_name}//g")
            now_terminationGracePeriodSeconds=$(kubectl -n ${namespace} get deployment ${deployment_name} -o yaml | grep 'terminationGracePeriodSeconds' | grep -v apiVersion | grep -Po [0-9]+)
            ((to_terminationGracePeriodSeconds=${now_terminationGracePeriodSeconds} + 1))
            echo now $deployment_name ${now_terminationGracePeriodSeconds} ${to_terminationGracePeriodSeconds}
            kubectl -n ${namespace} patch deployment ${deployment_name} -p '{"spec":{"template":{"spec":{"terminationGracePeriodSeconds":'${to_terminationGracePeriodSeconds}'}}}}'
        else
            statefulsets_name=$(echo ${line} | sed "s/-${last_one_split_name}//g")
            now_terminationGracePeriodSeconds=$(kubectl -n ${namespace} get statefulsets ${statefulsets_name} -o yaml | grep 'terminationGracePeriodSeconds' | grep -v 'apiVersion'| grep -Po [0-9]+)
            ((to_terminationGracePeriodSeconds=${now_terminationGracePeriodSeconds} + 1))
            echo now2 $statefulsets_name ${now_terminationGracePeriodSeconds} ${to_terminationGracePeriodSeconds}
            kubectl -n ${namespace} patch statefulsets ${statefulsets_name} -p '{"spec":{"template":{"spec":{"terminationGracePeriodSeconds":'${to_terminationGracePeriodSeconds}'}}}}'
        fi
    done
done

标题:shell - k8s平滑移除node
地址:https://blog.nijianqiang.xyz:8443/articles/2021/07/05/1625473653703.html