I have to list all server in a file by using a template.j2. The purpose is to generate a config file up to date with the ansible inventory file. All files are on the ansible server. I have a generate-projectconf.yml, a template.j2 and the inventory file. The problem is that with my method the localhost is also in the generated file. I only want IP that are in the inventory file.
My yml file looks like that
- hosts: localhost
tasks:
- name: modif du project.conf
template: src="template.j2" dest="/tmp/project.conf"
the template.j2 file
...
ServersList
{% for host in groups[servers_to_monitor] %}
{{ hostvars[host]['ansible_hostname'] }} : {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
...
The inventory file looks like that
[DB_Servers]
cas05 ansible_ssh_host=192.168.20.105 ansible_user=ansible
cas06 ansible_ssh_host=192.168.20.106 ansible_user=ansible
[MS_Account_Servers]
acc21 ansible_host=192.168.20.99 ansible_user=ansible
acc22 ansible_host=192.168.20.100 ansible_user=ansible
[MS_Admin_Servers]
adm21 ansible_host=192.168.20.79 ansible_user=ansible
adm22 ansible_host=192.168.20.80 ansible_user=ansible
[MS_Admingui_Servers]
ihm21 ansible_host=192.168.20.81 ansible_user=ansible
To launch this, I execute the command
ansible-playbook generate-projectconf.yml -i /.../inventory --extra-vars "servers_to_monitor=all"
The result looks like this:
...
dep01 : 192.168.20.3
ihm21 : 192.168.20.81
adm21 : ...
...
Exclude current host (in your case localhost
) from list of servers in your template:
{% for host in groups[servers_to_monitor] | difference([inventory_hostname]) %}