Bootstrap FreeKB - Ansible - Delegate variable from host A to host B
Ansible - Delegate variable from host A to host B

Updated:   |  Ansible articles

Let's say you have two hosts in your default hosts file or your own inventory file.

all:
  hosts:
    server1.example.com:
    server2.example.com:

 

And you want to pass a variable from server1 to server2. For example, let's say /tmp/example.txt on server1 contains "Hello World".

In this example, the shell module is used to read /tmp/example.txt on server1 and the register parameter is store Hello World in the out variable. The set_fact module is then used to create a variable named greeting and delegate_to and delegate_facts are used set the greeting variable as a fact on server2. The debug module is then used to see that the greeting variable has been set on server2.

---
- hosts: all
  tasks:
  - shell: cat /tmp/example.txt
    register: out
    when: inventory_hostname == 'server1.example.com'

  - set_fact:
      greeting: "{{ out.stdout }}"
    delegate_to: server2.example.com
    delegate_facts: true

  - debug:
      var: greeting
    when: inventory_hostname == 'server2.example.com'
...

 

Running this playbook should produce the following.

TASK [shell]
changed: [server1.example.com]
skipping: [server2.example.com]

TASK [docker : set_fact] 
ok: [server1.example.com -> server2.example.com]
skipping: [server2.example.com]

TASK [docker : debug]
skipping: [server1.example.com]
ok: [server2.example.com] => {
    "greeting": "Hello World"
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 07b798 in the box below so that we can be sure you are a human.