【问题标题】:Get a list of inventory hostnames获取清单主机名列表
【发布时间】:2019-06-12 16:55:19
【问题描述】:
host1: abc
host2: xyz

host1 和 host2 列在 test-hosts 下

[test-hosts]
abc
xyz

当我调试 inventory_hostnames 时,我看到它们如下所示

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

有什么方法可以通过将inventory_hostname 分配给一个变量来像列表一样收集它。

预期结果:

exp_result: [abc, xyz]

【问题讨论】:

    标签: ansible ansible-inventory ansible-template


    【解决方案1】:

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

    例如:

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

    【讨论】:

      【解决方案2】:

      如果您想选择多个组或使用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
      
      

      【讨论】:

        猜你喜欢
        • 2018-06-30
        • 1970-01-01
        • 2019-09-28
        • 2017-09-25
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 2013-07-30
        • 2022-01-23
        相关资源
        最近更新 更多