Hi
I have a dictionary of disks in my host vars:
`
disks:
sdc:
dev: sdc
vg: vg01
lv: app
mp: ‘/opt/app’
sdd:
dev: sdd
vg: vg02tmp
lv: shared
mp: ‘/opt/app/oracle/shared’
`
A very basic playbook, just to access the dictionary::
`
tasks:
debug:
msg: “disk name: {{item}}”
loop:
“{{disks}}”
`
shows good results so I’m pretty sure I have the dictionary defined correctly:
TASK [debug] ************************************************************************************************************************************************** ok: [mynewhost] => (item=[{'key': 'sdc', 'value': {'dev': 'sdc', 'vg': 'vg01', 'lv': 'app', 'mp': '/opt/app'}}, {'key': 'sdd', 'value': {'dev': 'sdd', 'vg': 'vg02tmp', 'lv': 'shared', 'mp': '/opt/app/oracle/shared'}}]) => { "msg": "disk name: [{'key': 'sdc', 'value': {'dev': 'sdc', 'vg': 'vg01', 'lv': 'app', 'mp': '/opt/app'}}, {'key': 'sdd', 'value': {'dev': 'sdd', 'vg': 'vg02tmp', 'lv': 'shared', 'mp': '/opt/app/oracle/shared'}}]" }
How do I loop over the dictionary key? in this case, it’d be sdc and sdd… I’ve been trying iteration of {{item.key}}, and {{disks.key}} but nothing has worked yet.
Thanks for any hints/tips/suggestions.
Doug O’Leary
racke
(Stefan Hornburg)
June 12, 2020, 12:44pm
2
Hi
I have a dictionary of disks in my host vars:
>
disks:
sdc:
dev: sdc
vg: vg01
lv: app
mp: '/opt/app'
sdd:
dev: sdd
vg: vg02tmp
lv: shared
mp: '/opt/app/oracle/shared'
>
A **very** basic playbook, just to access the dictionary::
>
tasks:
-debug:
msg:"disk name: {{item}}"
loop:
-"{{disks}}"
>
shows good results so I'm pretty sure I have the dictionary defined correctly:
>
TASK
[debug]**************************************************************************************************************************************************
ok:[mynewhost]=>(item=[{'key':'sdc','value':{'dev':'sdc','vg':'vg01','lv':'app','mp':'/opt/app'}},{'key':'sdd','value':{'dev':'sdd','vg':'vg02tmp','lv':'shared','mp':'/opt/app/oracle/shared'}}])=>{
"msg":"disk name: [{'key': 'sdc', 'value': {'dev': 'sdc', 'vg': 'vg01', 'lv': 'app', 'mp': '/opt/app'}}, {'key':
'sdd', 'value': {'dev': 'sdd', 'vg': 'vg02tmp', 'lv': 'shared', 'mp': '/opt/app/oracle/shared'}}]"
}
>
How do I loop over the dictionary key? in this case, it'd be sdc and sdd... I've been trying iteration of
{{item.key}}, and {{disks.key}} but nothing has worked yet.
Thanks for any hints/tips/suggestions.
Old style:
with_dict: "{{ disks }}"
New style:
loop: "{{ disks | dict2items }}"
In both cases the key is in item.key and values can be accessed with item.value, e.g item.value.dev.
Reference: https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#iterating-over-a-dictionary
Regards
Racke
Never mind, I got it. Amazing how often I ask the question then immediately find the answer…
The trick is:
`
tasks:
debug:
msg: “disk name: {{item.key}}”
with_dict: “{{disks}}”
`
Theoretically, this should work too:
`
loop:
“{{lookup(‘dict’, disks)}}”
`
Hopefully, that’ll help someone.
Thanks
Doug