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

问题描述 投票:0回答:3

我正在运行 Ansible play,并想列出它所针对的所有主机。 Ansible 文档提到这是可能的,但他们的方法似乎不适用于复杂的目标组(像主机这样的目标:web_servers:&data_center_primary)

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

ansible
3个回答
46
投票

您正在寻找“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

39
投票

您可以使用选项

--list-hosts
仅列出 playbook 会影响的主机。

此外,还有一个字典

hostvars
,其中包含 Ansible 当前已知的所有主机。但我认为
setup
模块必须在所有主机上运行,因此您不能通过
gather_facts: no
跳过该步骤。


0
投票

我遇到了同样的问题,在执行 playbook 之前尝试获取

pattern
的主机列表作为健全性检查。

如果您运行

ansible
命令,它将打印用法,您将看到:

--list-hosts  outputs a list of matching hosts; does not execute anything else

因此运行如下所示的内容:

ansible -i my/ansible/inventory.yml --list-hosts mygroup

输出类似:

hosts (2):
  myhostname1
  myhostname2
© www.soinside.com 2019 - 2024. All rights reserved.