在Ansible inventory中使用主机范围时,可以通过内置变量ansible_play_hosts_all
来获取当前的"主机索引"。该变量是一个包含所有主机的列表,可以通过ansible_play_hosts_all.index(inventory_hostname)
来获取当前主机在列表中的索引位置。
例如,假设有一个inventory文件包含3个主机,分别是host1、host2和host3。在playbook中,可以使用以下方式获取当前主机的索引:
- name: Get host index
hosts: all
tasks:
- name: Print host index
debug:
msg: "The index of {{ inventory_hostname }} is {{ ansible_play_hosts_all.index(inventory_hostname) }}"
执行该playbook后,会输出类似以下的结果:
TASK [Print host index] **********************************************************************************************************************
ok: [host1] => {
"msg": "The index of host1 is 0"
}
ok: [host2] => {
"msg": "The index of host2 is 1"
}
ok: [host3] => {
"msg": "The index of host3 is 2"
}
这样就可以获取到当前主机在inventory中的索引位置。根据需要,可以在playbook中进一步利用该索引执行特定的操作或逻辑。
领取专属 10元无门槛券
手把手带您无忧上云