Accessing hostvars for a host group in Ansible

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?

Best Answer

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'] }}"