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.



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
  - shell: cat /tmp/example.txt
    register: out
    when: inventory_hostname == ''

  - set_fact:
      greeting: "{{ out.stdout }}"
    delegate_facts: true

  - debug:
      var: greeting
    when: inventory_hostname == ''


Running this playbook should produce the following.

TASK [shell]
changed: []
skipping: []

TASK [docker : set_fact] 
ok: [ ->]
skipping: []

TASK [docker : debug]
skipping: []
ok: [] => {
    "greeting": "Hello World"


Did you find this article helpful?

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


Add a Comment

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