How to access group variables from inventory file inside ansible yaml

ansibleansible-inventory

I have an inventory file with one group like below:

[example1]
H1 ip1 username1 
H2 ip2 username2
H3 ip3 username3

and I have defined group variable like below to make that variable common to all hosts in that group:

[example1:vars]
temp='H2'

I am trying to access this variable inside my ansible yml under hosts field like below:

---
 - name: temp playbook to practice hostvars
   hosts: "{{ hostvars['example1']['temp'] }}"
   tasks:
    .....
    .....
    ....

But while executing this playbook, I am getting the hostvars undefined error like below:

"ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'hostvars' is undefined"

My ansible file and inventory file in same folder, could anyone help me to rectify what I am missing to access the variable from inventory file?

Best Answer

Please, don't do it like that. It's bad way. Use groups with 'children' property for host grouping.

Nevertheless, here is a fix for your problem. You've tried to access hostvars for a group. There is no host 'example1' in your inventory. And hostvars have variables for host, as you can see.

Following code will do the trick:

- hosts: localhost
  gather_facts: no
  tasks:
   - debug:
- hosts: '{{  hostvars[groups.example1[0]].temp }}'
  tasks:
     ...

I use groups.example1 to get a list of hosts in a group example1, then I take first member of that group ([0]) then I peek into its variables through hostvars.

The strange task with debug at the begin need to help Ansible to initialize hostvars. Without it, it will fail with undefined variable error.

But, again, don't do it like that. It's really, really mess up way to reinvent groups.

Related Topic