从组中的主机获取 IP 地址

Get IP address from hosts in a Group

我有一个引用库存 hosts.yml 文件的简单剧本。我希望能够查询一个组,并检索该组中主机的 IP 地址。

简单hosts.yml

---
all:
  hosts:
    w2k16-std:
      ansible_host: 10.1.1.12
      in_play_ip: 10.200.2.12
    w2k12-x64:
      ansible_host: 10.1.1.13
      in_play_ip: 10.200.2.13
    lin-test:
      ansible_host: 10.1.1.20
      in_play_ip: 10.200.2.20
  children:
    windows:
      vars:
        ansible_connection: winrm
        ansible_winrm_transport: certificate
        ansible_winrm_cert_pem: /home/user/.ssh/windows.pem
        ansible_winrm_cert_key_pem: /home/user/.ssh/windows_key.pem
        ansible_port: 5986
        ansible_winrm_scheme: https
        ansible_winrm_server_cert_validation: ignore
      hosts:
        w2k12-x64:
        w2k16-std:
    linux:
      hosts:
        lin-test:
    targets:
      hosts:
        w2k12-x64:
        w2k16-std:

这是简单的剧本:

---
- hosts: kali
  vars:
  tasks:
    - name: Create comma delimited list of target names from targets group.
      set_fact:
        targets: "{{ groups.targets | list | join(',') }}"

    - name: List targets from Inventory
      debug:
        var: targets

产生以下输出:

TASK [List targets from Inventory] ***************************************
ok: [lin-test] => {
    "targets": "w2k12-x64,w2k16-std"

我希望能够做到以下几点:

到目前为止我可以:

我不确定我的主机文件布局是否正确,或者我是否只需要查询方面的帮助?

期望输出:

产生以下输出:

TASK [List target IPs from Inventory] ***************************************
ok: [lin-test] => {
    "targets": "10.1.1.12,10.1.1.13"

您可以从 hostvars special variable.

中提取您要查找的值

您还可以过滤组 targets 中包含的字典 hostvars 的项目,这要归功于过滤器 dict2items, which will create a key/value list from the dictionary, and selectattr 以仅获取具有键匹配的已创建列表的项目在 targets 组中。

然后,您只需要通过 map, because you are only interested in the ansible_host attribute, and join 整个过程将字典列表缩减为一个简单列表。

所以,这以这个单一任务结束:

- debug:
    msg: >-
      {{
        hostvars 
          | dict2items 
          | selectattr('key', 'in', groups.targets)
          | map(attribute="value.ansible_host")
          | join(',')
      }}

哪个会产生您的预期:

TASK [debug] **************************************************************
ok: [localhost] => 
  msg: 10.1.1.12,10.1.1.13