Ansible实战:5分钟搞定批量服务器配置(附常用模块速查表)

张开发
2026/4/7 20:27:12 15 分钟阅读

分享文章

Ansible实战:5分钟搞定批量服务器配置(附常用模块速查表)
Ansible实战5分钟完成基础服务器配置的极简指南运维工程师小张刚接手了20台新服务器主管要求他在下班前完成基础环境配置。传统方式需要逐台SSH登录操作不仅效率低下还容易出错。这时Ansible的批量操作能力成为了救命稻草——只需5分钟小张就完成了所有服务器的标准化配置。本文将还原这个真实场景带你快速掌握Ansible的核心用法。1. 零基础快速搭建Ansible环境1.1 极简安装方案在控制节点操作机执行以下命令完成安装# CentOS/RHEL系统 yum install -y epel-release yum install -y ansible # Ubuntu系统 apt update apt install -y ansible安装完成后验证版本ansible --version # 应输出类似ansible 2.9.271.2 主机清单配置技巧编辑/etc/ansible/hosts文件采用分组管理[web_servers] 192.168.1.101 ansible_ssh_useradmin 192.168.1.102 ansible_ssh_useradmin [db_servers] 192.168.1.201 ansible_ssh_port2222 192.168.1.202 [cluster:children] web_servers db_servers提示使用ansible-inventory --list命令可验证主机分组情况2. 五大核心模块实战演示2.1 文件分发copy模块批量部署Nginx配置文件ansible web_servers -m copy -a src/local/nginx.conf dest/etc/nginx/ ownerroot grouproot mode0644关键参数解析参数作用示例值src源文件路径/tmp/config.inidest目标路径/etc/app/config.inibackup是否备份原文件yes/nomode文件权限06442.2 软件管理yum/apt模块批量安装常用工具# RedHat系 ansible all -m yum -a namehtop,vim,git statepresent # Debian系 ansible all -m apt -a namehtop,vim,git statepresent2.3 服务控制systemd模块统一管理Nginx服务状态ansible web_servers -m systemd -a namenginx enabledyes statestarted2.4 命令执行shell模块批量获取服务器负载信息ansible all -m shell -a uptime | awk {print \$10}2.5 用户管理user模块创建运维专用账户ansible all -m user -a nameops uid2000 groupwheel shell/bin/bash3. 高效配置技巧与避坑指南3.1 并行执行优化通过-f参数控制并发数默认5ansible all -m ping -f 10 # 同时检测10台主机3.2 错误处理机制忽略特定错误继续执行- name: 尝试创建目录 file: path: /opt/logs state: directory ignore_errors: yes3.3 配置幂等性验证使用-C参数进行模拟运行ansible-playbook deploy.yml -C # 只显示变更不会实际执行4. 常用模块速查表实战精华模块典型场景示例命令file文件/目录管理ansible web -m file -a path/data statedirectorycron计划任务管理ansible db -m cron -a namebackup minute0 job/bin/backup.shmount挂载文件系统ansible storage -m mount -a src/dev/sdb1 path/data fstypeext4 statemountedlineinfile文本行修改ansible all -m lineinfile -a path/etc/ssh/sshd_config regexp^#PermitRootLogin linePermitRootLogin nostat文件状态检查ansible app -m stat -a path/var/run/app.pid5. 进阶实战批量部署Web服务以下playbook示例可在5分钟内完成Nginx集群部署--- - hosts: web_servers become: yes tasks: - name: 安装Nginx yum: name: nginx state: latest - name: 部署配置文件 template: src: templates/nginx.conf.j2 dest: /etc/nginx/nginx.conf notify: 重启Nginx - name: 启动服务 systemd: name: nginx enabled: yes state: started handlers: - name: 重启Nginx systemd: name: nginx state: restarted执行playbookansible-playbook nginx_deploy.yml实际项目中建议将这类常用操作封装成可复用的role。例如创建roles/nginx目录后结构如下roles/nginx/ ├── tasks │ ├── install.yml │ ├── config.yml │ └── main.yml ├── templates │ └── nginx.conf.j2 └── vars └── main.yml

更多文章