#!/bin/bash
# 配置參數
BACKUP_DIR="/var/backups/k8s"
NAMESPACE="default"
LOG_FILE="/var/log/k8s_backup.log"
# 檢查并創建日志文件
if [ ! -f "$LOG_FILE" ]; then
touch "$LOG_FILE"
fi
# 記錄日志函數
log() {
echo "$(date +"%Y-%m-%d %H:%M:%S") - $1" >> "$LOG_FILE"
}
# 創建備份目錄
mkdir -p "$BACKUP_DIR"
# 備份Kubernetes資源
log "Starting backup of Kubernetes resources..."
kubectl get all -n $NAMESPACE -o yaml > "$BACKUP_DIR/all_resources.yaml"
kubectl get pv -o yaml > "$BACKUP_DIR/pv.yaml"
kubectl get pvc -o yaml > "$BACKUP_DIR/pvc.yaml"
kubectl get secrets -o yaml > "$BACKUP_DIR/secrets.yaml"
kubectl get configmaps -o yaml > "$BACKUP_DIR/configmaps.yaml"
log "Backup completed successfully."
# 清理舊備份
find "$BACKUP_DIR" -type f -mtime +7 -exec rm -f {} \;
log "Old backups cleaned up."