Ansible - 从库存文件中获取主机名和私有IP

时间:2016-12-27 13:43:45

标签: ansible ansible-inventory

有没有办法获得每个节点的私有IP?

使用此模板:

{{ ansible_managed }}

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

{% for item in groups['all'] %}
{{ hostvars[item]['ansible_ssh_host'] }} {{ item }}
{% endfor %}

我得到以下结果:

Ansible managed

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

127.0.0.1 arithproducer
127.0.0.1 controller
127.0.0.1 restapi

成为我的库存文件:

[control]
controller ansible_ssh_host=192.168.50.3 ansible_ssh_user=vagrant

[servers]
restapi ansible_ssh_host=192.168.50.5 ansible_ssh_user=vagrant

[producers]
arithproducer ansible_ssh_host=192.168.50.4 ansible_ssh_user=vagrant

[services:children]
servers
producers

我的想法是获取此信息,以便我可以填充控制节点中的/etc/hosts/文件

1 个答案:

答案 0 :(得分:1)

您可以使用下面提到的模板和任务文件。

模板文件

{{ ansible_managed }}

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6


{% for group in groups %}
{% if groups[group] and group != 'all' %}
{% for host in groups[group] %}
{{hostvars[host].ansible_default_ipv4.address}} {{ ansible_hostname }}
{% endfor %}

{% endif %}
{% endfor %}

任务文件

---
- name: Create HostsFile
  hosts: development
  user: vagrant
  become: yes
  become_method: sudo

  tasks:
    - name: Create Hosts File
      template: src=hostsFile.j2 dest=/tmp/hosts owner=root group=root