提交工单

用Ansible批量管理香港服务器:零停机滚动更新 + 配置统一管理完整实战

文档更新于

管理 5 台服务器还可以手动 SSH,管理 20 台服务器手动操作就是噩梦——每台都要执行相同命令,改一处配置要重复 20 次,遗漏某台服务器会导致配置漂移。Ansible 用声明式 YAML Playbook 描述服务器的期望状态,一条命令同时在所有服务器上执行,幂等、可重复、可版本管理。


一、Ansible 安装与 Inventory 配置

<code"># 在控制机(你的本地或跳板机)安装 Ansible
pip install ansible

# 创建项目结构
mkdir -p ~/ansible-hk/{inventories,roles,playbooks,group_vars,host_vars}
cd ~/ansible-hk

# /inventories/production.ini(服务器清单)
[web_servers]
hk-web-01 ansible_host=10.0.0.1 ansible_user=ubuntu
hk-web-02 ansible_host=10.0.0.2 ansible_user=ubuntu
hk-web-03 ansible_host=10.0.0.3 ansible_user=ubuntu

[db_servers]
hk-db-01 ansible_host=10.0.0.10 ansible_user=ubuntu
hk-db-02 ansible_host=10.0.0.11 ansible_user=ubuntu

[cache_servers]
hk-cache-01 ansible_host=10.0.0.20 ansible_user=ubuntu

# 组变量(所有服务器共用)
[all:vars]
ansible_ssh_private_key_file=~/.ssh/hk_servers
ansible_python_interpreter=/usr/bin/python3

[production:children]
web_servers
db_servers
cache_servers

二、基础 Playbook:批量安全加固

<code"># playbooks/security-baseline.yml
---
- name: 香港服务器安全基线配置
  hosts: all
  become: true   # sudo 权限
  gather_facts: true

  vars:
    ssh_port: 2222
    allowed_users:
      - deploy
      - ubuntu

  tasks:
    - name: 安装安全工具
      apt:
        name:
          - fail2ban
          - ufw
          - unattended-upgrades
          - auditd
        state: present
        update_cache: true

    - name: 配置 SSH 安全选项
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "{{ item.regexp }}"
        line: "{{ item.line }}"
        backup: true
      loop:
        - {regexp: '^#?Port', line: "Port {{ ssh_port }}"}
        - {regexp: '^#?PermitRootLogin', line: 'PermitRootLogin no'}
        - {regexp: '^#?PasswordAuthentication', line: 'PasswordAuthentication no'}
        - {regexp: '^#?X11Forwarding', line: 'X11Forwarding no'}
      notify: reload sshd

    - name: 配置 UFW 防火墙规则
      ufw:
        rule: allow
        port: "{{ item }}"
        proto: tcp
      loop:
        - "{{ ssh_port }}"
        - "80"
        - "443"

    - name: 启用 UFW
      ufw:
        state: enabled
        policy: deny

    - name: 配置自动安全更新
      copy:
        content: |
          APT::Periodic::Update-Package-Lists "1";
          APT::Periodic::Unattended-Upgrade "1";
          APT::Periodic::AutocleanInterval "7";
        dest: /etc/apt/apt.conf.d/20auto-upgrades

    - name: 启动并设置 fail2ban 开机自启
      systemd:
        name: fail2ban
        state: started
        enabled: true

  handlers:
    - name: reload sshd
      systemd:
        name: sshd
        state: reloaded

三、零停机滚动更新 Playbook

<code"># playbooks/rolling-update.yml
---
- name: 零停机滚动更新 Web 应用
  hosts: web_servers
  serial: 1          # 每次只更新一台(保证始终有服务在运行)
  # serial: "30%"    # 或每次更新30%的服务器
  become: true

  vars:
    app_image: "registry.yourdomain.com/myapp/backend:{{ image_tag }}"
    health_check_url: "http://localhost:8000/health"
    haproxy_backend: "app_backend"
    haproxy_host: "10.0.0.100"

  tasks:
    - name: 从 HAProxy 摘除当前节点(停止接收流量)
      community.general.haproxy:
        host: "{{ inventory_hostname }}"
        backend: "{{ haproxy_backend }}"
        state: disabled
        socket: /var/run/haproxy/admin.sock
      delegate_to: "{{ haproxy_host }}"

    - name: 等待当前连接处理完成
      wait_for:
        timeout: 30

    - name: 拉取新版本镜像
      docker_image:
        name: "{{ app_image }}"
        source: pull

    - name: 停止旧容器
      docker_container:
        name: myapp
        state: stopped
      ignore_errors: true

    - name: 启动新版本容器
      docker_container:
        name: myapp
        image: "{{ app_image }}"
        state: started
        restart_policy: unless-stopped
        ports:
          - "127.0.0.1:8000:8000"
        env_file: /opt/myapp/.env

    - name: 等待健康检查通过
      uri:
        url: "{{ health_check_url }}"
        status_code: 200
      register: health_result
      until: health_result.status == 200
      retries: 10
      delay: 5

    - name: 将节点重新加入 HAProxy
      community.general.haproxy:
        host: "{{ inventory_hostname }}"
        backend: "{{ haproxy_backend }}"
        state: enabled
        socket: /var/run/haproxy/admin.sock
      delegate_to: "{{ haproxy_host }}"

    - name: 打印更新结果
      debug:
        msg: "{{ inventory_hostname }} 更新完成,新版本: {{ image_tag }}"
<code"># 执行滚动更新(传入镜像版本号)
ansible-playbook \
  -i inventories/production.ini \
  playbooks/rolling-update.yml \
  -e "image_tag=v2.1.0"

四、Role 封装(Nginx 配置管理)

<code"># roles/nginx/tasks/main.yml
---
- name: 安装 Nginx
  apt:
    name: nginx
    state: present

- name: 部署 Nginx 主配置
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    validate: 'nginx -t -c %s'   # 验证语法后再替换
    backup: true
  notify: reload nginx

- name: 部署虚拟主机配置
  template:
    src: vhost.conf.j2
    dest: /etc/nginx/sites-available/{{ vhost_domain }}.conf
  notify: reload nginx

- name: 启用虚拟主机
  file:
    src: /etc/nginx/sites-available/{{ vhost_domain }}.conf
    dest: /etc/nginx/sites-enabled/{{ vhost_domain }}.conf
    state: link
  notify: reload nginx

# roles/nginx/templates/vhost.conf.j2
server {
    listen 443 ssl http2;
    server_name {{ vhost_domain }};

    ssl_certificate {{ ssl_cert_path }};
    ssl_certificate_key {{ ssl_key_path }};

    location / {
        proxy_pass http://{{ backend_host }}:{{ backend_port }};
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

五、Ansible Vault:加密敏感信息

<code"># 创建加密的 Vault 文件(存储密码、API Key 等)
ansible-vault create group_vars/all/vault.yml
# 输入 Vault 密码后,在编辑器中添加:
vault_db_password: "ProductionDBPass2026!"
vault_redis_password: "RedisPass2026!"
vault_stripe_secret: "sk_live_xxxxxxxxxxxxx"
vault_feishu_webhook: "https://open.feishu.cn/..."

# 在 group_vars/all/vars.yml 中引用(不加密的变量文件)
db_password: "{{ vault_db_password }}"
redis_password: "{{ vault_redis_password }}"

# 执行 Playbook 时解密
ansible-playbook playbooks/deploy.yml \
  --ask-vault-pass    # 手动输入密码

# 或使用密码文件(CI/CD 中使用)
ansible-playbook playbooks/deploy.yml \
  --vault-password-file ~/.vault_pass

六、常用 Ad-hoc 命令(临时操作)

<code"># 检查所有服务器磁盘使用
ansible all -i inventories/production.ini \
  -m shell -a "df -h / | tail -1" | grep -v CHANGED

# 批量重启 Nginx
ansible web_servers -i inventories/production.ini \
  -m systemd -a "name=nginx state=reloaded" --become

# 查看所有服务器的 MySQL 版本
ansible db_servers -i inventories/production.ini \
  -m shell -a "mysql --version" --become

# 批量推送文件
ansible all -i inventories/production.ini \
  -m copy -a "src=./config/app.conf dest=/etc/myapp/app.conf mode=0644" \
  --become

# 收集所有服务器的 facts(硬件信息)
ansible all -i inventories/production.ini -m setup \
  --filter "ansible_memory_mb"

七、总结

Ansible 将运维从「重复的手工操作」升级为「声明式的代码管理」。Playbook 存储在 Git 中,每次变更有记录、可回滚;Vault 加密敏感信息,安全可审计;滚动更新逻辑让多台香港服务器的应用升级安全可控。10 台服务器的批量操作从 30 分钟缩短到 3 分钟,是 DevOps 工程化最具性价比的自动化投入。

需要服务器?

香港 / 美国 / 日本服务器与 VPS,工程师 7×24 在线,工单平均 10 分钟内响应。