How to access a certain element of a register variable in a loop

I discovered the other day that when a register variable is used in a loop, like this

`

  • name: Generate pw’s for users
    command: “/some_path/generate_hashed_pw.sh -u {{ item }}”
    register: hashed_pws
    with_items:
  • joe
  • sally
  • john
    `

the hashed_pws register is a hash that contains a results key, which is an array of hashes, like so

{ "hashed_pws: { "changed" : true, "some_other_key" : "some_other_value", "results" : [ { "item" : "joe", "stdout": "joes_hashed_pw", "some_other_key" : "some_other_value" }, { "item" : "sally", "stdout": "sallys_hashed_pw", "some_other_key" : "some_other_value" }, { "item" : "john", "stdout": "johns_hashed_pw", "some_other_key" : "some_other_value" } ] } }

So what is the syntax to directly access, the “stdout” element in each of the hash elements in the array? In other words, I want:

`

  • debug: msg=“Sallys hashed pw is {{ hashed_pws.results[SOME_KEY_TO_DIRECTLY_GET_SALLYS_STDOUT_VALUE] }}”
    `

This is probably a python question as much as it is an Ansible question.

I think this is what you want:

  • debug: msg=“Sallys hashed pw is {{item.stdout}}”
    with_items: “{{hashed_pws.results}}”

That will list ALL the item.stdout values, not just Sally’s.

when: item.item == ‘sally’

This gave me a clue. Loop through a registered variable with with_dict in Ansible, so I did this.

`

  • debug: msg=‘{{ item }} hashed value is {{ hashed_pws.results | selectattr(“item”,“equalto”,item) | map(attribute=“stdout”) | first }}’
    with_items:
  • joe
  • sally
  • john
    `

If you know what you are looking for, isn’t this the simplest solution - when: item.item == ‘sally’