首页 > 解决方案 > Ansible 获取清单主机组的主机名和 IP

问题描述

我正在尝试获取主机的主机名和 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}}"

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

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

line: "{{ hostvars[ groups['Servers'][0] ].ansible_hostname }} :{{ hostvars[ groups['Servers'][0] ].ansible_default_ipv4.address }}"

我四处搜索,这就是我发现的,我该怎么做?

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

解决方案


我会为此使用 jinja 模板:

# hosts_file.j2
{% for server in groups['Servers'] %}
{{hostvars[server]['ansible_facts']['hostname']}}:{{hostvars[server]['ansible_facts']['default_ipv4']['address']}}
{% endfor %}
- hosts: localhost
  tasks:
    - name: create hosts file from template
      template: 
        src: hosts_file.j2
        dest: {{store_files_path}}/{{ansible_date_time.date}}/{{ansible_date_time.time}}/hosts.txt

推荐阅读