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

如何用Ansible在Windows上异步运行多PowerShell进程并维持固定并发数

目标

我拥有200多个Azure订阅,需要针对每个订阅运行PowerShell脚本以完成相关操作。

现有实现

为提升运行效率,我开发了如下Ansible剧本,在单台指定主机上异步运行PowerShell脚本。
我最初考虑使用throttle关键字,但它限制的是特定任务的worker数量,而我仅有1个worker主机。
因此我将订阅列表拆分为每组9个的批次,借助Ansible的异步特性,每个批次同时运行9个PowerShell进程。
必须为每个订阅启动独立的PowerShell进程,因为使用PowerShell多线程(或作业)时,会出现订阅作用域数据泄漏到其他作用域的异常错误。

待解决问题

当前方案可正常运行,但存在一个明显缺陷:必须等待批次中最后一个PowerShell进程完成后,才能启动下一个批次。
我希望实现维持最大9个并发进程的机制,当其中一个进程完成后立即启动下一个订阅的进程,请问是否有相关实现经验?

代码

main.yml

- name: Subscription list
  ansible.builtin.set_fact:
    all_subscriptions:
      - subscription1
      - subscription2
    [...]
      - subscription200

- name: Split subscriptions into batches
  vars:
    batch_size: 9
  ansible.builtin.set_fact:
    batches: "{{ all_subscriptions | batch(batch_size) }}"

- name: Process each batch
  ansible.builtin.include_tasks: process_batch.yml
  loop: "{{ batches }}"
  loop_control:
    loop_var: batch_items

process_batch.yml

- name: Execute PowerShell commands for batch
  ansible.windows.win_powershell:
    script: "{{ lookup('ansible.builtin.file', 'files/script.ps1') }}"
    executable: pwsh.exe
    error_action: stop
    parameters:
      SubscriptionData: "{{ subscription_item | to_json }}"
  async: 1500 # Allow each task up to 25 minutes to run
  poll: 0     # Do not wait for the task to finish; continue immediately
  register: async_jobs
  loop: "{{ batch_items }}"
  loop_control:
    loop_var: subscription_item

- name: Wait for all tasks in the batch to finish
  ansible.builtin.async_status:
    jid: "{{ item.ansible_job_id }}"
  register: job_status
  until: job_status.finished
  retries: 300
  loop: "{{ async_jobs.results }}"
  when: item.ansible_job_id is defined

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:17:03