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: h1Hello 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_642.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 configure2.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 help3.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: 分享和复用社区编写的角色和 PlaybookCI/CD 集成: 结合 Jenkins、GitLab CI 实现自动化部署云平台管理: 学习使用 Ansible 管理 AWS、Azure、阿里云等资源参考资料Ansible 官方文档: https://docs.ansible.com/Ansible Galaxy: https://galaxy.ansible.com/YAML 语法参考: https://yaml.org/如果你觉得这篇文章有帮助欢迎点赞、在看、转发支持有问题欢迎在评论区留言讨论。