一次在多个主机组上运行一个剧本 [英] Running a playbook on multiple host groups one at a time
问题描述
我想在我使用 group_by 模块动态创建的多个主机组上运行包含一些角色的剧本.
I want to run a playbook containing some roles on multiple host groups I create dynamically with the group_by module.
我可以像下面的例子那样做(ping 代替我的实际角色).
I'm able to do it like the example below (ping replacing my actual role).
我想知道是否有办法在循环中单独运行每个组,而不是列出所有实例 ID.我不想为每个实例 ID 创建一个重复的行.
I was wondering if there is a way to run each group separately in a loop instead of listing all instance ids. I don't want to create a duplicate line with every instance id.
这里的目的是一次部署到每个数据中心的一个实例,而不是用低串行运行所有实例,这需要很长时间.
The purpose here is to deploy to one instance in every data center at a time instead of running all with a low serial which takes a long time.
可能有不同的方法,我也不想在清单中为每个 instance_id 创建静态组.
There might be a different way of doing it, I don't want to create static groups in the inventory for each instance_id as well.
---
- hosts: tag_type_edgenode
tasks:
- group_by: key=instance_id_{{instance_id}}
register: dyn_groups
- hosts: instance_id_1
tasks:
- ping:
- hosts: instance_id_2
tasks:
- ping:
- hosts: instance_id_3
tasks:
- ping:
- hosts: instance_id_4
tasks:
- ping:
推荐答案
如果每组主机数相等,可以使用模式 + 串行.
Ansible 通过在组中顺序移动的模式形成主机列表.因此,如果您的主机数量相等,那么串行形成的批次将等于组.
If you have equal count of hosts in each group, you can use pattern + serial.
Ansible forms host list by pattern moving through groups sequentially. So if you have equal count of hosts, then batches formed by serial will be equal to groups.
在您的示例中,如果每个组中恰好有 3 个主机,则可以使用:
In your example, if you have exactly 3 hosts in each group, you can use:
- hosts: instance_id_*
serial: 3
tasks:
- ping:
如果你不介意一点 Ansible 补丁,你可以修改 _get_serialized_batches 方法.
在 while len(all_hosts) > 之前添加此代码0:
:
If you don't mind a bit of Ansible patching, you can modify _get_serialized_batches method.
Add this code just before while len(all_hosts) > 0:
:
if 'serialize_by_var' in play.get_vars():
param = play.get_vars()['serialize_by_var']
sb = []
def by_param(x):
vrs = x.get_vars()
if param in vrs:
return vrs[param]
else:
return None
s_hosts = sorted(all_hosts,key=by_param)
for k, g in itertools.groupby(s_hosts, by_param):
sb.append(list(g))
display.vv('Serializing by host var "{}": {}'.format(param,sb))
return sb
你可以通过任何这样的变量序列化主机:
And you can serialize hosts by any variable like this:
- hosts: tag_type_edgenode
vars:
serialize_by_var: instance_id
tasks:
- ping
这篇关于一次在多个主机组上运行一个剧本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!