I am trying to loop over a hash and arrays associated with it like this:
Var:
dictionary:
aword: [ ant, den ]
bword: [ fat, slim ]
Task:
name: Create symlinks
command: do something with item[0] over item[1]
with_nested:
- "{{ item.key }}"
- "{{ item.value }}"
with_dict: dictionary
This does not work. Am I doing something wrong or Ansible doesn't support such iteration?
I solved this one using
with_subelements
like this
vars:
dictionary:
- name: aword
words:
- ant
- den
- name: bword
words:
- fat
- slim
Task:
name: Create symlinks
command: do something with item.0.name over item.1
with_subelements:
- dictionary
- words
For completeness, this can also be accomplished using with_nested
by creating nested lists in Ansible. Doing so allows the same looping behavior without requiring setting a var/fact. This is useful for when you want to instantiate the nested lists on the task itself.
Like so:
---
- hosts: localhost
connection: local
become: false
tasks:
- debug:
msg: "do something with {{ item[0] }} over {{ item[1] }}"
with_nested:
- - ant # note the two hyphens to create a list of lists
- den
- - fat
- slim
Output:
TASK [debug] ********************************************************************************************
ok: [localhost] => (item=[u'ant', u'fat']) => {
"changed": false,
"item": [
"ant",
"fat"
],
"msg": "do something with ant over fat"
}
ok: [localhost] => (item=[u'ant', u'slim']) => {
"changed": false,
"item": [
"ant",
"slim"
],
"msg": "do something with ant over slim"
}
ok: [localhost] => (item=[u'den', u'fat']) => {
"changed": false,
"item": [
"den",
"fat"
],
"msg": "do something with den over fat"
}
ok: [localhost] => (item=[u'den', u'slim']) => {
"changed": false,
"item": [
"den",
"slim"
],
"msg": "do something with den over slim"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With