# Re-using set\_fact variable in other role

**URL:** <https://forum.ansible.com/t/re-using-set-fact-variable-in-other-role/27902>\
**Category:** Ansible Project\
**Created:** [June 28, 2018, 7:45pm UTC](https://forum.ansible.com/t/re-using-set-fact-variable-in-other-role/27902 "2018-06-28T19:45:38Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Paolo\_P](https://avatars.discourse-cdn.com/v4/letter/p/ecc23a/32.png) [@Paolo\_P](https://forum.ansible.com/u/Paolo_P)\
**Post date:** [June 28, 2018, 7:45pm UTC](https://forum.ansible.com/t/re-using-set-fact-variable-in-other-role/27902/1 "2018-06-28T19:45:38Z")

</div>

Hello,

I need to execute a role with a conditional based on a variable set on a different host/group.

The variable is set doing a query on host db1 and a set\_fact :

- hosts: db1  
tasks:
- name: Check for DB  
shell: psql -Atc “SELECT id FROM …;”

register: dbs\_check

- set\_fact:  
base\_id: “{{ dbs\_check.stdout.split(‘|’)[0]|int }}”

Then on a condition on base\_id I want to run a role on a different host , but the variable is not defined as for normal Ansible behaviour.

- hosts: db2

roles:

- { role: createdb, when: base\_id \> 0 }

As a workaround I could run queries to DBs executing commands from localhost but I don’t like it.

Is there any easy workaround I am missing?

Thank you.  
P.

---

<div class="post-metadata">

**Author:** ![Paolo\_P](https://avatars.discourse-cdn.com/v4/letter/p/ecc23a/32.png) [@Paolo\_P](https://forum.ansible.com/u/Paolo_P)\
**Post date:** [June 28, 2018, 7:58pm UTC](https://forum.ansible.com/t/re-using-set-fact-variable-in-other-role/27902/2 "2018-06-28T19:58:51Z")

</div>

In addition, I know I could refer to host variable with “hostvars” but I don’t know how to do it since my host is defined by a intersection of two groups like:

db:$prod{{ prod\_num }}

Thanks again.

---

<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:** [June 30, 2018, 10:37am UTC](https://forum.ansible.com/t/re-using-set-fact-variable-in-other-role/27902/3 "2018-06-30T10:37:03Z")

</div>

Check out lookup plugin inventroy\_hostnames to find the host.
