Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable from another host

Tags:

ansible

I have a playbook that executes a script on a Windows box that returns a value that I have to re-use later on in my playbook after switching to localhost.
How can I access this value after switching back to localhost?

Here is an example:

- hosts: windows
  gather_facts: no
  
  tasks:
    - name: Call PowerShell script
      win_command: "c:\\windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe c:\\psl_scripts\\getData.ps1"
      register: value_to_reuse

- hosts: localhost
  gather_facts: no
  
  tasks:
    - name: debug store_name from windows host
      debug:
        var: "{{ hostvars[windows][value_to_reuse][stdout_lines] }}"

What is the correct syntax accessing a variable from another host? I'm receiving error message:

"msg": "The task includes an option with an undefined variable. The error was: 'windows' is undefined

like image 258
larrybg Avatar asked Feb 12 '26 23:02

larrybg


1 Answers

Here is the code that works for a group in a loop:

- name: print value_to_reuse
  debug:
    var: hostvars[item].value_to_reuse.stdout_lines
  loop: "{{ groups['windows'] }}"

Same code works without iterations:

- name: print value_to_reuse
 debug:
   var: hostvars[groups['windows'].0].value_to_reuse.stdout_lines
like image 83
larrybg Avatar answered Feb 16 '26 02:02

larrybg