What does the [0] mean in when: inventory_hostname == groups['mongo_servers'][0] ?

I saw this in the ansible-examples / openshift / openshift_ec2 / roles / mongodb / tasks / main.yml

  • name: Initialize the replication set
    shell: /usr/bin/mongo --port “{{ mongod_port }}” /tmp/repset_init.js;touch /opt/rep.init creates=/opt/rep.init
    when: inventory_hostname == groups[‘mongo_servers’][0]

What does the [0] mean in when: inventory_hostname == groups[‘mongo_servers’][0] ?

I wanted to find a conditional that would say: when inventory_hostname is not in group mailservers

It seems to work for me with this now:

when: inventory_hostname != groups[‘mailservers’][0]

But I just don’t understand what the syntax means.

Thanks!

Hi David,

That means the first host in the group “mongo_Servers”. [0] notion means the first element in a list. similarly [1] means the second element in a list.

Regards,
Benno

How can I use this when function to work with the hosts in my inventory file? I had when: inventory_hostname == play_hosts[0] but I notice that it only selects a random server. I want it to select all of the servers. Using a * doesn’t work…

I don't understand why you want to do this, inventory_hostname will always be in play_hosts, so it will always be true.
Maybe you are looking for "with_items: play_hosts"?

To check if something is in a list the syntax is
when: <variable> in <list>