T1级,生产环境事故—Shell脚本一键备份K8s的YAML文件

时间:2024-04-23 07:08:15
#/bin/bash # # K8S_YAML_SHELL_DIR:记录脚本和resources.txt存放位置,移动是需要修改其值 # 一键备份K8s集群YAML文件脚本 # resources.txt文件,编写需要备份资源 # # 定时任务示例 # 0 0 */1 * * /usr/bin/bash /a/k8s-yaml-all-bak/start.sh > /a/k8s-yaml-all-bak/yaml_bak.logs 2>&1 # 后台运行示例 # nohup /usr/bin/bash /a/k8s-yaml-all-bak/start.sh > /a/k8s-yaml-all-bak/yaml_bak.logs 2>&1 & # 当前时间 DATE=`date +%Y-%m-%d--%H-%M-%S` # 备份路径 K8S_YAML_BACKUP_DIR="/opt/k8s_yaml_bak" # 脚本存放目录 K8S_YAML_SHELL_DIR="/a/k8s-yaml-all-bak" if [ ! -d $K8S_YAML_BACKUP_DIR ];then mkdir -p $K8S_YAML_BACKUP_DIR fi # 获取备份资源 if [ -f ${K8S_YAML_SHELL_DIR}/resources.txt ];then RESOURCES=`cat ${K8S_YAML_SHELL_DIR}/resources.txt` # 判断资源文件是否为空 if [[ $RESOURCES == "" ]]; then echo "${DATE} ${K8S_YAML_SHELL_DIR}/resources.txt 文件为空,请输入资源名称" exit 1 fi else echo "resources.txt文件,不存在!" exit 1 fi # 每次备份单独创建一个家目录+时间 mkdir -p ${K8S_YAML_BACKUP_DIR}/k8s-${DATE} # 获取家目录 GET_HOME_DIR=`ls -l ${K8S_YAML_BACKUP_DIR} | tail -n 1 | awk '{print $9}'` echo "备份路径:$K8S_YAML_BACKUP_DIR/$GET_HOME_DIR" # 获取k8s名称空间 NAMESPACE=`kubectl get ns | awk '{print $1}' | tail -n +2` dump_yaml(){ # 遍历NS for NS in $NAMESPACE ;do # 创建NS备份目录 mkdir -p ${K8S_YAML_BACKUP_DIR}/${GET_HOME_DIR}/${NS} # 过滤NS(kube-public、kube-system) if [[ $NS != "kube-public" && $NS != "kube-system" && $NS != "csdr" && $NS != "kube-node-lease" ]]; then # 遍历k8s资源 for RESOURCE in $RESOURCES; do # 创建资源目录 mkdir -p ${K8S_YAML_BACKUP_DIR}/${GET_HOME_DIR}/${NS}/${RESOURCE} # 遍历对应资源名称 for RESOURCE_NAME in $(kubectl get $RESOURCE -n $NS | awk '{print $1}' | tail -n +2);do DATE_YAML=`date +%Y-%m-%d--%H:%M:%S` echo "${DATE_YAML} 导出YAML: ${NS} ${RESOURCE} ${RESOURCE_NAME} " # 导出对应名称空间下对应资源的yaml kubectl get ${RESOURCE} ${RESOURCE_NAME} -n ${NS} -o yaml > ${K8S_YAML_BACKUP_DIR}/${GET_HOME_DIR}/$NS/${RESOURCE}/${RESOURCE_NAME}.yaml echo "" done done fi done } del_yaml(){ for DIR_NAME in $(find $K8S_YAML_BACKUP_DIR -type d -mtime +7);do DATE_YAML=`date +%Y-%m-%d--%H:%M:%S` echo "${DATE_YAML} 删除:$DIR_NAME" > ${K8S_YAML_SHELL_DIR}/del-yaml.logs rm -rf $DIR_NAME >> ${K8S_YAML_SHELL_DIR}/del-yaml.logs echo "" >> ${K8S_YAML_SHELL_DIR}/del-yaml.logs done } dump_yaml del_yaml