Search code examples
ansibleansible-inventory

Need to use host variables in Ansible (ansible engine 2.8 & ansible tower 3.5)


Need your help in achieving below: - use variables provided inline with hostIP (i.e. host variables) in Ansible inventory

my inventory:

[ora_patch]
10.24.29.14 SID=orcl,orcl2

my playbook:

---
- hosts: [ora_patch]
  tasks:
  - debug:
     var: "{{ hostvars[ansible_host]['SID'] }}"

Output ** I GET **:

PLAY [ora_patch] ************************************************************

TASK [patch_ora_si_122 : debug] *****************************************
ok: [10.24.29.14] => {
    "orcl,orcl2": "(Undefined, Undefined)"
}

PLAY RECAP ******************************************************************
10.24.29.14               : ok=1    changed=0    unreachable=0    failed=0

Output ** I want ** :

PLAY [ora_patch] ***********************************************************

TASK [patch_ora_si_122 : debug] ****************************************
ok: [10.24.29.14] => {
    "SID": "orcl,orcl2"
}

PLAY RECAP *****************************************************************
10.24.29.14               : ok=1    changed=0    unreachable=0    failed=0

Command I execute:

ansible-playbook -i inventory patch_ora_si_122.yml

Solution

  • Your playbook is slightly wrong. You are trying to use the content of the hostvar "{{ hostvars[ansible_host]['SID'] }}" as a variable name to display with debug: var=....

    Simply change your playbook to

    ---
    - hosts: ora_patch
      tasks:
      - debug:
         msg: "SID: {{ hostvars[ansible_host]['SID'] }}"
    

    or you could also use the variable name directly:

    ---
    - hosts: ora_patch
      tasks:
      - debug:
         var: SID