iterating a hash in a task

The question was asked a few times on freenode (by myself included). Just sharing my solution in case it’s useful for someone else:
https://coderwall.com/p/rxsmvw

best,
./A

Please send a pull request to add something like this to core, but rather than a filter plugin, it really should be a lookup plugin.

with_hash_items: ahash

etc

–Michael

I was hoping you’d say that.

If this functionality is going to be part of core, I feel the following is a better way to access the individual items:

task:

  • name: echo
  • action: command echo “{{ item.key item.value }}”
    with_hash_items: ${var}

… instead of item[0] for key and item[1] for value.

Open to suggestions of course.

best,
./A

"If this functionality is going to be part of core, I feel the following is a better way to access the individual items:

task:

  • name: echo
  • action: command echo “{{ item.key item.value }}”
    with_hash_items: ${var}"

Public service announcement: Using ${var} is unneccessary here.

with_hash_items: varname

You can do this for all lookup plugins.

Nobody should be using variables of form $x or ${x} anymore. They are included for backwards compatibility only.

Ali-Akber Saifee wrote:

task:

  • name: echo
  • action: command echo “{{ item.key item.value }}”
    with_hash_items: ${var}

FWIW, I had to do something similar today and ended up using the “dictsort” Jinja2 filter:

task:

  • name: echo
    action: command echo “{{ item[0] item[1] }}”
    with_items: var|dictsort

It even has parameters to control the sort order:

http://jinja.pocoo.org/docs/templates/#dictsort

You do have to user the item[0] and item[1] syntax, though, rather than item.key and item.value.

—Alan

Nice, wasn’t aware of this one!

We should add this to the section where we are discussing loops.