How to Pick and match the inventory_hostname against {{ ansible_hostname }} using groups.hosts

3,834 views
Skip to first unread message

rrak...@gmail.com

unread,
Mar 12, 2018, 11:25:11 AM3/12/18
to Ansible Project
Hi Experts,


---
- hosts: all
  remote_user: root
  tasks:
  - name: test variable
    shell: echo "setosprov-04.sh -o OSLABEL -b SITE hostinfo={{ ansible_hostname }}:{{ ansible_default_ipv4.address }} CIC0" 
    #when: inventory_hostname == "{{ inventory_hostname }}"
    when: inventory_hostname == groups.hosts

My hostvar inventory as below:

[hosts]
host-test1
host-test2
noi-pranjala
[hosts:vars]
ansible_ssh_user=root


Now i'm checking where "{{ ansible_hostname }}" should match the each   "{{ inventory_hostname }}"  and if  "{{ inventory_hostname }}" matches with  "{{ ansible_hostname }}"  then proceed otherwise fail.

I tried using "when: inventory_hostname == groups.hosts"  it didn't pich the hostnames Serially hence its getting failed, So, how to ensure the each "{{ inventory_hostname }}"  can be red serially so it can run to all the hosts in a sequence so it may match the hostname correctlt and compare the condition.

Brian Coca

unread,
Mar 12, 2018, 11:32:11 AM3/12/18
to Ansible Project
First of all you are comparing a string (inventory_hostname) to a list
(groups.hosts, which is [host-test1, host-test2, noi-pranjala]).

if you want to match inventory-hostname to ansible_hostname, just do that:


when: inventory_hostname == ansible_hostname


that will skip the task when they don't match.


if you want the task to actually fail:


failed_when: inventory_hostname != ansiblie_hostname


----------
Brian Coca

rrak...@gmail.com

unread,
Mar 12, 2018, 12:01:39 PM3/12/18
to Ansible Project
@Brian ,  Thanks a lot for your suggestion, this looks Great,

What about "when: inventory_hostname == groups.hosts"  when: inventory_hostname == groups.hosts[0] , i google around but did not get clear & explicit explanation about its usage

Brian Coca

unread,
Mar 12, 2018, 12:11:34 PM3/12/18
to Ansible Project
This is invalid, as i explained above:
when: inventory_hostname == groups.hosts"


This works when the 'current host' is also the 'first host in the
group', here [0] is an index on the list that is group.hosts, so it is
a valid comparison.

when: inventory_hostname == groups.hosts[0]

> --
> 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 post to this group, send email to ansible...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/ansible-project/ca01ad77-4c40-4f5e-8162-32636a1c7a6a%40googlegroups.com.
>
> For more options, visit https://groups.google.com/d/optout.



--
----------
Brian Coca
Reply all
Reply to author
Forward
Message has been deleted
0 new messages