Pass Ansible variables from one role (running on one host) to another role running on another host within the same playbook

This topic is complicated, and there are two different answers depending on what you want.

Access a variable defined in one role inside other for the same host

Example:

---
- hosts: host1
- roles:
    - role1
    - role2

Goal: You want to access some variable from role1 inside role2.

Use set_fact module.

Inside role1:

name: save precious value
set_fact: 
  pantsu: shiroi

Inside role2:

name: Nozoki...
debug: msg="Color is {{ pantsu }}"

Access to static variable for one host (or group) to other

Example:

[group_foo]
host1
host2
[group_bar]
host3
host4

group_vars/group_foo

important_value=bla-bla-ba

Goal: You want to use it in playbook for group2.

This is much trickier to do.

Inside group_vars/group_bar

other_var: '{{hostvars[groups["group_foo"][0]].important_value}}'

You can use other indexes besides '0'.


The problem is in your inventory.

This message:

fatal: [10.104.148.138] => host not found: LBL

is because LBL is a group and not a host. Group LBL has one host in it: 10.104.148.136

Do one of the following:

1. Change your inventory (/etc/ansible/hosts) to:

LBL ansible_ssh_host=10.104.148.136
LM ansible_ssh_host=10.104.148.138

2. or if you really know what you're doing and LBL is a group and you wanna keep it that way then access the variable with:

{{ hostvars['10.104.148.136']['db']['stdout'] }}

Again LBL is a group not a host. More info.


Here's my solution. My task was to sync data between two servers and I wanted to pass in the server names like this: ansible-playbook sync.yaml -e "source=host1 destination=host2"

Here's the main playbook:

---

- name: get_sync_facts
  hosts: "{{ source }}"
  roles:
    - set_sync_facts

- name: sync
  hosts: "{{ destination }}" 
  roles:
    - get_sync_facts
    - sync

Here's the set_sync_facts role:

---

- set_fact: src_media_dir='/some/dir/'
- set_fact: src_user='myuser'
- set_fact: src_host='1.1.1.1'
- set_fact: src_port=12345
- set_fact: src_db_user='dbuser'
- set_fact: src_db_password='something'
- set_fact: src_db_name='some_db'

(I actually derived some of these from tasks and others from host vars but you get the point)

And here's the get_sync_facts role:

---

- set_fact: src_media_dir={{ hostvars[source]['src_media_dir'] }}
- set_fact: src_user={{ hostvars[source]['src_user'] }}
- set_fact: src_host={{ hostvars[source]['src_host'] }}
- set_fact: src_port={{ hostvars[source]['src_port'] }}
- set_fact: src_db_user={{ hostvars[source]['src_db_user'] }}
- set_fact: src_db_password={{ hostvars[source]['src_db_password'] }}
- set_fact: src_db_name={{ hostvars[source]['src_db_name'] }}

You could do without this and just reference hostvars directly in your plays but this seemed easier to maintain as it corresponds directly with the set_sync_facts role.