# Hostvar variable index in template

**URL:** <https://forum.ansible.com/t/hostvar-variable-index-in-template/34492>\
**Category:** Ansible Project\
**Created:** [January 22, 2021, 2:21pm UTC](https://forum.ansible.com/t/hostvar-variable-index-in-template/34492 "2021-01-22T14:21:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Csoke\_Janos](https://avatars.discourse-cdn.com/v4/letter/c/858c86/32.png) [@Csoke\_Janos](https://forum.ansible.com/u/Csoke_Janos)\
**Post date:** [January 22, 2021, 2:21pm UTC](https://forum.ansible.com/t/hostvar-variable-index-in-template/34492/1 "2021-01-22T14:21:58Z")

</div>

Hi,

I have a problem and I can’t find a solutions.

In my playbook, I have a host based variable called: server\_name  
I would like to use in a template file the IP address of the server which hostname’s is stored in the server\_name variable.  
Like this:

{{ hostvars[‘{{ server\_name }}’][‘ansible\_eth0’][‘ipv4’][‘address’] }}

If I use this sentences in a roles, is working fine, but if I use in a template, this error happen:  
FAILED! =\> {“changed”: false, “msg”: “AnsibleUndefinedVariable: "hostvars[‘{{ server\_name }}’]" is undefined”}

Have you any idea how can I solve this problem?

Best regards,  
Janos

---

<div class="post-metadata">

**Author:** ![racke](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/racke/32/4767_2.png) [@racke](https://forum.ansible.com/u/racke)\
**Post date:** [January 22, 2021, 2:33pm UTC](https://forum.ansible.com/t/hostvar-variable-index-in-template/34492/2 "2021-01-22T14:33:13Z")

</div>

> Hi,
> 
> I have a problem and I can't find a solutions.
> 
> In my playbook, I have a host based variable called: server\_name  
> I would like to use in a template file the IP address of the server which hostname's is stored in the server\_name variable.  
> Like this:  
> {{ hostvars['{{ server\_name }}']['ansible\_eth0']['ipv4']['address'] }}
> 
> If I use this sentences in a roles, is working fine, but if I use in a template, this error happen:  
> FAILED! =\> {"changed": false, "msg": "AnsibleUndefinedVariable: \"hostvars['{{ server\_name }}']\" is undefined"}
> 
> Have you any idea how can I solve this problem?
> 
> Best regards,  
> Janos

If you use variables inside {{ ... }} you can't wrap them again in {{ ... }}.  
Remove the curly braces and the single quotes:

&nbsp;&nbsp;&nbsp;{{ hostvars[server\_name]['ansible\_eth0']['ipv4']['address'] }}

Regards  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Racke

---

<div class="post-metadata">

**Author:** ![Csoke\_Janos](https://avatars.discourse-cdn.com/v4/letter/c/858c86/32.png) [@Csoke\_Janos](https://forum.ansible.com/u/Csoke_Janos)\
**Post date:** [January 22, 2021, 8:53pm UTC](https://forum.ansible.com/t/hostvar-variable-index-in-template/34492/3 "2021-01-22T20:53:43Z")

</div>

Oh, Thank you so much!

Best regards,  
Janos
