0%

批量备份k8s资源的脚本

使用方式:执行时传入参数namespace,则会将该namespace下所有资源通过yaml方式备份

NAMESPACE=$1

deployments=$(kubectl get deployments -n "$NAMESPACE" |awk 'NR>1  {print $1}')

for deployment in $deployments; do
    mkdir -p $NAMESPACE/deploy
    output_file="$NAMESPACE/deploy/$deployment.yaml"
    kubectl get deployment "$deployment" -n "$NAMESPACE" -o yaml > "$output_file"
    echo "Downloaded $deployment.yaml"
done


services=$(kubectl get service -n "$NAMESPACE" |awk 'NR>1  {print $1}')

for service in $services; do
    mkdir -p $NAMESPACE/service
    output_file="$NAMESPACE/service/$service.yaml"
    kubectl get service "$service" -n "$NAMESPACE" -o yaml > "$output_file"
    echo "Downloaded $service.yaml"
done


services=$(kubectl get ConfigMap -n "$NAMESPACE" |awk 'NR>1  {print $1}')

for service in $services; do
    mkdir -p $NAMESPACE/cm 
    output_file="$NAMESPACE/cm/$service.yaml"
    kubectl get ConfigMap "$service" -n "$NAMESPACE" -o yaml > "$output_file"
    echo "Downloaded $service.yaml"
done



services=$(kubectl get Secret -n "$NAMESPACE" |awk 'NR>1  {print $1}')

for service in $services; do
    mkdir -p $NAMESPACE/secret
    output_file="$NAMESPACE/secret/$service.yaml"
    kubectl get Secret "$service" -n "$NAMESPACE" -o yaml > "$output_file"
    echo "Downloaded $service.yaml"
done


services=$(kubectl get ingress -n "$NAMESPACE" |awk 'NR>1  {print $1}')

for service in $services; do
    mkdir -p $NAMESPACE/ingress
    output_file="$NAMESPACE/ingress/$service.yaml"
    kubectl get Secret "$service" -n "$NAMESPACE" -o yaml > "$output_file"
    echo "Downloaded $service.yaml"
done