首页 > 解决方案 > Ansible:从库存中检索数据

问题描述

我需要从库存文件中检索 bob_server 的 IP。我不清楚在 , 和 中使用filter什么lookup组合when?根据库存文件bob_serveralice_server名称可以更改,但app_type不会更改。我的剧本逻辑显然是错误的,有人可以指导我获取IP地址的正确方法吗app_type = bob

我当前的库存文件:

---
all:
  hosts:
  children:
    bob_server:
      hosts: 10.192.2.6
      vars:
        app_type: bob
    alice_server:
      hosts: 10.192.2.53
      vars:
        app_type: alice

我的剧本

---
- hosts: localhost
  name: Retrive data
  tasks:
    - name: Set Ambari IP
      set_fact:
        ambariIP: "{{ lookup('hosts', children) }}"
      when: "hostvars[app_type] == 'bob'"

标签: ansibleansible-2.xansible-inventoryansible-facts

解决方案


鉴于库存

shell> cat hosts-01
---
all:
  hosts:
  children:
    bob_server:
      hosts: 10.192.2.6
      vars:
        app_type: bob
    alice_server:
      hosts: 10.192.2.53
      vars:
        app_type: alice

简单的选项是使用ansible-inventory,例如

- hosts: localhost
  tasks:
    - command: ansible-inventory -i hosts-01 --list
      register: result
    - set_fact:
        my_inventory: "{{ result.stdout|from_yaml }}"
    - debug:
        var: my_inventory.bob_server.hosts

  my_inventory.bob_server.hosts:
  - 10.192.2.6

如果您想自己解析文件,请将其读入字典并展平路径,例如(安装 ansible.utils ansible-galaxy collection install ansible.utils

    - include_vars:
        file: hosts-01
        name: my_hosts
    - set_fact:
        my_paths: "{{ lookup('ansible.utils.to_paths', my_hosts) }}"
    - debug:
        var: my_paths

  my_paths:
    all.children.alice_server.hosts: 10.192.2.53
    all.children.alice_server.vars.app_type: alice
    all.children.bob_server.hosts: 10.192.2.6
    all.children.bob_server.vars.app_type: bob
    all.hosts: null

现在选择键结束bob_server.hosts

    - set_fact:
        bob_server_hosts: "{{ my_paths|
                              dict2items|
                              selectattr('key', 'match', '^.*bob_server\\.hosts$')|
                              items2dict }}"

  bob_server_hosts:
    all.children.bob_server.hosts: 10.192.2.6

并选择 IP

    - set_fact:
        bob_server_ips: "{{ bob_server_hosts.values()|list }}"

  bob_server_ips:
  - 10.192.2.6

清单缺少组的概念。请参阅清单基础:格式、主机和组。通常, 的值children是一组主机。在此清单中, 的值children是单个主机。这在概念上是错误的,但仍然有效,例如

- hosts: bob_server
  gather_facts: false
  tasks:
    - debug:
        var: inventory_hostname

shell> ansible-playbook -i hosts-01 playbook.ym
  ...
TASK [debug] ****************************************************
ok: [10.192.2.6] =>
  inventory_hostname: 10.192.2.6

推荐阅读