# how to use variables from one role in another role

**URL:** <https://forum.ansible.com/t/how-to-use-variables-from-one-role-in-another-role/18952>\
**Category:** Ansible Project\
**Created:** [August 5, 2015, 11:22am UTC](https://forum.ansible.com/t/how-to-use-variables-from-one-role-in-another-role/18952 "2015-08-05T11:22:52Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Stri](https://avatars.discourse-cdn.com/v4/letter/s/c67d28/32.png) [@Stri](https://forum.ansible.com/u/Stri)\
**Post date:** [August 5, 2015, 11:22am UTC](https://forum.ansible.com/t/how-to-use-variables-from-one-role-in-another-role/18952/1 "2015-08-05T11:22:52Z")

</div>

Hi,  
How to set a variable inside role A and use it inside role B ? Role B is listed in dependencies sections in meta/main.yml of role A and I see its output then call role A.  
I have tried to use **set\_fact** module or **register** variable, but no luck.

**role A:**  
`

- name: Print test var from another role  
debug: msg=“{{ test\_var }}”  
`

**role B:**  
`

- name: Save some vars in register  
shell: echo “BLAH”  
register: test\_var

- name: Save some vars in facts  
set\_fact:

test\_var: BLAH  
`

**ansible-playbook’s Output:**

> fatal: [localhost] =\> One or more undefined variables: ‘test\_var’ is undefined  
> FATAL: all hosts have already failed – aborting

If I set test\_var via role’s parameter in site.yml, all works fine:

**site.yml**

**`**

---

<div class="post-metadata">

**Author:** ![Dick\_Davies](https://avatars.discourse-cdn.com/v4/letter/d/b9e5f3/32.png) [@Dick\_Davies](https://forum.ansible.com/u/Dick_Davies)\
**Post date:** [August 5, 2015, 2:10pm UTC](https://forum.ansible.com/t/how-to-use-variables-from-one-role-in-another-role/18952/2 "2015-08-05T14:10:52Z")

</div>

If role A depends on B, then B will get handled first, \_then\_ A.

Any vars you set in B are visible in A, but not the other way round  
(since B happens 'before' A and you haven't had a chance to set those vars).

---

<div class="post-metadata">

**Author:** ![Stri](https://avatars.discourse-cdn.com/v4/letter/s/c67d28/32.png) [@Stri](https://forum.ansible.com/u/Stri)\
**Post date:** [August 6, 2015, 8:50am UTC](https://forum.ansible.com/t/how-to-use-variables-from-one-role-in-another-role/18952/3 "2015-08-06T08:50:18Z")

</div>

If I use var/main.yml for storing variables, all works fine (variables from Role A and B seen in each role).  
I want to symplify code in my roles and move generic code to separate role or playbook. Then I want to pass some variables from roles to this playbook (for creating directory structure, for example). I can’t save output from modules inside role A in variable and pass it to role B (even with set\_fact module inside one server I see facts onle inside the role, where I create fact.)
