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

51 views
Skip to first unread message

ZillaYT

unread,
Sep 26, 2016, 11:40:49 AM9/26/16
to Ansible Project
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.


Brian Coca

unread,
Sep 26, 2016, 11:46:10 AM9/26/16
to ansible...@googlegroups.com
I think this is what you want:

- debug: msg="Sallys hashed pw is {{item.stdout}}"
  with_items: "{{hashed_pws.results}}"


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

ZillaYT

unread,
Sep 26, 2016, 12:34:33 PM9/26/16
to Ansible Project
That will list ALL the item.stdout values, not just Sally's.

Brian Coca

unread,
Sep 26, 2016, 1:03:45 PM9/26/16
to ansible...@googlegroups.com
when: item.item == 'sally'


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

ZillaYT

unread,
Sep 26, 2016, 1:07:04 PM9/26/16
to Ansible Project
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

ishan jain

unread,
Sep 27, 2016, 10:09:40 AM9/27/16
to Ansible Project
If you know what you are looking for, isn't this the simplest solution - when: item.item == 'sally'
Reply all
Reply to author
Forward
0 new messages