forks、strategy、serial、throttle、async
gather_facts: false,需要時用 setup: gather_subset 去選擇要什麼資訊。forks (預設 5),並視情況使用 strategy: free。package: name: [a,b,c] )。shell/command ,有 module 就用 module。serial 滾動佈署、throttle 限制重操作的並行。[defaults]
forks = 20
timeout = 30
gathering = smart
[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o ControlPath=~/.ssh/ansible-ctl-%%r@%%h:%%p
提高 forks 要注意遠端機器跟網路的負載,建議慢慢增加並觀察。
---
# perf-demo.yml
- name: Day19 performance & parallel demo
hosts: all
gather_facts: false
strategy: free # 各主機不互等,加快整體時間
serial: 50% # 滾動佈署,降低一次性風險
any_errors_fatal: true
max_fail_percentage: 20
tasks:
- name: Prepare working dir
file:
path: /tmp/perf-demo
state: directory
mode: '0755'
- name: Create multiple files (合併操作減少 I/O)
file:
path: "/tmp/perf-demo/{{ item }}"
state: touch
mode: '0644'
loop:
- a.txt
- b.txt
- c.txt
- name: Simulate heavy work in background (async)
shell: sleep 10 && echo done > /tmp/perf-demo/async.txt
async: 120 # 最多允許 120 秒
poll: 0 # 不中斷等待,背景執行
register: heavy_async
- name: Throttled operation (限制單任務併發)
lineinfile:
path: /tmp/perf-demo/throttle.txt
line: "{{ inventory_hostname }} updated"
create: yes
throttle: 2 # 同時最多 2 台主機執行
- name: Run once for all (一次性前置)
debug:
msg: "Generating shared artifact..."
run_once: true
- name: Wait for background job to finish
async_status:
jid: "{{ heavy_async.ansible_job_id }}"
register: heavy_status
until: heavy_status.finished
retries: 30
delay: 2
來執行看看
# 實際執行時可提高 forks
ansible-playbook -i inventory.ini perf-demo.yml -f 20
strategy: free:同一個 Playbook 的主機不互等,誰先完成誰先跑下一步。serial:分批滾動佈署;搭配 max_fail_percentage、any_errors_fatal 控制失敗門檻。throttle:限制「單一任務」同時併發數,避免重操作壓垮資源。async/poll:長耗時任務改背景執行;poll: 0 先放背景,再用 async_status 追蹤完成。-vv flag 觀察瓶頸 (等待、連線、任務耗時) 後再根據問題做調整。forks,同時監控目標端負載與網路是否可以負擔。serial 滾動,並且設定 max_fail_percentage、any_errors_fatal。async/poll,避免阻塞整體流程。pipelining、ControlPersist 與合理 SSH 參數。strategy: free 卻沒變快?瓶頸可能在單一任務本身 (I/O),或 serial 批次太小。forks 提太大導致失敗:遠端主機資源不足或網路擁塞,。async 任務沒結束:提高 async 上限並以 async_status 追蹤,或檢查遠端程式實際耗時。throttle 看似無效:僅限制該任務的同時併發,不影響其他任務或整體 forks。strategy: free,實測 f 5/20/50 差異。serial: 25% 與 max_fail_percentage,觀察滾動行為。async/poll,並用 async_status 輪詢完成狀態。明天我們來做自己的模組