当服务器数量超过 3 台,手动 SSH 进去一台台配置就成了低效且易出错的工作。Ansible 是目前最流行的无代理自动化运维工具——控制机(你的本地电脑或跳板机)通过 SSH 推送任务到目标服务器,无需在目标服务器安装任何客户端。本文构建一套可管理多台香港服务器的 Ansible 自动化运维体系。
一、Ansible 工作原理
<code">
你的本地机器(控制节点)
│ SSH 推送(无需在目标机器安装 Agent)
├──→ 香港 VPS 1(Web Server)
├──→ 香港 VPS 2(数据库服务器)
└──→ 香港 VPS 3(Redis 缓存服务器)
控制流程:
Inventory(主机清单) → Playbook(任务剧本) → 目标服务器执行
二、安装 Ansible(控制机)
<code"># macOS 控制机 brew install ansible # Linux 控制机(Ubuntu) apt update && apt install -y ansible # 验证安装 ansible --version
三、项目目录结构
<code">/ansible-hk/ ├── inventory/ │ ├── production.ini # 生产环境主机清单 │ └── staging.ini # 测试环境主机清单 ├── group_vars/ │ ├── all.yml # 所有主机共用变量 │ ├── web.yml # Web 组变量 │ └── db.yml # 数据库组变量 ├── host_vars/ │ └── hk-web-1.yml # 特定主机变量 ├── roles/ │ ├── common/ # 基础配置角色 │ ├── nginx/ # Nginx 安装角色 │ ├── docker/ # Docker 安装角色 │ └── app-deploy/ # 应用部署角色 ├── site.yml # 主 Playbook(完整部署) ├── security.yml # 安全加固 Playbook └── ansible.cfg # Ansible 全局配置
四、Inventory 主机清单
<code"># inventory/production.ini [web] hk-web-1 ansible_host=1.2.3.4 ansible_port=22 ansible_user=root hk-web-2 ansible_host=1.2.3.5 [db] hk-db-1 ansible_host=1.2.3.6 [redis] hk-redis-1 ansible_host=1.2.3.7 # 分组继承 [hk:children] web db redis [hk:vars] ansible_ssh_private_key_file=~/.ssh/hk_deploy_key ansible_python_interpreter=/usr/bin/python3
<code"># ansible.cfg(全局配置) [defaults] inventory = ./inventory/production.ini remote_user = root host_key_checking = False # 首次连接不验证主机指纹(CI/CD 环境) forks = 10 # 并行执行的主机数 timeout = 30 log_path = ./ansible.log [ssh_connection] ssh_args = -o ControlMaster=auto -o ControlPersist=60s # SSH 连接复用(加速) pipelining = True # 减少 SSH 连接次数(显著提速)
五、常用 Ad-Hoc 命令(快速执行单个任务)
<code"># 测试连通性 ansible all -m ping # 在所有 Web 服务器执行命令 ansible web -m command -a "uptime" ansible web -m shell -a "df -h | grep /dev/vda" # 批量推送文件 ansible web -m copy -a "src=./nginx.conf dest=/etc/nginx/nginx.conf backup=yes" # 批量安装软件包 ansible web -m apt -a "name=htop,iotop state=present update_cache=yes" # 批量重启服务 ansible web -m service -a "name=nginx state=restarted" # 查看所有主机的 Facts(系统信息) ansible hk-web-1 -m setup | grep -A3 "ansible_memory_mb"
六、Playbook:基础服务器安全加固
<code"># security.yml
---
- name: 香港服务器安全加固
hosts: all
become: yes # sudo 提权
vars:
ssh_port: 2222
admin_user: deploy
admin_pubkey: "{{ lookup('file', '~/.ssh/id_ed25519.pub') }}"
tasks:
- name: 更新系统软件包
apt:
update_cache: yes
upgrade: dist
cache_valid_time: 3600
- name: 安装安全工具
apt:
name:
- fail2ban
- ufw
- unattended-upgrades
state: present
- name: 创建运维用户
user:
name: "{{ admin_user }}"
shell: /bin/bash
groups: sudo
append: yes
- name: 部署 SSH 公钥
authorized_key:
user: "{{ admin_user }}"
key: "{{ admin_pubkey }}"
state: present
- name: 修改 SSH 端口
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?Port '
line: "Port {{ ssh_port }}"
backup: yes
- name: 禁止 root 直接 SSH 登录
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?PermitRootLogin '
line: 'PermitRootLogin no'
- name: 禁止密码登录(仅 SSH Key)
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?PasswordAuthentication '
line: 'PasswordAuthentication no'
- name: 重启 SSH 服务
service:
name: sshd
state: restarted
- name: 配置 UFW 防火墙
ufw:
rule: allow
port: "{{ item }}"
proto: tcp
loop:
- "{{ ssh_port }}"
- "80"
- "443"
- name: 启用 UFW
ufw:
state: enabled
policy: deny
direction: incoming
- name: 启动 Fail2ban
service:
name: fail2ban
state: started
enabled: yes
七、Role:Nginx 安装与配置
<code"># roles/nginx/ 目录结构
# roles/nginx/
# ├── tasks/main.yml
# ├── handlers/main.yml
# ├── templates/nginx.conf.j2
# └── defaults/main.yml
# roles/nginx/tasks/main.yml
---
- name: 安装 Nginx
apt:
name: nginx
state: present
update_cache: yes
- name: 部署 Nginx 配置(使用 Jinja2 模板)
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
backup: yes
notify: reload nginx # 配置变更时触发 handler
- name: 部署站点配置
template:
src: "{{ item.src }}"
dest: "/etc/nginx/sites-available/{{ item.name }}"
loop: "{{ nginx_sites }}"
notify: reload nginx
- name: 启用站点
file:
src: "/etc/nginx/sites-available/{{ item.name }}"
dest: "/etc/nginx/sites-enabled/{{ item.name }}"
state: link
loop: "{{ nginx_sites }}"
- name: 确保 Nginx 开机自启
service:
name: nginx
state: started
enabled: yes
# roles/nginx/handlers/main.yml
---
- name: reload nginx
service:
name: nginx
state: reloaded
<code"># roles/nginx/templates/nginx.conf.j2(Jinja2 模板)
worker_processes {{ ansible_processor_vcpus }}; # 自动获取 CPU 核数
events {
worker_connections {{ nginx_worker_connections | default(65536) }};
use epoll;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
server_tokens off;
{% if nginx_gzip_enabled | default(true) %}
gzip on;
gzip_comp_level 4;
gzip_types text/plain text/css application/json application/javascript;
{% endif %}
include /etc/nginx/sites-enabled/*;
}
八、Ansible Vault:加密敏感变量
<code"># 创建加密的变量文件(存储数据库密码、API Key 等)
ansible-vault create group_vars/all/vault.yml
# 输入 Vault 密码后,在编辑器中写入:
# vault_db_password: "SuperSecretPassword123"
# vault_stripe_key: "sk_live_xxxx"
# 在普通变量文件中引用 Vault 变量
# group_vars/all/vars.yml
db_password: "{{ vault_db_password }}"
stripe_key: "{{ vault_stripe_key }}"
# 执行 Playbook 时输入 Vault 密码
ansible-playbook site.yml --ask-vault-pass
# 或者使用密码文件(CI/CD 环境)
echo "vault_password" > .vault_pass
ansible-playbook site.yml --vault-password-file .vault_pass
九、一键全量部署 Playbook
<code"># site.yml(主 Playbook,完整部署)
---
- name: 基础安全加固
import_playbook: security.yml
- name: 安装公共组件
hosts: all
roles:
- common # 时区、hostname、swap、BBR 等
- name: 部署 Web 服务器
hosts: web
roles:
- docker
- nginx
- app-deploy
- name: 部署数据库
hosts: db
roles:
- mysql
- name: 部署缓存服务
hosts: redis
roles:
- redis
<code"># 执行完整部署(--check 只检查不实际执行) ansible-playbook site.yml --check # 正式执行 ansible-playbook site.yml # 只执行带特定标签的任务 ansible-playbook site.yml --tags "nginx,ssl" # 只针对特定主机执行 ansible-playbook site.yml --limit hk-web-1 # 查看执行计划(diff 模式,显示文件变更内容) ansible-playbook site.yml --diff
十、总结
Ansible 的核心价值是幂等性——同一个 Playbook 执行多次,结果始终一致,已完成的步骤不会重复执行。这让服务器配置真正做到了「代码即文档」:新人加入团队,一条命令 ansible-playbook site.yml 即可复现所有服务器的完整配置状态,彻底告别「手工搭建、口口相传」的运维模式。
