Re-using set_fact variable in other role

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.

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.

Check out lookup plugin inventroy_hostnames to find the host.