Ansible Nested Loop Question

Hi there,

I am using the following tasks to iterate over all policy-maps (outer loop) and I would also like to iterate over all class-maps into each policy-map (inner-loop)

  • name: Gather all policy-maps

ansible.utils.cli_parse:

command: show policy-map

parser:

name: ansible.netcommon.pyats

set_fact: qos

  • name: Print all policy-maps

ansible.builtin.debug:

msg: “no policy-map {{ item.key }}”

msg: “no class-map {{ item.xxxx }}”. <— I also want to iterate over the class-maps

loop: “{{ qos.policy_map|dict2items }}”

After applying the dict2items the following is produced.

ok: [cat3850] => (item={‘key’: ‘policy3’, ‘value’: {‘class’: {‘example3’: {}, ‘example4’: {‘set’: ‘dscp af12’}, ‘class-default’: {‘set’: ‘ip dscp af12’}}}}) => {

“ansible_loop_var”: “item”,

“changed”: false,

“item”: {

“key”: “policy3”, <— right now iterating over this works

“value”: {

“class”: {. <— I also want to iterate over the class

“class-default”: { <— I want to match only the class name

“set”: "ip dscp af12”. <— I don’t want to match this

},

“example3”: {}, <— And also match this class name

“example4”: {. <— And also match this class name and so on.

“set”: "dscp af12”. <— I don’t want to match this

}

}

}

},

“msg”: "no policy-map policy3”. <— this is want I want for each class name too

}

Thank you,

Lucius

What I usually do in these cases is including a separate task file for
the "item" at hand.

Pseudo code:

main.yml:

- Do stuff
- include_tasks: policymap.yml
  loop: "{{ policymaps }}"
  loop_control:
    loop_var: policymap

policymap.yml:

- #other task for the policymap
- include_tasks: classmap.yml
  loop: "{{ policymap.classmaps }}"
  loop_control:
    loop_var: classmap

classmap.yml:
- do stuff with "{{ classmap }}"...

You can descend down into as many nested levels as needed by adding a
task file for each level.
It may seem a bit clunky at first, but I find it quite clear to
understand as it's all very explicit and the files themselves are
small.

Dick

Yes, modularising is best practice, thanks for the tip.