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

如何在Ansible中复用SSO令牌并并行操作多主机以提速?

解决方案:复用SSO令牌并行操作多台主机

要解决复用单个SSO令牌同时并行处理225台主机的问题,你可以通过拆分Playbook为多Play结构,结合Ansible的原生并行能力实现,具体调整如下:

修改后的Playbook代码

---
- name: 获取SSO令牌
  hosts: localhost
  connection: local
  vars_files: ../vars/site_vars.yml
  tasks:
    - name: 生成oVirt SSO令牌
      ovirt_auth:
        url: https://rhevm.mgmt.local/ovirt-engine/api
        username: admin@internal
        password: "{{ ADMIN_PASS }}"
      register: ovirt_auth_result

- name: 并行启动虚拟机
  hosts: virtual_machines
  connection: local
  vars_files: ../vars/site_vars.yml
  vars:
    ovirt_auth: "{{ hostvars['localhost']['ovirt_auth_result']['ovirt_auth'] }}"
  tasks:
    - name: 启动目标虚拟机
      ovirt_vm:
        auth: "{{ ovirt_auth }}"
        state: running
        name: "{{ inventory_hostname.split('.') | first }}"
        template: "template{{ hostvars[inventory_hostname]['cluster_name'][-1] }}"
        cluster: "{{ hostvars[inventory_hostname]['cluster_name'] }}"

- name: 后续操作与令牌撤销
  hosts: localhost
  connection: local
  vars_files: ../vars/site_vars.yml
  vars:
    ovirt_auth: "{{ hostvars['localhost']['ovirt_auth_result']['ovirt_auth'] }}"
  tasks:
    - name: 等待10分钟让Cloud-Init配置IP
      shell: sleep 600

    - name: 撤销SSO令牌
      ovirt_auth:
        state: absent
        ovirt_auth: "{{ ovirt_auth }}"

核心原理与优化点

1. 多Play拆分实现令牌复用

  • 第一个Play仅在localhost执行,获取SSO令牌并通过register保存为变量ovirt_auth_result。
  • 后续Play通过hostvars['localhost']['ovirt_auth_result']['ovirt_auth']直接复用该令牌,全程仅生成一次SSO凭证,符合你的需求。

2. 利用Ansible原生并行能力

  • 第二个Play直接针对virtual_machines组执行,Ansible会根据forks配置(默认5)并行处理多台主机的启动任务。
  • 你可以通过以下方式提高并行数:
    • 在ansible.cfg中添加/修改:forks = 50(根据控制节点性能调整,建议不超过100)
    • 执行Playbook时通过命令行指定:ansible-playbook -f 50 your_playbook.yml

3. 可选优化:控制并行批次

如果担心一次性请求过多导致oVirt服务器压力过大,可以在第二个Play中添加serial参数,控制每批并行处理的主机数:

- name: 并行启动虚拟机
  hosts: virtual_machines
  connection: local
  serial: 20  # 每批处理20台主机
  # ... 其余配置不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:22:53