Ansible Playbook 自动化管理教程
Ansible 是一款无需在被管理节点上安装代理(Agentless)的自动化运维工具,通过 SSH 协议即可批量管理多台服务器。Ansible Playbook 以 YAML 格式编写,可以将复杂的运维操作编排为可复用、可版本控制的代码。本文将介绍如何在搬瓦工 VPS 上安装和使用 Ansible 进行自动化管理。
一、环境要求
- 控制节点:安装 Ansible 的机器,可以是本地电脑或一台搬瓦工 VPS。
- 被管理节点:只需 SSH 访问和 Python 即可,无需安装额外软件。
- Python:Ansible 基于 Python,控制节点需要 Python 3.9+。
- SSH 密钥:推荐使用 SSH 密钥认证实现免密登录。
二、安装 Ansible
2.1 使用 apt 安装(Ubuntu/Debian)
apt update
apt install software-properties-common -y
add-apt-repository --yes --update ppa:ansible/ansible
apt install ansible -y
2.2 使用 pip 安装(推荐)
apt install python3-pip -y
pip3 install ansible
2.3 验证安装
ansible --version
三、配置 Inventory
Inventory 文件定义了被管理的主机列表。创建 /etc/ansible/hosts 或项目目录下的 inventory.ini:
[webservers]
web1 ansible_host=192.168.1.10 ansible_user=root
web2 ansible_host=192.168.1.11 ansible_user=root
[dbservers]
db1 ansible_host=192.168.1.20 ansible_user=root
[all:vars]
ansible_python_interpreter=/usr/bin/python3
ansible_ssh_private_key_file=~/.ssh/id_rsa
测试连通性:
ansible all -i inventory.ini -m ping
四、编写 Playbook
4.1 基础示例:系统初始化
创建 init-server.yml:
---
- name: 初始化服务器
hosts: all
become: yes
vars:
timezone: Asia/Shanghai
swap_size: 2G
tasks:
- name: 更新系统包
apt:
update_cache: yes
upgrade: dist
when: ansible_os_family == "Debian"
- name: 安装常用工具
apt:
name:
- vim
- curl
- wget
- htop
- git
- ufw
- fail2ban
state: present
- name: 设置时区
timezone:
name: "{{ timezone }}"
- name: 配置 SSH 安全
lineinfile:
path: /etc/ssh/sshd_config
regexp: "{{ item.regexp }}"
line: "{{ item.line }}"
loop:
- { regexp: '^#?PermitRootLogin', line: 'PermitRootLogin prohibit-password' }
- { regexp: '^#?PasswordAuthentication', line: 'PasswordAuthentication no' }
notify: 重启 SSH
- name: 启用防火墙
ufw:
state: enabled
policy: deny
direction: incoming
- name: 开放 SSH 端口
ufw:
rule: allow
port: '22'
proto: tcp
handlers:
- name: 重启 SSH
service:
name: sshd
state: restarted
4.2 运行 Playbook
ansible-playbook -i inventory.ini init-server.yml
添加 --check 参数可以进行干运行(不实际执行):
ansible-playbook -i inventory.ini init-server.yml --check
五、部署 Web 应用示例
创建 deploy-webapp.yml:
---
- name: 部署 Web 应用
hosts: webservers
become: yes
vars:
app_name: myapp
app_dir: /opt/myapp
app_repo: https://github.com/yourname/myapp.git
app_branch: main
nginx_domain: app.yourdomain.com
tasks:
- name: 安装 Nginx
apt:
name: nginx
state: present
- name: 安装 Node.js
shell: |
curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
apt install -y nodejs
args:
creates: /usr/bin/node
- name: 克隆代码仓库
git:
repo: "{{ app_repo }}"
dest: "{{ app_dir }}"
version: "{{ app_branch }}"
force: yes
- name: 安装依赖
npm:
path: "{{ app_dir }}"
state: present
- name: 构建项目
command: npm run build
args:
chdir: "{{ app_dir }}"
- name: 配置 Nginx
template:
src: templates/nginx.conf.j2
dest: "/etc/nginx/sites-available/{{ app_name }}"
notify: 重载 Nginx
- name: 启用站点
file:
src: "/etc/nginx/sites-available/{{ app_name }}"
dest: "/etc/nginx/sites-enabled/{{ app_name }}"
state: link
notify: 重载 Nginx
handlers:
- name: 重载 Nginx
service:
name: nginx
state: reloaded
六、使用 Role 组织代码
当 Playbook 变得复杂时,使用 Role 来组织代码结构:
# 创建 Role 目录结构
ansible-galaxy init roles/webserver
ansible-galaxy init roles/database
目录结构如下:
roles/
webserver/
tasks/main.yml
handlers/main.yml
templates/
files/
vars/main.yml
defaults/main.yml
在 Playbook 中引用 Role:
---
- name: 部署完整应用栈
hosts: all
become: yes
roles:
- role: webserver
when: "'webservers' in group_names"
- role: database
when: "'dbservers' in group_names"
七、Ansible Vault 加密
使用 Ansible Vault 加密敏感数据:
# 创建加密变量文件
ansible-vault create vars/secrets.yml
# 编辑加密文件
ansible-vault edit vars/secrets.yml
# 使用加密变量运行 Playbook
ansible-playbook -i inventory.ini site.yml --ask-vault-pass
加密变量文件示例内容:
db_password: "your_secure_password"
api_key: "your_api_key_here"
ssl_private_key: |
-----BEGIN PRIVATE KEY-----
...
八、常用 Ad-Hoc 命令
# 检查所有主机的磁盘使用情况
ansible all -i inventory.ini -a "df -h"
# 批量重启服务
ansible webservers -i inventory.ini -m service -a "name=nginx state=restarted"
# 复制文件到所有主机
ansible all -i inventory.ini -m copy -a "src=/local/file dest=/remote/path"
# 批量创建用户
ansible all -i inventory.ini -m user -a "name=deploy state=present groups=sudo"
九、常见问题
SSH 连接超时
在 ansible.cfg 中增加超时时间:
[defaults]
timeout = 30
[ssh_connection]
ssh_args = -o ConnectTimeout=30 -o ServerAliveInterval=15
Python 解释器报错
在 Inventory 中明确指定 Python 路径:
ansible_python_interpreter=/usr/bin/python3
权限不足
确保 Playbook 中添加了 become: yes,或者使用 --become 参数运行。
总结
Ansible 是管理多台搬瓦工 VPS 的利器,通过 Playbook 可以将运维操作标准化和自动化,大幅提高效率并减少人为错误。搬瓦工 VPS 选购请参考 全部方案,使用优惠码 NODESEEK2026 享受 6.77% 折扣。