Ansible 自动化运维实战 —— 批量部署、安全加固与进阶技巧
导语: 这是《Ansible 自动化运维入门》的续篇。在前一篇中,你已经掌握了 Ansible 的安装、配置和基础用法。本文将带你深入实战,学习如何批量部署服务、批量管理用户、系统安全加固,以及变量、角色、标签等进阶技巧。
一、实战案例
案例一:批量部署 Nginx
在playbooks/目录下创建文件:
cd ~/ansible-project nano playbooks/deploy-nginx.yml--- - name: 部署 Nginx Web 服务器 hosts: webservers become: yes tasks: - name: 安装 Nginx apt: name: nginx state: present update_cache: yes - name: 确保 Nginx 开机自启 service: name: nginx state: started enabled: yes - name: 创建测试页面 copy: content: "<h1>Hello from {{ inventory_hostname }}</h1>\n" dest: /var/www/html/index.html mode: '0644' - name: 重启 Nginx service: name: nginx state: restarted执行部署:
ansible-playbook playbooks/deploy-nginx.yml验证访问:
curl http://192.168.1.101 curl http://192.168.1.102案例二:批量创建用户
在playbooks/目录下创建文件:
cd ~/ansible-project nano playbooks/create-users.yml--- - name: 批量创建用户 hosts: all become: yes vars: users: - name: alice groups: sudo - name: bob groups: docker tasks: - name: 创建用户 user: name: "{{ item.name }}" groups: "{{ item.groups }}" create_home: yes shell: /bin/bash loop: "{{ users }}" - name: 设置用户密码 lineinfile: path: /etc/shadow state: absent when: false # 实际需要设置密码执行:
ansible-playbook playbooks/create-users.yml案例三:系统安全加固
在playbooks/目录下创建文件:
cd ~/ansible-project nano playbooks/hardening.yml--- - name: 系统安全加固 hosts: all become: yes tasks: - name: 禁用 Root 远程登录 lineinfile: path: /etc/ssh/sshd_config regexp: '^PermitRootLogin' line: 'PermitRootLogin no' notify: 重启 SSH - name: 禁用密码登录,仅允许密钥 lineinfile: path: /etc/ssh/sshd_config regexp: '^PasswordAuthentication' line: 'PasswordAuthentication no' notify: 重启 SSH - name: 配置防火墙规则 ufw: rule: allow port: "22,80,443" proto: tcp - name: 自动更新系统 cron: name: 自动更新 special_time: daily job: 'apt update && apt upgrade -y' when: ansible_os_family == "Debian" handlers: - name: 重启 SSH service: name: ssh state: restarted执行加固:
ansible-playbook playbooks/hardening.yml提示: 在生产环境执行安全加固前,请务必先用--check --diff参数预览变更,确保不会锁死自己!
二、进阶技巧
2.1 使用变量
- name: 使用变量 hosts: all become: yes vars: nginx_port: 80 deploy_dir: /opt/app tasks: - name: 创建部署目录 file: path: "{{ deploy_dir }}" state: directory mode: '0755'变量还可以定义在单独的文件中:
# group_vars/webservers.yml nginx_port: 8080 deploy_dir: /var/www # group_vars/databases.yml db_port: 3306 db_data_dir: /data/mysql2.2 条件判断
- name: 根据系统类型安装软件 apt: name: "{{ item }}" state: present loop: - curl - vim when: ansible_distribution == "Ubuntu"多条件判断:
- name: 根据 CPU 架构安装不同软件包 apt: name: "{{ item }}" state: present loop: - htop - tmux when: ansible_architecture == "x86_64"2.3 使用角色 (Roles)
角色是组织 Playbook 的最佳方式,可以实现代码复用:
roles/ nginx/ tasks/ main.yml templates/ files/ handlers/ defaults/ mysql/ tasks/ main.yml templates/在 Playbook 中引用角色:
--- - name: 部署 Web 服务 hosts: webservers become: yes roles: - nginx - common为什么使用角色?
- 代码复用:一个角色可在多个 Playbook 中引用
- 职责分离:每个角色独立管理,便于维护
- 便于分享:可以发布到 Ansible Galaxy 供社区使用
2.4 使用标签
- name: 安装 Nginx apt: name: nginx state: present tags: - install - nginx - name: 配置 Nginx template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf tags: - configure - nginx仅执行安装任务:
ansible-playbook playbooks/site.yml --tags "install"排除某些任务:
ansible-playbook playbooks/site.yml --skip-tags "configure"2.5 循环与迭代
- name: 安装多个软件包 apt: name: "{{ item }}" state: present loop: - curl - vim - htop - git - name: 创建多个用户 user: name: "{{ item }}" state: present groups: sudo loop: - alice - bob - charlie2.6 错误处理与忽略失败
- name: 尝试安装软件,允许失败 apt: name: nginx state: present ignore_errors: yes - name: 条件性执行任务 command: /usr/bin/some_command ignore_errors: yes register: result - name: 根据结果决定下一步 debug: msg: "命令执行失败,执行备选方案" when: result.failed三、常见问题排查
3.1 连接失败
# 使用 -vvv 查看详细日志 ansible all -i inventory/hosts.ini -m ping -vvv # 检查 SSH 配置 ssh -v user@被控节点IP3.2 权限不足
# 检查是否配置了 become become: yes # 检查用户权限 sudo -l3.3 YAML 格式错误
YAML 对缩进要求严格:
必须使用空格,不能使用制表符
同一层级的缩进必须一致
使用在线工具验证: https://yamlchecker.com/
3.4 模块报错
# 查看模块文档 ansible-doc apt # 检查模块是否存在 ansible all -m apt -a "help"3.5 被控节点 ModuleNotFoundError
如果看到类似ModuleNotFoundError: No module named 'ansible.module_utils.six.moves'错误,说明被控节点缺少 Ansible 的 Python 模块:
web01 | FAILED! => { "module_stderr": "Shared connection to 10.10.5.32 closed.\r\n", "module_stdout": "\r\nTraceback (most recent call last):\r\n File .../AnsiballZ_ping.py\", line 37, in invoke_module\r\n from ansible.module_utils import basic\r\nModuleNotFoundError: No module named 'ansible.module_utils.six.moves'\r\n", }解决方法:在被控节点上安装 Ansible 的 Python 模块:
# Ubuntu/Debian(注意:apt 可能没有此包,需要用 pip) sudo pip3 install ansible-core --break-system-packages # CentOS/RHEL sudo dnf install -y ansible # 或者用 pip 安装(版本更新) sudo pip3 install ansible-core为什么需要装?
Ansible 的工作方式是控制节点把模块(Python 代码)发送到被控节点,在被控节点的 Python 环境中执行。所以被控节点也需要有 Ansible 的 Python 模块,否则无法运行任何模块。
3.6 apt 软件源同步问题
如果 Playbook 安装软件时遇到类似这样的错误:
E: Failed to fetch http://security.ubuntu.com/ubuntu/.../vim-tiny_9.1.0016-1ubuntu7.18_amd64.deb File has unexpected size (836 != 805816). Mirror sync in progress?原因:Ubuntu 软件源镜像正在同步中,文件不完整。
解决方法:在被控节点上执行sudo apt update --fix-missing刷新缓存,然后重试 Playbook。
四、总结与扩展
本节回顾
通过本系列文章,你已经学会了:
✅ 配置 Inventory 主机清单
✅ 安装配置 Ansible 和控制节点
✅ 编写和执行 Playbook
✅ 常用模块的实际应用
✅ 批量部署、用户管理、安全加固等实战案例
✅ 变量、角色、标签等进阶技巧
下一步建议
- AWX / Tower
: 使用 Ansible 的 Web 界面,提供可视化操作和权限管理
- Ansible Galaxy
: 分享和复用社区编写的角色和 Playbook
- CI/CD 集成
: 结合 Jenkins、GitLab CI 实现自动化部署
- 云平台管理
: 学习使用 Ansible 管理 AWS、Azure、阿里云等资源
参考资料
Ansible 官方文档: https://docs.ansible.com/
Ansible Galaxy: https://galaxy.ansible.com/
YAML 语法参考: https://yaml.org/
如果你觉得这篇文章有帮助,欢迎点赞、在看、转发支持!有问题欢迎在评论区留言讨论。
