I am trying to get host name and IP address of hosts and save them to a file.
I have this solution working;
- 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}}"
But the issue is in my hosts file, I have two groups, local
and Servers
. I want to get the Servers
only and not the local
group which is the localhost
only.
I have tried the below line but it doesn't work, it gives me an error.
line: "{{ hostvars[ groups['Servers'][0] ].ansible_hostname }} :{{ hostvars[ groups['Servers'][0] ].ansible_default_ipv4.address }}"
I have searched around and that's what I found, how should I do this?
I would use a jinja template for this :
# 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