Why my 'hostvars' is undefined ...

742 views
Skip to first unread message

Philippe Limouzy

unread,
Mar 8, 2022, 10:02:54 AM3/8/22
to Ansible Project
Hi Evrybody, 
I'm facing to a problem that I don't understand the origin:  Any help will be welcome. 

I want to use in a playbook a role where the name depends on a variable defined in the inventory. 
 
I have the following dynamic inventory for a host: 

the command ansible-inventory -i /etc/ansible/cobbler.py --host "rhel8-test-2"  returns: 

{
    "cobbler": {  
         ...
        "image": "",
        "ks_meta": {},
        "mgmt_classes": [
            "online",
        ],
        "name": "rhel8-test-2",
        "netboot_enabled": true,
        "power_user": "",
        "profile": "HWCL_402"
    }
}

In my playbook I want to acess to the profile variable   =>     "cobbler.profile": "HWCL_402"
The following playbook works fine: 

---
- name: " print profile"
  hosts: "{{ myhost }}"
  gather_facts: no

  vars:
    PROFILE: "{{ hostvars[inventory_hostname].cobbler.profile }}"

  tasks:

  - name: print profile value defined in inventory
    ansible.builtin.debug:
      msg: "{{  PROFILE }}"


This  playbook prints the correct value of my variable: 
ansible-playbook -i /etc/ansible/cobbler.py    playbook2.yml -e "myhost=rhel8-test-2"

PLAY [print profile] *******************************************************************************************
TASK [print profile value defined in inventory] *******************************************************************************************
ok: [rhel8-test-2] => {
    "msg": "HWCL_402"
}
...


Now, , I add the call to a role ( echo )  where the path depends  on profile value:  
-> the role is under HWCL_402/echo

---
- name: " use profile"
  hosts: "{{ myhost }}"
  gather_facts: no

  vars:

    PROFILE: "{{ hostvars[inventory_hostname].cobbler.profile }}"

  tasks:

  - name: print profile value defined in inventory
    ansible.builtin.debug:
      msg: "{{  PROFILE }}"

  roles:

    - "{{ PROFILE }}/echo"

the execution of this modifified playbook returns immediatly : 

ERROR! {{ hostvars[inventory_hostname].cobbler.profile }}: 'hostvars' is undefined

what I did wrong ?  why hostvars is undefined ? it was correct in the previous example ? 
If I declare PROFILE  in a simple variable  ( not in the inventory) it 'works also fine ! 

Best regards. 
Philippe. 

Roland Müller

unread,
Mar 10, 2022, 2:39:35 PM3/10/22
to Ansible Project
Hello,

I think that hostvars can be used only for something that is related to a target host where ansible tasks are executed (in your case behind variable 'myhost'). The definition of a role directory again is related to the control host thus the host where your playbook is running.

 BR
Roland
Reply all
Reply to author
Forward
0 new messages