# how to use variables defined in another group

**URL:** <https://forum.ansible.com/t/how-to-use-variables-defined-in-another-group/19718>\
**Category:** Ansible Project\
**Created:** [November 10, 2015, 1:51am UTC](https://forum.ansible.com/t/how-to-use-variables-defined-in-another-group/19718 "2015-11-10T01:51:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Florin\_Andrei](https://avatars.discourse-cdn.com/v4/letter/f/c77e96/32.png) [@Florin\_Andrei](https://forum.ansible.com/u/Florin_Andrei)\
**Post date:** [November 10, 2015, 1:51am UTC](https://forum.ansible.com/t/how-to-use-variables-defined-in-another-group/19718/1 "2015-11-10T01:51:51Z")

</div>

I have several inventory files, where many groups are defined. For the big groups, I’ve defined variables in ./group\_vars/${group\_name}/main.yml

For one role, which is typically executed only against two groups (specifically, against one host in each one of those two big groups), I need to “borrow” a variable defined in pretty much all other groups. How do I do that? How do I tell the role to use that variable, but with the value defined in another group?

Of course, I could hardcode the values within that role, but then those values would be defined twice: once in this role, and then again as a group variable in all other groups. I want to avoid that.

---

<div class="post-metadata">

**Author:** ![Brian\_Coca](https://avatars.discourse-cdn.com/v4/letter/b/6de8d8/32.png) [@Brian\_Coca](https://forum.ansible.com/u/Brian_Coca)\
**Post date:** [November 10, 2015, 5:02pm UTC](https://forum.ansible.com/t/how-to-use-variables-defined-in-another-group/19718/2 "2015-11-10T17:02:12Z")

</div>

you can use hostvars to access it through a host that belongs to the other group

hostvars['hostname']['varname']

if you don't know the host you can use the groups['groupname'] list to get one

hostvars[groups['groupname'][0]]['varname']

^ this looksup the var from the first host in the group, you can also  
use |random or other indecies if you know them.
