Reputation: 287
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?
Upvotes: 3
Views: 13237
Reputation: 312
I know it's an old question, but just found the solution for this problem. Just put this before using hostvars in the next task or role and somehow you will be able to use the hostvars variables into hosts: definition.
- name: Do nothing
hosts: all
gather_facts: no
become: no
it seems that there is no need for run_once: yes (maybe only for some performance improvment, if any) I can't say I understand what's under the hood, but it seems that ansible (2.9, 2.10) need something bogus in order to use hostvars variable in the next tasks/roles.
Upvotes: 1
Reputation: 7917
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.
Upvotes: 4