Iterate over hosts in a group with index

Hi all,

So I’m trying to figure out how I can iterate over the hosts in a group along with an index value. I’m trying to do something like this:

  • name: My Task
    shell: echo Host Number {{ item }} is {{ groups.mygroup[item] }}
    with_sequence: start=0 end={{ groups.mygroup|count - 1 }}

But it seems that ‘groups.mygroup[item]’ does not get evaluated like I expect it to.

Any way to do this?

Probably because the sequence plugin is returning strings and you have to cast them, but we generally don’t like it when people have to program.

Things should be easier, as well as much more readable.

I would suggest we create a lookup plugin called “with_indexed_items”, so it could be as simple as:

  • name: My Task
    shell: echo Host Number {{ item.0 }} is {{ item.1 }}
    with_indexed_items: groups.mygroup

It would be a small copy of “with_items” with a one or two line change to get there.

I really like that idea, but with a small change:

  • name: My Task
    shell: echo Host Number {{ item.index }} is {{ item.value }}
    with_indexed_items: groups.mygroup

What do you think? That way it’s clear which value is the index and which is the value from the items being iterated over. I’ve tweaked the ‘with_items’ lookup plugin to do this and pretty happy with the result. Much cleaner than what I was originally attempting :slight_smile:

Yeah, I am not a fan of this because we already have a precedence for returning indexes when used with “with_nested” and others, plus it would be consistent with “enumerate()” in Python.

Agreed. Consistency is generally a good idea. I’ve submitted a PR with the change you originally suggested.