1. 概述
1.1 什么是自动化运维
自动化运维(AIOps / Automated Operations)是指利用脚本、工具和平台,将传统手工运维操作标准化、流程化、自动化,从而提高运维效率、降低人为错误、保障系统稳定性。
1.2 自动化运维的目标
降低人工成本 — 减少重复性操作,释放运维人力
提高响应速度 — 自动检测、自动告警、自动修复
减少人为错误 — 标准化操作流程,避免误操作
提升服务可用性 — 7×24 无人值守运维
支撑规模化增长 — 管理数百/数千台服务器
1.3 自动化运维成熟度模型
| 级别 | 阶段 | 特征 |
|:----:|------|------|
| L0 | 纯手工运维 | 所有操作手动执行,依赖个人经验 |
| L1 | 脚本化 | 常用操作编写脚本,减少重复劳动 |
| L2 | 工具化 | 引入配置管理、部署工具,操作可追溯 |
| L3 | 平台化 | 统一运维平台,CMDB、工单系统集成 |
| L4 | 智能化 | AIOps,AI 辅助故障预测和根因分析 |
2. 基础设施自动化
2.1 配置管理
2.1.1 Ansible
适用场景:批量服务器配置、应用部署、日常运维操作
# playbook 示例: 批量安装 nginx
---
- name: 安装并启动 Nginx
hosts: webservers
become: yes
tasks:
- name: 安装 Nginx
apt:
name: nginx
state: latest
update_cache: yes
- name: 启动 Nginx 服务
systemd:
name: nginx
state: started
enabled: yes
- name: 部署配置文件
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: 重启 Nginx
handlers:
- name: 重启 Nginx
systemd:
name: nginx
state: restarted
2.1.2 主机清单管理
# inventory/hosts.ini
[webservers]
web01 ansible_host=10.0.1.10
web02 ansible_host=10.0.1.11
web03 ansible_host=10.0.1.12
[dbservers]
db01 ansible_host=10.0.2.10
db02 ansible_host=10.0.2.11
[all:vars]
ansible_user=deploy
ansible_ssh_private_key_file=~/.ssh/deploy_key
2.2 基础设施即代码(IaC)
Terraform 示例
# 创建云服务器集群
resource "alicloud_instance" "web" {
count = 3
instance_name = "web-${count.index + 1}"
image_id = "ubuntu_22_04_x64_20G"
instance_type = "ecs.c7.large"
security_groups = [alicloud_security_group.web_sg.id]
vswitch_id = alicloud_vswitch.main.id
internet_charge_type = "PayByTraffic"
tags = {
Environment = "production"
Role = "webserver"
}
}
2.3 容器编排
Docker Compose
version: '3.8'
services:
app:
image: myapp:latest
deploy:
replicas: 3
resources:
limits:
cpus: '0.5'
memory: 512M
ports:
- "8080:8080"
environment:
- DB_HOST=db
- REDIS_HOST=redis
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
interval: 30s
timeout: 10s
retries: 3
db:
image: mysql:8.0
volumes:
- db_data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_root_password
redis:
image: redis:7-alpine
command: redis-server --appendonly yes
volumes:
db_data:
3. CI/CD 自动化
3.1 流水线设计
代码提交 → 代码扫描 → 单元测试 → 构建镜像 → 安全扫描 → 部署测试环境 → 集成测试 → 审批 → 部署生产环境
3.2 GitLab CI 示例
stages:
- test
- build
- security
- deploy-staging
- deploy-production
variables:
DOCKER_IMAGE: registry.example.com/myapp
test:
stage: test
script:
- pip install -r requirements.txt
- pytest tests/ --cov=app --cov-report=xml
coverage: '/TOTAL.*\s+(\d+%)/'
build:
stage: build
script:
- docker build -t $DOCKER_IMAGE:$CI_COMMIT_SHA .
- docker push $DOCKER_IMAGE:$CI_COMMIT_SHA
security-scan:
stage: security
script:
- trivy image $DOCKER_IMAGE:$CI_COMMIT_SHA
deploy-staging:
stage: deploy-staging
script:
- kubectl set image deployment/myapp app=$DOCKER_IMAGE:$CI_COMMIT_SHA -n staging
- kubectl rollout status deployment/myapp -n staging --timeout=300s
environment:
name: staging
deploy-production:
stage: deploy-production
script:
- kubectl set image deployment/myapp app=$DOCKER_IMAGE:$CI_COMMIT_SHA -n production
- kubectl rollout status deployment/myapp -n production --timeout=300s
environment:
name: production
when: manual
only:
- main
3.3 蓝绿部署 / 金丝雀发布
| 策略 | 说明 | 适用场景 |
|------|------|----------|
| 滚动更新 | 逐步替换旧版本 Pod | 无状态服务常规更新 |
| 蓝绿部署 | 新旧版本并行,流量一次性切换 | 需要快速回滚的关键服务 |
| 金丝雀发布 | 先导入少量流量到新版本 | 大规模服务,需验证稳定性 |
| A/B 测试 | 按用户特征分流 | 功能验证、用户体验测试 |
4. 监控告警自动化
4.1 监控体系架构
┌─────────────┐
│ Grafana │ ← 可视化面板
└──────┬──────┘
│
┌────────────┼────────────┐
│ │ │
┌───────┴───┐ ┌─────┴─────┐ ┌───┴────────┐
│Prometheus │ │ Loki │ │ Tempo │
│ (指标) │ │ (日志) │ │ (链路) │
└───────┬───┘ └─────┬─────┘ └───┬────────┘
│ │ │
┌───────┴────────────┴────────────┴───────┐
│ 应用 / 基础设施 │
└─────────────────────────────────────────┘
4.2 Prometheus 告警规则
groups:
- name: 基础设施告警
rules:
- alert: 服务器CPU使用率过高
expr: 100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 85
for: 5m
labels:
severity: warning
annotations:
summary: "CPU使用率超过85%"
description: " CPU使用率 %,持续5分钟"
- alert: 磁盘空间不足
expr: (node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100 < 15
for: 10m
labels:
severity: critical
annotations:
summary: "磁盘剩余空间不足15%"
description: " 剩余 %"
- alert: 服务宕机
expr: up == 0
for: 1m
labels:
severity: critical
annotations:
summary: "服务不可达"
description: " 已宕机超过1分钟"
4.3 告警通知配置(飞书集成)
# alertmanager.yml
route:
receiver: 'feishu-webhook'
group_by: ['alertname', 'severity']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
routes:
- match:
severity: critical
receiver: 'feishu-critical'
repeat_interval: 1h
receivers:
- name: 'feishu-webhook'
webhook_configs:
- url: 'https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_WEBHOOK_TOKEN'
send_resolved: true
- name: 'feishu-critical'
webhook_configs:
- url: 'https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_CRITICAL_WEBHOOK_TOKEN'
send_resolved: true
5. 日志管理自动化
5.1 日志收集架构
应用日志 → Filebeat/Fluentd → Kafka(缓冲) → Logstash(处理) → Elasticsearch(存储) → Kibana(查询)
5.2 Filebeat 配置
filebeat.inputs:
- type: log
paths:
- /var/log/app/*.log
fields:
app: myapp
env: production
multiline.pattern: '^\d{4}-\d{2}-\d{2}'
multiline.negate: true
multiline.match: after
output.kafka:
hosts: ["kafka01:9092", "kafka02:9092"]
topic: "app-logs"
codec.format:
string: '%{[message]}'
5.3 日志轮转配置
# /etc/logrotate.d/app
/var/log/app/*.log {
daily
rotate 30
compress
delaycompress
missingok
notifempty
create 0640 app app
sharedscripts
postrotate
systemctl reload app 2>/dev/null || true
endscript
}
6. 自动化巡检
6.1 巡检脚本示例
#!/usr/bin/env python3
"""日常自动化巡检脚本"""
import subprocess
import datetime
import json
import smtplib
from email.mime.text import MIMEText
def check_disk_usage(threshold=85):
"""检查磁盘使用率"""
result = subprocess.run(
["df", "-h", "--output=target,pcent"],
capture_output=True, text=True,
)
alerts = []
for line in result.stdout.strip().split("\n")[1:]:
parts = line.split()
if len(parts) == 2:
mount, usage = parts
usage_pct = int(usage.strip("%"))
if usage_pct > threshold:
alerts.append(f"{mount}: {usage}")
return alerts
def check_service_status(services):
"""检查服务运行状态"""
alerts = []
for svc in services:
result = subprocess.run(
["systemctl", "is-active", svc],
capture_output=True, text=True,
)
if result.stdout.strip() != "active":
alerts.append(f"{svc}: {result.stdout.strip()}")
return alerts
def check_memory_usage(threshold=90):
"""检查内存使用率"""
result = subprocess.run(
["free", "-m"], capture_output=True, text=True,
)
lines = result.stdout.strip().split("\n")
mem_parts = lines[1].split()
total, used = int(mem_parts[1]), int(mem_parts[2])
usage_pct = (used / total) * 100
if usage_pct > threshold:
return [f"内存使用率: {usage_pct:.1f}% ({used}M/{total}M)"]
return []
def check_ssl_expiry(domains, warn_days=30):
"""检查 SSL 证书有效期"""
alerts = []
for domain in domains:
result = subprocess.run(
["openssl", "s_client", "-connect", f"{domain}:443",
"-servername", domain],
input="", capture_output=True, text=True, timeout=10,
)
for line in result.stdout.split("\n"):
if "notAfter" in line:
# 解析到期日期并计算剩余天数
pass
return alerts
def run_inspection():
"""执行巡检"""
report = {
"time": datetime.datetime.now().isoformat(),
"hostname": subprocess.getoutput("hostname"),
"checks": {},
}
services = ["nginx", "mysql", "redis-server", "docker"]
report["checks"]["disk"] = check_disk_usage()
report["checks"]["memory"] = check_memory_usage()
report["checks"]["services"] = check_service_status(services)
has_alert = any(report["checks"].values())
report["status"] = "ALERT" if has_alert else "OK"
return report
if __name__ == "__main__":
report = run_inspection()
print(json.dumps(report, indent=2, ensure_ascii=False))
6.2 巡检计划(Cron)
# 每天早上 8:00 执行日常巡检
0 8 * * * /opt/scripts/daily_inspection.py | /opt/scripts/send_report.sh
# 每小时检查关键服务
0 * * * * /opt/scripts/check_critical_services.sh
# 每周一生成周报
0 9 * * 1 /opt/scripts/weekly_report.py
7. 安全运维自动化
7.1 自动化安全基线检查
| 检查项 | 说明 | 标准 |
|--------|------|------|
| SSH 配置 | 禁止 root 远程登录 | PermitRootLogin no |
| 密码策略 | 密码复杂度和有效期 | 最少12位,90天过期 |
| 防火墙 | 仅开放必要端口 | 最小化开放 |
| 系统更新 | 安全补丁及时更新 | 30天内更新 |
| 文件权限 | 敏感文件权限检查 | /etc/shadow 600 |
| 日志审计 | 关键操作日志留存 | 保留180天 |
7.2 自动安全扫描
#!/bin/bash
# 定期安全扫描脚本
echo "=== 安全基线检查 ==="
# SSH 配置检查
echo -n "SSH Root登录: "
grep -q "^PermitRootLogin no" /etc/ssh/sshd_config && echo "PASS" || echo "FAIL"
# 防火墙状态
echo -n "防火墙状态: "
ufw status | grep -q "Status: active" && echo "PASS" || echo "FAIL"
# 检查异常进程
echo -n "可疑进程: "
ps aux | grep -E "(cryptominer|xmrig)" | grep -v grep && echo "FOUND" || echo "CLEAN"
# 检查未授权用户
echo -n "UID=0的用户: "
awk -F: '$3 == 0 {print $1}' /etc/passwd
# 检查开放端口
echo "=== 开放端口 ==="
ss -tlnp | grep LISTEN
7.3 漏洞管理流程
漏洞扫描(Nessus/OpenVAS) → 漏洞评估(CVSS评分) → 修复计划 → 自动/手动修复 → 验证扫描 → 关闭工单
8. 备份与恢复自动化
8.1 备份策略
| 类型 | 频率 | 保留周期 | 存储位置 |
|------|------|----------|----------|
| 全量备份 | 每周日 | 4周 | 异地对象存储 |
| 增量备份 | 每天 | 7天 | 本地 + 异地 |
| 数据库备份 | 每6小时 | 7天 | 异地对象存储 |
| 配置备份 | 每次变更 | 30天 | Git 仓库 |
8.2 数据库自动备份脚本
#!/bin/bash
# MySQL 自动备份脚本
BACKUP_DIR="/data/backup/mysql"
DATE=$(date +%Y%m%d_%H%M%S)
DB_HOST="localhost"
DB_USER="backup"
RETENTION_DAYS=7
OSS_BUCKET="s3://backup-bucket/mysql/"
mkdir -p "$BACKUP_DIR"
mysqldump --host=$DB_HOST --user=$DB_USER \
--all-databases --single-transaction \
--routines --triggers --events \
| gzip > "$BACKUP_DIR/full_${DATE}.sql.gz"
if [ $? -eq 0 ]; then
echo "$DATE: 备份成功 - $(du -h $BACKUP_DIR/full_${DATE}.sql.gz | cut -f1)"
# 上传到对象存储
aws s3 cp "$BACKUP_DIR/full_${DATE}.sql.gz" "$OSS_BUCKET"
else
echo "$DATE: 备份失败!" | mail -s "MySQL备份告警" ops@company.com
fi
# 清理过期备份
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +$RETENTION_DAYS -delete
9. 故障自愈
9.1 自愈架构
监控检测异常 → 判断故障类型 → 匹配自愈规则 → 执行修复动作 → 验证恢复 → 通知运维
9.2 常见自愈场景
| 故障 | 检测方式 | 自愈动作 |
|------|----------|----------|
| 服务进程挂掉 | Systemd/Supervisor | 自动重启 |
| 磁盘空间满 | 监控告警 | 清理日志/临时文件 |
| 连接数打满 | 监控告警 | 自动扩容/重启 |
| 证书过期 | 定期检查 | Certbot 自动续期 |
| OOM Kill | 内核日志监控 | 重启服务+告警 |
9.3 Systemd 自动重启配置
[Unit]
Description=My Application
After=network.target
[Service]
ExecStart=/opt/app/start.sh
Restart=on-failure
RestartSec=10
StartLimitInterval=60
StartLimitBurst=3
[Install]
WantedBy=multi-user.target
10. 运维工具链推荐
10.1 工具矩阵
| 领域 | 工具 | 说明 |
|------|------|------|
| 配置管理 | Ansible / SaltStack | 批量配置、部署 |
| 基础设施 | Terraform / Pulumi | IaC,云资源编排 |
| 容器编排 | Kubernetes / Docker Swarm | 容器化部署管理 |
| CI/CD | GitLab CI / Jenkins / GitHub Actions | 持续集成持续部署 |
| 监控 | Prometheus + Grafana | 指标监控可视化 |
| 日志 | ELK / Loki | 日志收集分析 |
| 链路追踪 | Jaeger / Tempo | 分布式链路追踪 |
| CMDB | NetBox / 蓝鲸 | 资产配置管理 |
| 工单 | Jira / 飞书审批 | 变更管理流程 |
| 堡垒机 | JumpServer | 运维审计 |
| 安全扫描 | Nessus / Trivy | 漏洞扫描 |
10.2 开源运维平台
蓝鲸智云(BlueKing) — 腾讯开源,覆盖 CMDB、作业平台、监控、日志
SaltStack — 配置管理、远程执行
JumpServer — 开源堡垒机,支持审计录像
Zabbix — 老牌监控系统
Nightingale(夜莺) — 滴滴开源监控告警平台
11. 最佳实践
11.1 运维规范
一切皆代码 — 配置、脚本、流水线全部纳入版本控制
不可变基础设施 — 不修改运行中的服务器,通过替换实现更新
最小权限原则 — 运维账号权限最小化,操作可审计
变更管理 — 所有变更需审批、有回滚方案、有变更窗口
文档即代码 — 运维文档与代码同仓库、同更新
11.2 事故响应流程
发现 → 评估(P0-P3) → 通知(值班/oncall) → 止血 → 根因分析 → 修复 → 复盘 → 改进
| 级别 | 响应时间 | 通知范围 | 示例 |
|:----:|----------|----------|------|
| P0 | 5分钟 | 全员 | 核心服务不可用 |
| P1 | 15分钟 | 团队负责人 | 服务降级 |
| P2 | 1小时 | 相关人员 | 非核心功能异常 |
| P3 | 下一工作日 | 记录工单 | 性能优化 |
11.3 容量规划
定期分析资源使用趋势(CPU、内存、磁盘、带宽)
提前 2-3 个月预测容量需求
设置容量告警阈值(75%预警,85%扩容)
建立快速扩容 Runbook
附录
A. 常用运维命令速查
# 系统信息
uname -a # 系统版本
uptime # 运行时间和负载
free -h # 内存使用
df -h # 磁盘使用
top -bn1 | head -20 # CPU/内存 TOP 进程
# 网络排查
ss -tlnp # 监听端口
curl -o /dev/null -s -w "%{http_code}\n" URL # HTTP状态码
dig +short domain.com # DNS 解析
traceroute target_ip # 路由追踪
tcpdump -i eth0 port 80 -nn # 抓包
# 日志分析
journalctl -u service -f # 实时查看服务日志
grep -c "ERROR" app.log # 错误计数
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head # Top IP
B. Ansible 常用模块
| 模块 | 用途 | 示例 |
|------|------|------|
| apt/yum | 包管理 | apt: name=nginx state=latest |
| copy | 文件复制 | copy: src=app.conf dest=/etc/ |
| template | 模板渲染 | template: src=nginx.j2 dest=/etc/nginx/ |
| systemd | 服务管理 | systemd: name=nginx state=restarted |
| user | 用户管理 | user: name=deploy groups=wheel |
| cron | 定时任务 | cron: name=backup minute=0 hour=2 |
| shell | 执行命令 | shell: /opt/scripts/deploy.sh |