Ansible是开源的自动化运维工具,使用SSH连接管理节点,无需在目标安装客户端。采用声明式YAML语法编写Playbook。
控制节点 ──SSH──→ 被管理节点1
──SSH──→ 被管理节点2
──SSH──→ 被管理节点N
# 特点:
# - 无Agent:不需要在目标安装软件
# - 幂等性:重复执行结果一致
# - 声明式:描述期望状态,而非步骤
# - SSH原生:利用现有SSH通道
# 安装
sudo apt install ansible # Ubuntu
sudo pip install ansible # pip
# 验证
ansible --version
# 配置文件优先级
# 1. ANSIBLE_CONFIG环境变量
# 2. ./ansible.cfg (当前目录)
# 3. ~/.ansible.cfg
# 4. /etc/ansible/ansible.cfg
# /etc/ansible/hosts 或自定义inventory.ini
[webservers]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11
[dbservers]
db1 ansible_host=192.168.1.20
[production:children]
webservers
dbservers
[all:vars]
ansible_user=deploy
ansible_ssh_private_key_file=~/.ssh/id_ed25519
# ping测试
ansible all -m ping
# 执行命令
ansible webservers -m command -a "uptime"
ansible webservers -m shell -a "free -h"
# 复制文件
ansible webservers -m copy -a "src=file.conf dest=/etc/app.conf"
# 安装包
ansible webservers -m apt -a "name=nginx state=present"
# 创建用户
ansible all -m user -a "name=deploy group=www-data"
| 模块 | 功能 | 示例 |
|---|---|---|
| ping | 连通测试 | -m ping |
| command | 执行命令 | -m command -a "uptime" |
| shell | Shell命令(支持管道) | -m shell -a "cat /proc/cpuinfo" |
| copy | 复制文件 | -m copy -a "src=x dest=y" |
| template | Jinja2模板 | -m template -a "src=x.j2 dest=y" |
| apt/yum | 包管理 | -m apt -a "name=nginx" |
| service | 服务管理 | -m service -a "name=nginx state=started" |
| user | 用户管理 | -m user -a "name=deploy" |
| file | 文件/目录 | -m file -a "path=/x state=directory" |
| cron | 定时任务 | -m cron -a "name=backup job=..." |
# 1. 创建inventory
cat > inventory.ini << EOF
[local]
localhost ansible_connection=local
EOF
# 2. 测试连通
ansible -i inventory.ini all -m ping
# 3. 收集信息
ansible -i inventory.ini all -m setup | head -30✅ 理解Ansible架构
✅ 掌握Inventory配置
✅ 学会Ad-hoc命令
✅ 了解常用模块
| 书名 | 作者 | 重点 |
|---|---|---|
| Linux命令行与Shell脚本编程大全 | Blum | Shell脚本全面覆盖 |
| UNIX/Linux系统管理技术手册 | Nemeth | 系统管理圣经 |
| Ansible: Up and Running | Lintner | Ansible实战 |
| 鸟哥的Linux私房菜 | 鸟哥 | 中文经典入门 |
| 认证 | 机构 | 级别 |
|---|---|---|
| LFCS | Linux Foundation | 基础系统管理 |
| LFCE | Linux Foundation | 高级系统工程师 |
| RHCSA | Red Hat | Red Hat管理员 |
| RHCE | Red Hat | Red Hat工程师 |
| CKA/CKAD | CNCF | Kubernetes管理员/开发者 |
# 文本处理速查
grep -E 'pattern' file # 扩展正则搜索
sed -i 's/old/new/g' file # 替换
awk '{print $1}' file # 提取列
sort | uniq -c | sort -rn # 频次统计
cut -d: -f1 file # 切列
tr 'A-Z' 'a-z' # 转小写
# 系统管理速查
systemctl status/start/stop/restart service
journalctl -u service -f # 跟踪日志
df -h / du -sh * # 磁盘使用
ps aux --sort=-%mem # 内存排序
ss -tlnp # 监听端口
iptables -L -n # 防火墙规则
crontab -e # 编辑定时任务
useradd -m -s /bin/bash user # 创建用户
# 网络诊断速查
ip addr / ip route # 网络配置
ping / traceroute # 连通测试
dig / nslookup # DNS查询
curl -I url # HTTP头检查
nc -zv host port # 端口测试
tcpdump -i eth0 port 80 # 抓包
$ ansible --version 2>/dev/null | head -3 || echo 'ansible not installed'
N/A
$ which ansible-playbook 2>/dev/null || echo '未安装'
未安装
# ansible.cfg
[defaults]
inventory = ./inventory
host_key_checking = False
forks = 10
timeout = 30
roles_path = ./roles
log_path = ./ansible.log
[privilege_escalation]
become = True
become_method = sudo
# 动态Inventory (AWS示例)
# inventory/aws_ec2.yml
plugin: aws_ec2
regions:
- us-east-1
keyed_groups:
- key: tags.Role
# Ansible Vault加密
ansible-vault create secrets.yml
ansible-vault encrypt secrets.yml
ansible-playbook --ask-vault-pass site.yml
在实际生产环境中,Ansible架构与模块开发是系统管理员必须深入掌握的核心能力。本节将探讨常见场景、最佳实践和避坑指南。
开发环境和生产环境的差异是脚本出错的常见原因。建议:
优化策略:
改善方法:
#!/bin/bash
# Ansible架构与模块开发最佳实践模板
set -euo pipefail
# 1. 参数校验
[[ $# -lt 1 ]] && echo "Usage: $0 <arg>" >&2 && exit 1
# 2. 环境检查
require_cmd() {
command -v "$1" >/dev/null || { echo "需要: $1" >&2; exit 1; }
}
# 3. 清理机制
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT
# 4. 日志记录
log() { echo "[$(date +%T)] $*"; }
err() { log "ERROR: $*" >&2; exit 1; }
# 5. 主逻辑
main() {
log "开始处理: $1"
# 业务逻辑
log "处理完成"
}
main "$@"
# 文件操作
ls -la # 详细列表
find / -name "*.conf" 2>/dev/null # 查找文件
ln -s target link # 符号链接
du -sh * | sort -rh # 目录大小排序
# 文本处理
grep -rn "pattern" dir/ # 递归搜索
sed -i.bak 's/old/new/g' f # 备份替换
awk -F: '{print $1}' file # 提取列
sort file | uniq -c # 去重计数
# 系统管理
systemctl status/start/stop/restart service
journalctl -u service -f # 实时日志
ps aux --sort=-%mem # 内存排序
ss -tlnp # 监听端口
crontab -e # 定时任务
# 网络诊断
ip addr/route/show # 网络配置
ping/traceroute # 连通测试
dig/nslookup # DNS查询
curl -I url # HTTP检查
nc -zv host port # 端口测试
# 磁盘管理
df -h # 磁盘使用
fdisk -l # 分区信息
mkfs.ext4 /dev/sdb1 # 格式化
mount /dev/sdb1 /mnt # 挂载
blkid # UUID查看
本章内容是Linux系统管理课程的重要组成部分。掌握这些知识需要大量的实践操作,建议在虚拟机或云服务器上反复练习。记住:纸上得来终觉浅,绝知此事要躬行。
在实际工作中,遇到问题时:
A: 从简单的Ad-hoc命令开始,逐步编写Playbook,最后组织为Role。在实践中学习最有效。
A: 1)先在staging验证 2)使用--check预演 3)确保有回滚方案 4)监控部署后状态
A: 1)查看ansible日志定位失败任务 2)手动修复或回滚 3)修复Playbook 4)重新执行
A: 使用声明式模块(apt/yum/service/file)而非命令式(command/shell)。
A: 使用Ansible Vault加密变量文件,密钥与代码分离存储。
# 核心概念对照表
声明式 vs 命令式:
声明式: 描述"要什么" → apt: name=nginx state=present
命令式: 描述"做什么" → command: apt install nginx
幂等性: 同一操作执行多次,结果一致
apt: name=nginx state=present # 已安装则不操作
command: apt install nginx # 可能重复安装
收敛: 使系统达到期望状态的过程
检测当前状态 → 计算差异 → 执行变更 → 验证结果
不可变基础设施:
不修改运行中的系统,而是重建
容器/AMI/镜像方式部署