Kubernetes集群状态检查与告警整合的自动化

发布于:2025-02-27 ⋅ 阅读:(14) ⋅ 点赞:(0)

将Kubernetes集群状态检查与告警整合的自动化方案,包含脚本实现、定时任务配置及异常通知机制:


1. 创建监控脚本

保存为 /opt/k8s-monitor/cluster-check.sh

#!/bin/bash

# 基础配置
LOG_DIR="/var/log/k8s-monitor"
REPORT_FILE="${LOG_DIR}/report-$(date +%Y%m%d).log"
ALERT_FLAG=0  # 异常标记

# 创建日志目录
mkdir -p ${LOG_DIR}

# 定义告警函数(示例使用邮件,可替换为其他通知方式)
send_alert() {
  local message=$1
  echo "[CRITICAL] ${message}" >> ${REPORT_FILE}
  # 发送邮件示例(需提前配置mailx)
  echo "Kubernetes集群异常告警: ${message}" | mailx -s "K8S集群异常告警" ops-team@example.com
  # 可选:调用Webhook(如钉钉/企业微信)
  # curl -X POST -H "Content-Type: application/json" -d '{"msgtype":"text","text":{"content":"'"${message}"'"}}' https://oapi.dingtalk.com/robot/send?access_token=xxx
}

# 检查节点状态
check_nodes() {
  echo "===== 节点状态检查 =====" >> ${REPORT_FILE}
  kubectl get nodes --no-headers | awk '{print $1,$2}' | while read -r node status; do
    if [ "$status" != "Ready" ]; then
      ALERT_FLAG=1
      send_alert "节点异常: ${node} 状态为 ${status}"
      echo "[ERROR] Node ${node} status: ${status}" >> ${REPORT_FILE}
    else
      echo "[OK] Node ${node} status: ${status}" >> ${REPORT_FILE}
    fi
  done
}

# 检查系统组件
check_system_pods() {
  echo "===== 系统Pod检查 =====" >> ${REPORT_FILE}
  kubectl get pods -n kube-system --no-headers | awk '{print $1,$3}' | while read -r pod status; do
    if [[ ! "$status" =~ ^(Running|Completed)$ ]]; then
      ALERT_FLAG=1
      send_alert "系统Pod异常: ${pod} 状态为 ${status}"
      echo "[ERROR] Pod ${pod} status: ${status}" >> ${REPORT_FILE}
    else
      echo "[OK] Pod ${pod} status: ${status}" >> ${REPORT_FILE}
    fi
  done
}

# 检查集群事件
check_events() {
  echo "===== 集群事件检查 =====" >> ${REPORT_FILE}
  kubectl get events --field-selector type=Warning --sort-by=.metadata.creationTimestamp --no-headers | head -n 20 | while read -r timestamp type reason object message; do
    if [[ -n "$type" ]]; then
      ALERT_FLAG=1
      send_alert "集群事件告警: ${reason} (对象: ${object})"
      echo "[WARNING] Event: ${timestamp} ${reason} ${object} ${message}" >> ${REPORT_FILE}
    fi
  done
}

# 执行检查
{
  check_nodes
  check_system_pods
  check_events

  # 生成总结报告
  if [ $ALERT_FLAG -eq 0 ]; then
    echo "===== 检查完成: 所有系统正常 =====" >> ${REPORT_FILE}
  else
    echo "===== 检查完成: 发现异常问题 =====" >> ${REPORT_FILE}
  fi
} | tee -a ${REPORT_FILE}

# 日志清理(保留7天)
find ${LOG_DIR} -name "*.log" -mtime +7 -exec rm -f {} \;

2. 设置执行权限

chmod +x /opt/k8s-monitor/cluster-check.sh

3. 配置定时任务

# 编辑crontab
sudo crontab -e

# 添加以下内容(每天8:00执行,异常时立即告警)
0 8 * * * /opt/k8s-monitor/cluster-check.sh >/dev/null 2>&1

# 查看定时任务
sudo crontab -l

4. 告警配置说明

邮件告警配置(示例使用mailx)
# 安装mailx
sudo yum install mailx -y

# 编辑配置文件
sudo vim /etc/mail.rc

# 添加以下内容(以QQ邮箱为例)
set from=your_email@qq.com
set smtp=smtps://smtp.qq.com:465
set smtp-auth-user=your_email@qq.com
set smtp-auth-password=your_auth_code  # 需申请SMTP授权码
set smtp-auth=login
set ssl-verify=ignore
set nss-config-dir=/etc/pki/nssdb
企业微信/钉钉告警

修改脚本中的send_alert函数,替换为实际的Webhook地址即可。


5. 日志监控增强(可选)

使用logrotate管理日志:

# 创建logrotate配置
sudo tee /etc/logrotate.d/k8s-monitor <<EOF
/var/log/k8s-monitor/*.log {
    daily
    rotate 30
    missingok
    compress
    delaycompress
    notifempty
    create 0644 root root
}
EOF

检查项说明

检查维度 判断标准 告警阈值
节点状态 状态非Ready 发现即告警
系统组件Pod 状态非Running/Completed 连续2次异常
集群事件 Warning级别事件 最近10条含Warning

验证测试

# 手动触发脚本
/opt/k8s-monitor/cluster-check.sh

# 查看最新日志
tail -f /var/log/k8s-monitor/report-$(date +%Y%m%d).log

# 模拟节点故障(测试用)
kubectl cordon <node-name>

该方案可实现以下功能:

  1. 自动巡检:每天定时检查核心指标
  2. 智能告警:发现异常立即触发通知
  3. 日志追溯:保留历史检查记录
  4. 灵活扩展:可添加更多检查项(如存储容量、API健康检查)