Ansible 获取库存主机组的主机名和 IP

n00*_*00b 3 ansible ansible-2.x ansible-facts ansible-inventory

我正在尝试获取主机的主机名和 IP 地址并将它们保存到文件中。

我有这个解决方案;

- name: Create File with hosts and IP address.
  when: inventory_hostname in groups['local']
  lineinfile:
    dest: "{{store_files_path}}/{{ansible_date_time.date}}/{{ansible_date_time.time}}/hosts.txt"
    create: yes
    line: "{{hostvars[inventory_hostname].ansible_hostname}}:{{hostvars[inventory_hostname].ansible_default_ipv4.address}}"
Run Code Online (Sandbox Code Playgroud)

但问题出在我的主机文件中,我有两个组,local并且Servers. 我想要得到Servers唯一的,而不是local唯一的组localhost

我已经尝试过以下行,但它不起作用,它给了我一个错误。

line: "{{ hostvars[ groups['Servers'][0] ].ansible_hostname }} :{{ hostvars[ groups['Servers'][0] ].ansible_default_ipv4.address }}"
Run Code Online (Sandbox Code Playgroud)

我查了一下,发现是这样的,我该怎么办?

β.ε*_*.βε 5

你自己让这件事变得极其复杂。

  1. 您不必通过 来hostvars实现您想要的,特殊变量主要为您提供有关 Ansible 当前正在操作的主机的信息。Ansible 为主机收集的事实也是如此。
  2. 对于当前的问题,您可以使用另一个特殊变量group_names,它允许您以列表的形式获取当前正在操作的主机所在的组。因此,获取属于某个组的主机就像执行以下操作一样简单when: "'group_that_interest_you' in group_names"

因此考虑到库存:

all:
  vars:
    ansible_python_interpreter: /usr/bin/python3

  children:
    local:
      hosts:
        localhost:

    Servers:
      hosts:
        foo.example.org:
          ansible_host: 172.17.0.2
Run Code Online (Sandbox Code Playgroud)

和剧本:

- hosts: all
  gather_facts: yes
      
  tasks:
    - debug:
        msg: "{{ ansible_hostname }}:{{ ansible_default_ipv4.address }}"
      when:  "'Servers' in group_names"
Run Code Online (Sandbox Code Playgroud)

这产生了回顾:

PLAY [all] **********************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************
ok: [localhost]
ok: [foo.example.org]

TASK [debug] ********************************************************************************************************
skipping: [localhost]
ok: [foo.example.org] => {
    "msg": "8088bc73d8cf:172.17.0.2"
}

PLAY RECAP **********************************************************************************************************
foo.example.org            : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
Run Code Online (Sandbox Code Playgroud)

现在,如果您在自己的剧本中进行调整,您应该可以开始:

- name: Create File with hosts and IP address.
  lineinfile:
    dest: "{{ store_files_path }}/{{ ansible_date_time.date }}/{{ ansible_date_time.time }}/hosts.txt"
    create: yes
    line: "{{ ansible_hostname }}:{{ ansible_default_ipv4.address }}"
  when:  "'Servers' in group_names"
  delegate_to: localhost
Run Code Online (Sandbox Code Playgroud)