如何在 Ansible play 中列出所有当前目标主机

How to list all currently targeted hosts in an Ansible play

我是运行一个Ansible play,想列出它所针对的所有主机。 Ansible 文档 mentions that this is possible,但他们的方法似乎不适用于复杂的目标群体(像主机这样的目标:web_servers:&data_center_primary)

我确定这是可行的,但似乎找不到任何进一步的文档。是否有包含所有当前目标主机的 var?

您可以使用选项 --list-hosts 仅列出剧本会影响的主机。

此外,还有字典 hostvars,它包含 Ansible 当前已知的所有主机。但我认为 setup 模块必须在所有主机上都是 运行,因此您不能通过 gather_facts: no.

跳过该步骤

您正在寻找 'play_hosts' 变量

---
- hosts: all

  tasks:
    - name: Create a group of all hosts by app_type
      group_by: key={{app_type}}

    - debug: msg="groups={{groups}}"
      run_once: true

- hosts: web:&some_other_group

  tasks:
   - debug: msg="play_hosts={{play_hosts}}"
     run_once: true

会导致

TASK: [Create a group of all hosts by app_type] *******************************
changed: [web1] => {"changed": true, "groups": {"web": ["web1", "web2"], "load_balancer": ["web3"]}}

TASK: [debug msg="play_hosts={{play_hosts}}"] *********************************
ok: [web1] => {
    "msg": "play_hosts=['web1']"
}

库存:

[proxy]
web1 app_type=web
web2 app_type=web
web3 app_type=load_balancer

[some_other_group]
web1
web3