'How to exclude localhost from groups when hosts action is localhost with ansible
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 : ...
...
Solution 1:[1]
Exclude current host (in your case localhost) from list of servers in your template:
{% for host in groups[servers_to_monitor] | difference([inventory_hostname]) %}
Solution 2:[2]
I needed to exclude a group from all
{% for host in groups['all'] | difference(groups['host_group_to_exclude']) %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Konstantin Suvorov |
| Solution 2 | Milad Jahandideh |
