#!/bin/bash

# 定义备份目录
BACKUP_DIR="/data/backupdata/k8s"
K8S_CONFIG_BACKUP="${BACKUP_DIR}/k8s_config_backup_$(date +%Y%m%d%H%M%S).tar.gz"
ETCD_BACKUP="${BACKUP_DIR}/etcd_backup_$(date +%Y%m%d%H%M%S).db"
TEMP_DIR="${BACKUP_DIR}/temp_$(date +%Y%m%d%H%M%S)"

# 创建备份目录和临时目录(如果不存在)
mkdir -p ${BACKUP_DIR}
mkdir -p ${TEMP_DIR}

# 备份Kubernetes配置数据到临时目录
kubectl get all --all-namespaces -o yaml > ${TEMP_DIR}/k8s_all_config.yaml

# 压缩Kubernetes配置数据
tar -czvf ${K8S_CONFIG_BACKUP} -C ${TEMP_DIR} k8s_all_config.yaml

# 删除临时目录
rm -rf ${TEMP_DIR}

# 备份etcd数据
ETCDCTL_API=3 etcdctl snapshot save ${ETCD_BACKUP} \
  --endpoints=https://10.1.xx.xx:2379 \
  --cacert=/etc/kubernetes/ssl/ca.pem \
  --cert=/etc/kubernetes/ssl/etcd.pem \
  --key=/etc/kubernetes/ssl/etcd-key.pem

# 清理旧备份,只保留最近20天的备份
find ${BACKUP_DIR} -type f -name '*.tar.gz' -mtime +20 -exec rm {} \;
find ${BACKUP_DIR} -type f -name '*.db' -mtime +20 -exec rm {} \;


# 输出备份完成信息
echo "Kubernetes配置数据和etcd数据备份完成:${K8S_CONFIG_BACKUP}, ${ETCD_BACKUP}"

crontab -e

0 2 * * * /path/to/backup_k8s.sh >> /var/log/backup_k8s.log 2>&1

未来万一出现故障时,恢复数据方法如下:

#提取备份文件
tar -xzvf /path/to/backup/directory/k8s_config_backup_YYYYMMDDHHMMSS.tar.gz -C /path/to/extract/directory


#恢复k8s配置数据
kubectl apply -f /path/to/extract/directory/k8s_all_config.yaml

#以下开始恢复etcd数据

sudo systemctl stop etcd

ETCDCTL_API=3 etcdctl snapshot restore /path/to/backup/directory/etcd_backup_YYYYMMDDHHMMSS.db \
  --name=etcd-10.1.xx.102 \
  --initial-advertise-peer-urls=https://10.1.xx.102:2380 \
  --initial-cluster=etcd-10.1.xx.102=https://10.1.xx.102:2380,etcd-10.1.xx.103=https://10.1.xx.103:2380,etcd-10.1.xx.104=https://10.1.xx.104:2380 \
  --initial-cluster-token=etcd-cluster-0 \
  --initial-cluster-state=new \
  --data-dir=/var/lib/etcd


sudo systemctl start etcd

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部