# How to use hostvars?

**URL:** <https://forum.ansible.com/t/how-to-use-hostvars/31231>\
**Category:** Ansible Project\
**Created:** [September 9, 2019, 9:54am UTC](https://forum.ansible.com/t/how-to-use-hostvars/31231 "2019-09-09T09:54:33Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![user48](https://avatars.discourse-cdn.com/v4/letter/u/bc8723/32.png) [@user48](https://forum.ansible.com/u/user48)\
**Post date:** [September 9, 2019, 9:54am UTC](https://forum.ansible.com/t/how-to-use-hostvars/31231/1 "2019-09-09T09:54:33Z")

</div>

My ansible version is 2.5.  
In my playbook, one host needs to access other host’s variable which I defined in inventory file.  
I used {{ hostvars[‘groupname’].var\_name }} and get an error, I also tried to use {{ hostvars[‘groupname’][‘var\_name’] }} which get an error also.  
So, I want to be clear how to use hostvars to access another host variables defined in the inventory file?

---

<div class="post-metadata">

**Author:** ![Dick\_Visser](https://avatars.discourse-cdn.com/v4/letter/d/d9b06d/32.png) [@Dick\_Visser](https://forum.ansible.com/u/Dick_Visser)\
**Post date:** [September 9, 2019, 10:26am UTC](https://forum.ansible.com/t/how-to-use-hostvars/31231/2 "2019-09-09T10:26:01Z")

</div>

You don't say what error you get?

In any case, you are trying to access hostvars for a group, which  
isn't possible.  
Instead, you need to access hostvars from a host.  
So for a group, practically this is done by accessing the hostvars of  
the first host of a group, like this:

hostvars[groups['groupname'][0]]['var\_name']

Dick

---

<div class="post-metadata">

**Author:** ![user48](https://avatars.discourse-cdn.com/v4/letter/u/bc8723/32.png) [@user48](https://forum.ansible.com/u/user48)\
**Post date:** [September 10, 2019, 1:19am UTC](https://forum.ansible.com/t/how-to-use-hostvars/31231/3 "2019-09-10T01:19:31Z")

</div>

Hi, thanks for your reply, I resolve this by using {{ hostvars[groups[‘groupname’][0]].var\_name }}.

在 2019年9月9日星期一 UTC+8下午6:26:25，Dick Visser写道：
