Ansible 自动化入门 — 从零到手写 Playbook

什么是 Ansible

Ansible 是一个自动化运维工具,一台控制机通过 SSH 管理所有服务器,不需要在被管机器上装任何 Agent。

核心理念:声明式——告诉 Ansible「我要什么状态」,它自动判断要不要执行。

1
ansible <目标> -i <inventory> -m <模块> -a <参数>

环境搭建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 安装
sudo dnf install -y epel-release
sudo dnf install -y --nogpgcheck ansible

# Inventory 文件定义目标机器
cat > hosts << EOF
[webserver]
47.99.166.175 ansible_connection=local

[all:vars]
ansible_user=bing
EOF

# 测试连通性
ansible -i hosts all -m ping
# -> pong

Ad-hoc 命令

-b 是 sudo(become root)。

命令 用途
ansible all -m ping 连通性测试
ansible all -m setup 采集系统信息
ansible all -m shell -a "free -h" 批量执行 shell
ansible all -m dnf -a "name=htop state=present" -b 批量装软件

Playbook 1:系统巡检

1
2
3
4
5
6
7
8
9
- name: 系统巡检
hosts: all
tasks:
- name: 主机名
command: hostname
- name: Docker 容器
shell: docker ps
- name: 内存
shell: free -h | grep "^Mem:"

ansible-playbook -i hosts check.yml 一行命令出完整报告。

Playbook 2:声明式部署 Nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- name: 部署 Nginx
hosts: all
tasks:
- name: 安装 nginx
dnf: name=nginx state=present
- name: 创建网站目录
file: path=/var/www/demo state=directory
- name: 写入首页
copy: content="<h1>部署成功</h1>" dest=/var/www/demo/index.html
- name: 配置站点
copy: content="server { listen 8081; root /var/www/demo; }" dest=/etc/nginx/conf.d/demo.conf
- name: 启动 nginx
systemd: name=nginx state=started enabled=yes
- name: 验证
uri: url=http://localhost:8081 return_content=yes

关键是幂等:跑第一遍全部 changed,第二遍全部 ok——已经是要的状态了。

Playbook 3:Docker 容器管理

1
2
3
4
5
6
7
8
9
10
11
12
13
- name: Docker 容器管理
hosts: all
tasks:
- name: 确保 Docker 运行
systemd: name=docker state=started
- name: 启动 blog-nginx
shell: docker start blog-nginx
- name: 启动 glances
shell: docker start glances
- name: 容器状态
shell: docker ps
- name: 系统内存
shell: free -h | grep "^Mem:"

学过的模块

模块 用途
ping 连通性测试
setup 采集所有系统信息
shell / command 执行命令
debug 打印变量/输出
dnf 包管理(幂等)
systemd 服务管理
file 文件/目录创建
copy 推送文件/内容
uri HTTP 请求/验证

面试话术

我写过 3 个 Ansible playbook:系统巡检一键收集 CPU/内存/磁盘/容器状态;Nginx 声明式部署,安装到验证全自动,幂等可重复执行;Docker 容器批量管理。用 ansible -m setup 可以同时采集所有服务器硬件信息,-m shell 批量执行命令,管 100 台也不用挨个 SSH。

踩坑记录

  1. docker_container 模块需要 Python docker SDK,Python 3.6 装不上 → 换 shell 模块直接调 CLI,更通用
  2. Nginx 默认 80 端口和 Docker 冲突 → 改成 8081
  3. GPG check 失败dnf install --nogpgcheck

项目地址

GitHub ops-portfolio/ansible


Ansible 自动化入门 — 从零到手写 Playbook
https://bingsv.github.io/2026/07/28/Ansible自动化入门/
作者
Bingsv
发布于
2026年7月28日
许可协议