# Variable in hostvars

**URL:** <https://forum.ansible.com/t/variable-in-hostvars/31867>\
**Category:** Ansible Project\
**Created:** [December 23, 2019, 4:38pm UTC](https://forum.ansible.com/t/variable-in-hostvars/31867 "2019-12-23T16:38:07Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Herman\_Pool](https://avatars.discourse-cdn.com/v4/letter/h/ad7895/32.png) [@Herman\_Pool](https://forum.ansible.com/u/Herman_Pool)\
**Post date:** [December 23, 2019, 4:38pm UTC](https://forum.ansible.com/t/variable-in-hostvars/31867/1 "2019-12-23T16:38:07Z")

</div>

Hi all,

I am new to ansible.  
Why is my playbook not working?  
And how can I solve it?

My playbook:

---

<div class="post-metadata">

**Author:** ![Kai\_Stian\_Olstad](https://avatars.discourse-cdn.com/v4/letter/k/e19adc/32.png) [@Kai\_Stian\_Olstad](https://forum.ansible.com/u/Kai_Stian_Olstad)\
**Post date:** [December 23, 2019, 5:16pm UTC](https://forum.ansible.com/t/variable-in-hostvars/31867/2 "2019-12-23T17:16:29Z")

</div>

> I am new to ansible.  
> Why is my playbook not working?

You have a couple of things you need to change.

> ---  
> - name: print out ip adressess  
> &nbsp;&nbsp;&nbsp;hosts: db\_servers  
> &nbsp;&nbsp;&nbsp;gather\_facts: True  
> &nbsp;&nbsp;&nbsp;vars:  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- nic: "enp0s8"  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- full\_line: ""

vars is a dict not a list so you need to remove those dashes in front.

> &nbsp;&nbsp;&nbsp;tasks:  
> &nbsp;&nbsp;&nbsp;- debug: var=ansible\_{{ nic }}.ipv4.address
> 
> &nbsp;&nbsp;&nbsp;- set\_fact: full\_line="{{ full\_line }} {{ hostvars[item].ansible\_enp0s8.ipv4.address }}"  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;loop: "{{ groups['db\_servers'] }}"
> 
> &nbsp;&nbsp;&nbsp;- debug:  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;msg: "{{ full\_line }}"
> 
> &nbsp;&nbsp;&nbsp;- set\_fact: full\_line="{{ full\_line }} {{ hostvars[item].ansible\_{{ nic }}.ipv4.address }}"  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;loop: "{{ groups['db\_servers'] }}"

You can't use {{ }} inside {{ }}, so you need to concatenate stings to make it work.

{{ hostvars[item]['ansible\_' ~ nic].ipv4.address }}

You could drop the loop by using this

- set\_fact:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;full\_line: "{{ groups['db\_servers'] | map('extract', hostvars, ['ansible\_' ~ nic, 'ipv4', 'address']) | join(' ') }}"

---

<div class="post-metadata">

**Author:** ![Herman\_Pool](https://avatars.discourse-cdn.com/v4/letter/h/ad7895/32.png) [@Herman\_Pool](https://forum.ansible.com/u/Herman_Pool)\
**Post date:** [December 23, 2019, 5:54pm UTC](https://forum.ansible.com/t/variable-in-hostvars/31867/3 "2019-12-23T17:54:22Z")

</div>

Hello Kai,

many thnx for the quick respons!  
Your solution works fine and it is exactly what I needed.

Happy X-mas to you all.

with regards,

Herman
