浅谈 Ansible Playbook 任务执行顺序组织
根据 strategy 和 serial 及 forks 数测试 Playbook 实际执行顺序。
基本概念
官方文档参考:
https://docs.ansible.com/ansible/latest/user_guide/playbooks_strategies.html
strategy
单个 play 级的调度策略,定义执行实例是否有步骤锁,即单个 task 是否等待其他实例执行完成。具体有两种方式:
- linear
Task execution is in lockstep per host batch as defined by serial (default all). Up to the fork limit of hosts will execute each task at the same time and then the next series of hosts until the batch is done, before going on to the next task.
默认值。在一个实例分组(serial)内,开始执行下一个任务需要等待所有
实例上一个任务执行完成。
- free
Task execution is as fast as possible per batch as defined by serial (default all). Ansible will not wait for other hosts to finish the current task before queuing more tasks for other hosts. All hosts are still attempted for the current task, but it prevents blocking new tasks for hosts that have already finished.
With the free strategy, unlike the default linear strategy, a host that is slow or stuck on a specific task won’t hold up the rest of the hosts and tasks.
非默认值。在一个实例分组(serial)内,开始执行下一个任务需要两个条件:
本实例
上一个任务执行完成,- 下一个任务的并发数(forks)有冗余。
forks
Maximum number of simultaneous connections Ansible made on each Task.
并发数。在单个分组和单个任务中,同时执行任务的最大实例数。
serial
默认值为 all
。定义单轮执行实例的数量。当一轮实例全部
执行完成后,下一轮的实例才会执行。
举例说明
定义5个实例数和2个任务,每个任务耗时5s:
- Node: C1\C2\C3\C4\C5
- Task:T1(5s), T2(5s)
先看看不同 strategy
场景:
场景1:strategy=linear, forks=5, (serial=all)
T1: C1-C2-C3-C4-C5 (5s)
T2: C1-C2-C3-C4-C5 (5s)
总耗时 10s
场景2: strategy=free, forks=5, (serial=all)
C1: T1->T2, 同时 C2: T1-> T2,同时 C3: T1->T2,同时 C4: T1->T2,同时 C5:T1->T2
总耗时 10s
在这个基础上修改 forks
数量,再看看不同 strategy
场景
场景3:strategy=linear, forks=3, (serial=all)
C1: T1->T2, 同时 C2: T1-> T2,同时 C3: T1->T2
C4: T1->T2,同时 C5:T1->T2
总耗时 20s
场景4:strategy=free, forks=3, (serial=all)
T1: C1-C2-C3 (5s)
T1: C4-C5 (5s)
T2: C1-C2-C3 (5s)
T2: C4-C5 (5s)
和场景3一样:20s
场景4和场景3表现一致:虽然单个实例之间互相无关联,但 C1-C2-C3 执行完 T1 前,T1最大 forks 为3,C4和C5需要等当前 T1 forks 有冗余时才能继续执行。
在 forks 为5时,修改 serial 的值:
场景5:strategy=linear, forks=5, serial=3
T1: C1-C2-C3 (5s)
T2: C1-C2-C3 (5s)
T1: C4-C5 (5s)
T2: C4-C5 (5s)
总耗时 20s
场景6:strategy=free, forks=5, serial=3
T1: C1-C2-C3 (5s)
T2: C1-C2-C3 (5s)
T1: C4-C5 (5s)
T2: C4-C5 (5s)
总耗时 20s
当 forks=3,serial=3 时:
场景7:strategy=linear, forks=3, serial=3
和场景5一致。
场景8:strategy=free, forks=3, serial=3
和场景6一致。
当 forks 小于 serial 时:
场景9:strategy=linear, forks=2, serial=3
T1: C1-C2 (5s)
T1: C3 (5s)
T2: C1-C2 (5s)
T2: C3 (5s)
T1: C4-C5 (5s)
T2: C4-C5 (5s)
总耗时 30s
场景10:strategy=free, forks=2, serial=3
T1: C1-C2 (5s)
T2: C1-C2 (5s)
T1: C3 (5s)
T2: C3 (5s)
T1: C4-C5 (5s)
T2: C4-C5 (5s)
总耗时 30s