下面从概念 → 核心组件 → 实战示例 → 最佳实践四个层面,系统讲如何用 Ansible 做自动化运维。
Ansible 是一款**无代理(agentless)**的自动化运维工具,基于 SSH 管理目标主机。
定义“管理哪些机器”
[web]
192.168.1.10
192.168.1.11
[db]
192.168.1.20
执行具体操作的单位
常见模块:
command / shellyum / aptcopyserviceusertemplate用 YAML 描述“做什么”
# CentOS / RHEL
yum install -y ansible
# Ubuntu
apt install -y ansible
# /etc/ansible/hosts
[web]
192.168.1.10
192.168.1.11
ansible all -m ping
# deploy_nginx.yaml
- hosts: web
become: yes
tasks:
- name: Install nginx
yum:
name: nginx
state: present
- name: Start nginx
service:
name: nginx
state: started
enabled: yes
执行:
ansible-playbook deploy_nginx.yaml
- hosts: web
become: yes
tasks:
- name: Copy nginx config
copy:
src: ./nginx.conf
dest: /etc/nginx/nginx.conf
notify: Restart nginx
handlers:
- name: Restart nginx
service:
name: nginx
state: restarted
- hosts: web
vars:
pkg_name: nginx
tasks:
- name: Install package
yum:
name: "{{ pkg_name }}"
state: present
适合中大型运维项目
nginx/
├── tasks/main.yaml
├── handlers/main.yaml
├── templates/nginx.conf.j2
├── vars/main.yaml
使用:
- hosts: web
roles:
- nginx
✅ 优点:
| 场景 | Ansible 用法 |
|---|---|
| 批量装软件 | yum/apt |
| 配置管理 | copy/template |
| 服务启停 | service/systemd |
| 用户管理 | user |
| 定时任务 | cron |
| 应用发布 | git + copy + service |
| 安全加固 | 写 role |
✅ 使用 SSH Key,不用密码
✅ 拆分环境(prod / test)Inventory
✅ 敏感信息用 Ansible Vault
ansible-vault encrypt vars.yaml
✅ 幂等性设计(state=present / absent)
✅ CI/CD 集成(GitLab + Ansible)
如果你愿意,我可以:
你现在的运维场景是什么?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。