2025.11.28
运维
陋技分享
ansible自动化运维
自动化运维进阶实战手册
Ansible 全栈实战手册
无 Agent 依赖 / 幂等性操作 / 从 Ad-Hoc 到企业级 Roles 架构
1. 极速环境配置
Ansible 只需要在控制节点安装,被控节点只需开启 SSH 服务并安装 Python。
# Ubuntu/Debian 控制节点安装
sudo apt update && sudo apt install -y ansible
# 生成 SSH 密钥并分发免密登录 (极其重要,否则后续天天输密码)
ssh-keygen -t rsa -b 4096 -N ""
ssh-copy-id root@192.168.1.100
ssh-copy-id root@192.168.1.101
⚠️ 首次连接避坑:关闭主机指纹确认
修改配置文件跳过交互式指纹确认(`Are you sure you want to continue connecting?`):
编辑 /etc/ansible/ansible.cfg,设置 host_key_checking = False
2. 配置资产清单 (Inventory)
告诉 Ansible 你要管理哪些机器。默认在 /etc/ansible/hosts,但推荐在项目目录下建立局部的 hosts.ini。
# hosts.ini 文件示例
[webservers]
10.0.0.10
10.0.0.11
[dbservers]
10.0.0.20 ansible_ssh_port=2222 # 指定非标端口
[all:vars]
ansible_python_interpreter=/usr/bin/python3
ansible_user=root
3. 日常巡检:Ad-Hoc 单行命令
不写剧本直接批量操作,用于紧急排障或快速获取信息。
# 1. 连通性测试 (测试 SSH 和 Python 是否就绪)
ansible all -i hosts.ini -m ping
# 2. 批量查看内存使用情况
ansible webservers -i hosts.ini -m command -a "free -m"
# 3. 批量拉取线上的 Nginx 错误日志到本地控制机
ansible webservers -i hosts.ini -m fetch -a "src=/var/log/nginx/error.log dest=/tmp/logs/"
4. 核心武功:Playbook 剧本编写
核心思想是“声明期望的状态”,而不是写执行步骤(保证幂等性)。
示例:deploy_nginx.yml
---
- name: 初始化 Web 服务器
hosts: webservers
become: yes # 提权执行
tasks:
- name: 确保安装了 Nginx
apt:
name: nginx
state: present # present代表需安装,absent代表卸载
- name: 推送自定义首页配置
copy:
src: ./files/index.html
dest: /var/www/html/index.html
notify:
- 重载 Nginx # 文件发生变化时才触发 handler
handlers:
- name: 重载 Nginx
service:
name: nginx
state: reloaded
5. 变量与 Facts 系统 (动态适配)
Ansible 会自动收集目标主机的硬件、系统信息(Facts)。配合自定义变量,剧本兼容性极强。
# 查看机器的所有 Facts:
ansible webservers -m setup
# 在 Playbook 中使用变量:
---
- hosts: all
vars:
app_port: 8080
tasks:
- name: 打印系统架构
debug:
msg: "系统:{{ ansible_distribution }} {{ ansible_architecture }},端口:{{ app_port }}"
6. Jinja2 模板渲染 (动态配置)
根据目标机器的 CPU 核心数、内存动态生成配置文件,必须使用 template 模块。
# nginx.conf.j2 模板文件内容
worker_processes {{ ansible_processor_vcpus }};
listen {{ app_port }};
server_name {{ ansible_default_ipv4.address }};
# Playbook 中分发模板
- name: 推送动态 Nginx 配置
template:
src: ./templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: 重载 Nginx
7. 循环与条件判断 (逻辑控制)
tasks:
# 批量装软件 (循环)
- name: 安装基础工具包
apt:
name: "{{ item }}"
state: present
loop:
- htop
- git
- curl
# 跨系统兼容 (条件判断)
- name: 如果是 CentOS,使用 yum 安装
yum:
name: httpd
state: present
when: ansible_distribution == "CentOS"
8. Ansible Vault (安全加密)
生产环境中,数据库密码绝不能明文写在 Playbook 里。
# 1. 创建加密文件 (提示输入密码)
ansible-vault create secrets.yml
# 2. 修改加密文件
ansible-vault edit secrets.yml
# 3. 执行包含加密文件的 Playbook
ansible-playbook site.yml --ask-vault-pass
9. Roles 角色化编排 (企业级规范)
当剧本庞大时,使用 Roles 解耦代码。使用 ansible-galaxy init nginx_role 生成骨架。
# 目录结构解析:
nginx_role/
├── tasks/ # 主逻辑 (main.yml)
├── handlers/ # 触发器
├── templates/ # 动态模板 (.j2)
├── files/ # 静态文件
└── vars/ # 变量配置
# site.yml (入口文件调用 Role)
---
- hosts: webservers
roles:
- role: base_setup
- role: nginx_role
vars:
app_port: 80
10. 生产级执行与排错指南
- 干跑测试 (预测改变):
ansible-playbook site.yml -C(Dry Run,极其推荐生产部署前执行)。 - 语法检查:
ansible-playbook site.yml --syntax-check。 - 单步确认模式:
ansible-playbook site.yml --step,执行每个 Task 前都需要你手动确认。 - YAML 缩进陷阱: 严禁混用 Tab 和空格,编辑器务必设置为空格缩进(2个或4个)。
- 慎用 shell 模块: shell 模块无幂等性,重复执行易报错。能用
file、apt等原生模块就别用shell。
提速核弹:开启 Pipelining
在 ansible.cfg 的 [ssh_connection] 下加入 pipelining = True。它能跳过 SSH 临时文件的传输,直接通过管道执行指令,速度飙升 2-3 倍。