大家好,我是程序员柏风,AI 最全的 Vibecoding 学习地图 http://coderoadmap.cn 作者。
Ansible
这一课你将能做到
- 用 Ansible 自动化配置服务器
- 编写 Playbook 批量部署应用
- 管理变量、模板、角色
为什么要学
手动登录每台服务器配置环境,10 台服务器就要重复 10 次。Ansible 用 SSH 批量执行,一次编写,处处运行。
人话:Ansible 是「遥控器」,一键控制所有服务器。
跟着做
步骤 1:安装
# macOS
brew install ansible
# Ubuntu
sudo apt install ansible
步骤 2:Inventory(主机清单)
# inventory.ini
[webservers]
web1 ansible_host=192.168.1.10 ansible_user=ubuntu
web2 ansible_host=192.168.1.11 ansible_user=ubuntu
[dbservers]
db1 ansible_host=192.168.1.20 ansible_user=ubuntu
[all:vars]
ansible_ssh_private_key_file=~/.ssh/mykey.pem
步骤 3:Ad-hoc 命令
# 测试连接
ansible all -i inventory.ini -m ping
# 执行命令
ansible webservers -i inventory.ini -m shell -a "uptime"
# 安装软件
ansible webservers -i inventory.ini -m apt -a "name=nginx state=present"
步骤 4:Playbook
# playbook.yml
---
- name: Setup web servers
hosts: webservers
become: yes
tasks:
- name: Install nginx
apt:
name: nginx
state: present
update_cache: yes
- name: Start nginx
service:
name: nginx
state: started
enabled: yes
- name: Copy index.html
copy:
src: ./index.html
dest: /var/www/html/index.html
notify: Restart nginx
handlers:
- name: Restart nginx
service:
name: nginx
state: restarted
# 执行
ansible-playbook -i inventory.ini playbook.yml
步骤 5:变量
# group_vars/webservers.yml
---
app_name: myapp
app_port: 3000
db_host: 192.168.1.20
# playbook.yml
- name: Setup app
hosts: webservers
vars_files:
- group_vars/webservers.yml
tasks:
- name: Create app directory
file:
path: "/var/www/{{ app_name }}"
state: directory
- name: Start app
command: "node app.js --port {{ app_port }}"
步骤 6:模板
# templates/nginx.conf.j2
server {
listen 80;
server_name {{ domain }};
location / {
proxy_pass http://localhost:{{ app_port }};
}
}
# playbook.yml
- name: Configure nginx
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/sites-available/{{ app_name }}
vars:
domain: example.com
面试常问
-
Ansible 和 Terraform 区别? Terraform 管基础设施(创建 EC2、VPC);Ansible 管配置(装软件、改配置)。
-
Ansible 和 Chef/Puppet 区别? Ansible 无代理(agentless),用 SSH;Chef/Puppet 需要装 agent。
自测三问
- Inventory 的作用?
- Handler 什么时候触发?
- 如何管理多环境变量?
小结
Ansible 用 SSH 批量配置服务器,Playbook 定义任务,模板和变量实现复用。