How to use hostvars?

22 views
Skip to first unread message

黄冠雄

unread,
Sep 9, 2019, 5:54:33 AM9/9/19
to Ansible Project
My ansible version is 2.5.
In my playbook, one host needs to access other host's variable which I defined in inventory file.
I used {{ hostvars['groupname'].var_name }} and get an error, I also tried to use {{ hostvars['groupname']['var_name'] }} which get an error also.
So, I want to be clear how to use hostvars to access another host variables defined in the inventory file?

Dick Visser

unread,
Sep 9, 2019, 6:26:25 AM9/9/19
to ansible...@googlegroups.com
You don't say what error you get?

In any case, you are trying to access hostvars for a group, which
isn't possible.
Instead, you need to access hostvars from a host.
So for a group, practically this is done by accessing the hostvars of
the first host of a group, like this:

hostvars[groups['groupname'][0]]['var_name']

Dick
> --
> You received this message because you are subscribed to the Google Groups "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/e5ee9ca4-0099-4d2a-aa8a-659a69815ea3%40googlegroups.com.



--
Dick Visser
Trust & Identity Service Operations Manager
GÉANT

黄冠雄

unread,
Sep 9, 2019, 9:19:31 PM9/9/19
to Ansible Project
Hi, thanks for your reply, I resolve this by using {{ hostvars[groups['groupname'][0]].var_name }}.

在 2019年9月9日星期一 UTC+8下午6:26:25,Dick Visser写道:
You don't say what error you get?

In any case, you are trying to access hostvars for a group, which
isn't possible.
Instead, you need to access hostvars from a host.
So for a group, practically this is done by accessing the hostvars of
the first host of a group, like this:

 hostvars[groups['groupname'][0]]['var_name']

Dick

On Mon, 9 Sep 2019 at 11:54, 黄冠雄 <huanggu...@gmail.com> wrote:
>
> My ansible version is 2.5.
> In my playbook, one host needs to access other host's variable which I defined in inventory file.
> I used {{ hostvars['groupname'].var_name }} and get an error, I also tried to use {{ hostvars['groupname']['var_name'] }} which get an error also.
> So, I want to be clear how to use hostvars to access another host variables defined in the inventory file?
>
> --
> You received this message because you are subscribed to the Google Groups "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to ansible...@googlegroups.com.
Reply all
Reply to author
Forward
Message has been deleted
Message has been deleted
0 new messages