获取清单主机名列表

时间:2019-06-12 16:55:19

标签: ansible ansible-inventory ansible-template

host1: abc
host2: xyz

host1和host2列在测试主机下

[test-hosts]
abc
xyz

当我调试清单主机名时,我看到它们如下所示

    > TASK [debug inventory_hostname]
    > ************************************************************************************************************************************************************************* 
ok: [abc] => {
    >     "inventory_hostname": "abc" } 
ok: [xyz] => {
    >     "inventory_hostname": "xyz" }

有什么方法可以通过将它分配给变量来收集清单的hostname_hostname。

预期结果:

exp_result: [abc, xyz]

2 个答案:

答案 0 :(得分:0)

您可以使用groups['test-hosts']将这些主机作为列表获取。

例如:

---
- hosts: all
  gather_facts: false
  tasks:
    - set_fact:
        host_list: "{{ groups['test-hosts'] }}"
    - debug:
        msg:  "{{host_list}}"

答案 1 :(得分:0)

如果您想选择多个组或使用 patterns 排除组,您也可以使用变量 inventory_hostnames

在这些示例中,我们选择了除 www 组中的主机之外的所有主机。

将主机列表保存为任务的变量:


- debug:
    var: hostnames
  vars:
    hostnames: "{{ query('inventory_hostnames', 'all:!www') }}"

您还可以使用 lookup plugin 循环匹配模式的主机。来自文档:

- name: show all the hosts matching the pattern, i.e. all but the group www
  debug:
    msg: "{{ item }}"
  with_inventory_hostnames:
    - all:!www

相关问题