Passing more than one var between tasks - how is it done?

As was said before, .records is a list, each item of which contains .attachments which is also a list, so to handle it correctly you’ll need to iterate over each record × attachment combination.

A typical way to handle nested loops is to use an included tasks file. The first task below just dumps out CR sys_ids paired with their attachments’ sys_ids. The second task iterates over each of the CRs.

    - name: Dump CRs and Attachments
      ansible.builtin.debug:
        msg: "{{ dcr_new_cr_request_found_out.records
                 | json_query('[].{cr_sysid: sys_id,
                                   cr_attachments: attachments[].sys_id
                                  }'
                             ) }}"
    - name: Handle each CR
      ansible.builtin.include_tasks:
        file: clerambeau370_01_cr.yml
      loop: "{{ dcr_new_cr_request_found_out.records }}"
      loop_control:
        loop_var: cr

The included task sees each CR in the variable cr, and the debug task there loops over that cr’s attachments. Behold:

---
# clerambeau370_01_cr.yml
- name: Handle CR attachments
  ansible.builtin.debug:
    msg: "handling CR {{ cr.sys_id }}, Attachment {{ attachment.sys_id }}."
  loop: "{{ cr.attachments }}"
  loop_control:
    loop_var: attachment

The output contains

msg: handling CR 34a34e0883f6f210f28198c6feaad380, Attachment fc2b752983bab210f28198c6feaad3a5.
msg: handling CR 34a34e0883f6f210f28198c6feaad380, Attachment 742b752983bab210f28198c6feaad3a7.
msg: handling CR 34a34e0883f6f210f28198c6feaad380, Attachment f82b752983bab210f28198c6feaad3a8.

If your initial results contained more than one CR, this would still work.

1 Like