Managing hosts file in ansible
Sometimes, its required to add hosts from ansible inventory to /etc/hosts on managed hosts.
In our scenario, each host from the inventory has defined an “ip” variable. If this is not the case, the facts of each host can also be used.
The advantage of the IP variable is that the IP addresses are also available for hosts that are not part of the current play.
- name: Add IP address of all hosts to all hosts
lineinfile:
dest: /etc/hosts
regexp: '.* {{ item }}$'
line: "{{ hostvars[item].ip|default(ansible_default_ipv4.address|default(ansible_all_ipv4_addresses[0])) }} {{item}}"
state: present
when: hostvars[item].ip|default(ansible_default_ipv4.address|default(ansible_all_ipv4_addresses[0]))
with_items: "{{ common_add_groups_to_hosts | map('extract',groups) | list}}"
This task expects the common_add_groups_to_hosts variable with a list of all host groups to be added to the /etc/hosts file.
common_add_groups_to_hosts: [ 'all' ]