How to access a variable between different play/hosts in the same playbook?

48 views
Skip to first unread message

Ramkumar A

unread,
Nov 6, 2022, 4:06:18 PM11/6/22
to Ansible Project
Hi Experts,

I am a newcomer to Ansible.
I need help in accessing a variable between different hosts/play on the playbook. In below code, group of servers is passed here dynamically and creating tempfile directory for each hosts on the Ansible server.
In the second play, i am unable to access the tempfile directory name (stagingdir) for the hosts, probably i am not using the correct approach using hostvars.
Can you please help & guide me to access the stagingdir value of hosts in the first play from the second play below ?

##################

- hosts: "{{host}}"
  gather_facts: false
  tasks:
  - name: Create local staging dir
    local_action:
      module: tempfile
      state: directory
    register: stagingdir

  - name: print stdout in same play
    debug: msg="Value of the variable is {{ hostvars[inventory_hostname].stagingdir.path }}"

- hosts: localhost
  gather_facts: false
  tasks:

  - name: print stdout in next play
    debug: msg="Value of the variable is {{ hostvars[ "{{host}}" ].stagingdir.path }}"

###################

# ansible-playbook test.yml -e "host=testhost"

PLAY [testhost] *************************************************

TASK [Create local staging dir] *************************************************
changed: [testhost -> localhost]

TASK [print stdout in same play] ************************************************
ok: [testhost] => {
    "msg": "Value of the variable is /tmp/ansible.IsLik6"
}

PLAY [localhost] ****************************************************************

TASK [print stdout in next play] ************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: \"hostvars['{{host}}']\" is undefined\n\nThe error appears to be in '/home/ooauto/ansible/test.yml': line 17, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: print stdout in next play\n    ^ here\n"}

PLAY RECAP **********************************************************************
testhost   : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
localhost                  : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
Reply all
Reply to author
Forward
0 new messages