# Loop with hostvars groups

**URL:** <https://forum.ansible.com/t/loop-with-hostvars-groups/31134>\
**Category:** Ansible Project\
**Created:** [August 27, 2019, 12:06pm UTC](https://forum.ansible.com/t/loop-with-hostvars-groups/31134 "2019-08-27T12:06:21Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rafael\_Tomelin](https://avatars.discourse-cdn.com/v4/letter/r/da6949/32.png) [@Rafael\_Tomelin](https://forum.ansible.com/u/Rafael_Tomelin)\
**Post date:** [August 27, 2019, 12:06pm UTC](https://forum.ansible.com/t/loop-with-hostvars-groups/31134/1 "2019-08-27T12:06:21Z")

</div>

Hi,

I have an inventory with groups this configuration the DB Servers:

[db]  
192.168.0.1  
192.168.0.2

192.168.0.3

I want to do loop the groups and get variable ipaddress in template.j2. My loop is:  
{% for host in groups[‘db’] -%}  
host all postgres {{ hostvars[host].ansible\_hostname }}/32 trust  
{% endfor %}

My error

“msg”: “AnsibleUndefinedVariable: ‘ansible.vars.hostvars.HostVarsVars object’ has no attribute ‘ansible\_hostname’”,

What`s correct configuration?

---

<div class="post-metadata">

**Author:** ![vinod93pop](https://avatars.discourse-cdn.com/v4/letter/v/ea5d25/32.png) [@vinod93pop](https://forum.ansible.com/u/vinod93pop)\
**Post date:** [August 27, 2019, 12:10pm UTC](https://forum.ansible.com/t/loop-with-hostvars-groups/31134/2 "2019-08-27T12:10:21Z")

</div>

Hi  
remove hostvars[host].ansible\_hostname and try with hostvars[host].ansible\_facts.hostname if you are doing it from setup module or gayher\_facts

If it’s not fixed put your playbook here

---

<div class="post-metadata">

**Author:** ![Rafael\_Tomelin](https://avatars.discourse-cdn.com/v4/letter/r/da6949/32.png) [@Rafael\_Tomelin](https://forum.ansible.com/u/Rafael_Tomelin)\
**Post date:** [August 27, 2019, 12:47pm UTC](https://forum.ansible.com/t/loop-with-hostvars-groups/31134/3 "2019-08-27T12:47:14Z")

</div>

Hi Vinoth,

Thanks, your recommendation is work.
