You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Serial部署应用时,如何在Ansible中循环操作负载均衡主机?

分批部署应用主机并切换负载均衡配置的Ansible Playbook结构

以下是符合需求的Playbook编写方案,核心是通过serial:25%分批处理应用主机,同时在批次前后统一对所有边缘节点执行负载均衡配置修改:

---
- name: 分批部署tag_Type_app主机并更新edge节点负载均衡配置
  hosts: tag_Type_app
  serial: 25%
  gather_facts: yes

  pre_tasks:
    - name: 从所有edge节点的负载均衡配置中移除当前批次应用主机
      blockinfile:
        path: /etc/nginx/conf.d/upstream.conf  # 替换为实际负载均衡配置文件路径
        marker: "<!-- {mark} ANSIBLE MANAGED BLOCK FOR {{ inventory_hostname }} -->"
        block: ""
        state: absent
      delegate_to: "{{ edge_host }}"
      loop: "{{ groups['tag_Type_edge'] }}"
      loop_control:
        loop_var: edge_host
      run_once: true
      become: yes  # 若修改配置需要root权限则添加

  tasks:
    - name: 执行应用主机的部署操作
      # 此处替换为你的实际部署步骤,例如:
      # yum: name=your-app state=latest
      # systemd: name=your-app state=restarted enabled=yes
      debug:
        msg: "正在完成 {{ inventory_hostname }} 的应用部署"

  post_tasks:
    - name: 将当前批次应用主机添加回所有edge节点的负载均衡配置
      blockinfile:
        path: /etc/nginx/conf.d/upstream.conf  # 同pre_tasks中的配置文件路径
        marker: "<!-- {mark} ANSIBLE MANAGED BLOCK FOR {{ inventory_hostname }} -->"
        block: |
          server {{ inventory_hostname }}:8000 max_fails=3 fail_timeout=10s;  # 替换为实际上游服务器配置
        state: present
      delegate_to: "{{ edge_host }}"
      loop: "{{ groups['tag_Type_edge'] }}"
      loop_control:
        loop_var: edge_host
      run_once: true
      become: yes

关键细节说明:

  • serial:25%:自动将80+台应用主机分为4批左右执行,每批处理约20台,降低部署风险
  • run_once: true:确保同一批次内仅执行一次边缘节点的配置修改,避免重复操作
  • delegate_to + 循环tag_Type_edge组:遍历所有边缘节点,在每台边缘主机上执行配置文件修改
  • blockinfile的marker:通过应用主机名标记专属配置块,确保移除/添加操作精准对应目标主机
  • become: yes:如果修改边缘节点的配置文件需要管理员权限,务必添加此参数

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 14:18:09