| Forum

Ansible - Re-use the same variable value of one server in another server

I have two servers serverA and serverB.
I have a variable val which is computed on the serverA. I dont want to compute again in serverB.
I need to use the serverA’s variable value itself. How can this be achieved?

You can use as below.

- name: Task1
   val: "cat /tmp/filevalue | grep value"
  when: hostvars[serverA]['val'] is not defined

- name: Task2
   new_val: "{{hostvars[serverA]['val']}}"
  when: hostvars[serverA]['val'] is defined

On ServerA:
The Task1 is first executed on serverA as the variable is not defined and then Task2 is executed.
On ServerB
The Task1 will not be executed as the variable is defined and then Task2 is executed.
So the new_val will be same for both server even if the file /tmp/filevalue is different.