Accessing hostvars for a host group in Ansible

I am trying to use Ansible to add entries in the server hosts file. I have a group of servers that I need to talk to each other over a private LAN.

My inventory file:

[server_list]
server1
server2

The task I am trying to get working:

- lineinfile: dest=/etc/hosts line="{{ hostvars[" {{ item }} "]['ansible_eth1']['ipv4']['address'] }}   {{ hostvars[" {{ item }} "]['ansible_hostname'] }}"
  with_items: groups['server_list']

It's not doing the trick, I get this:

fatal: [server1] => host not found:  {{item}} 
fatal: [server2] => host not found:  {{item}} 

This is basically the same as this, but in the new Ansible variable access format {{ }}.

Any ideas how to get this done?


OK. I had tried this before and it didn't really work. So I must have done something wrong back there.

This works:

- lineinfile: dest=/etc/hosts line="{{ hostvars[item]['ansible_eth1']['ipv4']['address'] }}   {{ hostvars[item]['ansible_hostname'] }}"
  with_items: groups['server_list']

or for 1.9 or later:

- lineinfile: dest=/etc/hosts line="{{ hostvars[item]['ansible_eth1']['ipv4']['address'] }}   {{ hostvars[item]['ansible_hostname'] }}"
  with_items: "{{ groups['server_list'] }}"

Had the same problem, I wanted to go over the list of hosts in one group and then add firewall rules with their ips. Looked a bit at how hostvars[item] is structured and used the different name to access this value. This worked for me:

- name: Setting up firewall so web_servers can access MySQL on port {{ mysql_port }}
  ufw: rule=allow proto=tcp to_port={{ mysql_port }} src="{{ hostvars[item]['ansible_default_ipv4']['address'] }}"
  with_items: "{{ groups.web_servers }}"

if you need to both add a prefix and a suffix, as well as making everything a list, take a look at the below:

  set_fact:
    extended_etcd_endpoints_list: "{{ groups['etcd'] | map('extract', hostvars, ['ansible_default_ipv4','address']) | map('regex_replace', '^(.*)$','https://\\1:2379') | list  }}"

it takes the list of all machines in the group etcd, extracts the ipv4, adds an 'https://' in front and an ':2379' at the end. Finally, everything is transformed in a list.