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

Hello. This is a continuation of the post “Passing a var between tasks”. Thanks all who chimed in on that one, your help is immensely appreciated! There is no need to read that previous post, as the question is stated clearly enough herein.
I have a playbook that does the following:

Go to ServiceNow ticketing system, get a Change Request meeting specific parameters, pass its SYS_ID to the next task which will download all the attachments in it. Each such attachment bears a unique SYS_ID, just like the master CR which has its own SYS_ID as well.

I managed to write it (barely!) in such a way that it only gets the first attachment to the Change Request and ignores the remaining ones. That means I will have to limit the users to upload multiple scripts to a request, which is unreasonable.

sys_id: "{{ dcr_new_cr_request_found_out.records[0].sys_id }}"

However, a Change Request may and will have multiple attachments.

Therefore, I need to re-write the playbook below in such a way that downloads all attachments, however many there may be.

The playbook and output below are downloading only one attachment.

Change Request “sys_id”: “fc2b752983bab210f28198c6feaad3a5”
attachments:
“sys_id”: “fc2b752983bab210f28198c6feaad3a5”
“sys_id”: “742b752983bab210f28198c6feaad3a7”
“sys_id”: “f82b752983bab210f28198c6feaad3a8”

---
    - name: Oracle database Data Change Request Process ID 2872.56
#      hosts: dbservers
      hosts: localhost
      gather_facts: true
      vars_files:
        - vars/main.yml

      tasks:

        - name: 0. Prepare. Display Ansible date_time fact and register | itsm_dcr
          delegate_to: localhost
          run_once: true
          set_fact: 
            currenttime: "{{ ansible_date_time.iso8601 }}"
          tags: linux

        - name: 1. Retrieve new DCR change requests
          servicenow.itsm.change_request_info:
             instance:
               host: "{{ sn_instance}}"
               username: "{{ sn_username }}"
               password:  "{{ sn_password }}"
             query:
              - state: = new
              - short_description: LIKE DCR
          register: dcr_new_cr_request_found_out
          delegate_to: localhost

        - name: 1.1 Debug the ServiceNow Change Request details to get the attachment SYS_ID | itsm_dcr
          debug: var=dcr_new_cr_request_found_out  

        - name: Cache the CR SYS_ID {{ ansible_date_time.iso8601 }} | itsm_dcr
          ansible.builtin.set_fact:
            sys_id: "{{ dcr_new_cr_request_found_out.records[0].sys_id }}"    

        - name: 2. Download the Change Request attachment with its hardcoded SYS_ID from Step 1 | itsm_dcr
          servicenow.itsm.attachment: 
            instance:
              host: "{{ sn_instance}}"
              username: "{{ sn_username }}"
              password:  "{{ sn_password }}"
            dest: /tmp/DCR_{{ currenttime }}_00000001.sql
            sys_id: "{{ dcr_new_cr_request_found_out.records[0].attachments[0].sys_id }}"            
#            sys_id: 003a3ef24ff1120031577d2ca310c74b
          register: dcr_new_cr_attachment_out  

        - name: 2.1 Debug the hardcoded-SYS-ID attachment download details | itsm_dcr
          debug: var=dcr_new_cr_attachment_out   

and the output (note there are four *.sql attachments in that CR):

[ansible_admin@ctrl ansible]$ ansible-playbook ./playbooks/dcr_03.yml

PLAY [Oracle database Data Change Request Process ID 2872.56] *************************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************************************************************************
ok: [localhost]
[WARNING]: Using run_once with the free strategy is not currently supported. This task will still be executed for every host in the inventory list.

TASK [0. Prepare. Display Ansible date_time fact and register | itsm_dcr] *************************************************************************************************************
ok: [localhost]

TASK [1. Retrieve new DCR change requests] ********************************************************************************************************************************************
[WARNING]: Encountered unknown value  while mapping field risk.
[WARNING]: Encountered unknown value Software while mapping field category.
ok: [localhost]

TASK [1.1 Debug the ServiceNow Change Request details to get the attachment SYS_ID | itsm_dcr] ****************************************************************************************
ok: [localhost] => {
    "dcr_new_cr_request_found_out": {
        "changed": false,
        "failed": false,
        "records": [
            {
                "active": "true",
                "activity_due": "",
                "additional_assignee_list": "",
                "approval": "approved",
                "approval_history": "",
                "approval_set": "2026-01-27 19:29:50",
                "assigned_to": "3c589a008334f210f28198c6feaad375",
                "assignment_group": "db53580b0a0a0a6501aa37c294a2ba6b",
                "attachments": [
                    {
                        "average_image_color": "",
                        "chunk_size_bytes": "700000",
                        "compressed": "true",
                        "content_type": "text/x-sql",
                        "download_link": "https://dev276659.service-now.com/api/now/attachment/fc2b752983bab210f28198c6feaad3a5/file",
                        "file_name": "DCR_002.sql",
                        "hash": "495a9dfd6868afb81786f3edb5183ebbde68fe136395373d7bacabb1fa36c24a",
                        "image_height": "",
                        "image_width": "",
                        "size_bytes": "76",
                        "size_compressed": "92",
                        "state": "available",
                        "sys_created_by": "admin",
                        "sys_created_on": "2026-02-01 10:42:41",
                        "sys_id": "fc2b752983bab210f28198c6feaad3a5",
                        "sys_mod_count": "1",
                        "sys_tags": "",
                        "sys_updated_by": "system",
                        "sys_updated_on": "2026-02-01 10:42:41",
                        "table_name": "change_request",
                        "table_sys_id": "34a34e0883f6f210f28198c6feaad380"
                    },
                    {
                        "average_image_color": "",
                        "chunk_size_bytes": "700000",
                        "compressed": "true",
                        "content_type": "text/x-sql",
                        "download_link": "https://dev276659.service-now.com/api/now/attachment/742b752983bab210f28198c6feaad3a7/file",
                        "file_name": "DCR_003.sql",
                        "hash": "468948ef7571706b68865cb9617fa979decc5664d30353742f03c024c0e6f3c5",
                        "image_height": "",
                        "image_width": "",
                        "size_bytes": "148",
                        "size_compressed": "141",
                        "state": "available",
                        "sys_created_by": "admin",
                        "sys_created_on": "2026-02-01 10:42:41",
                        "sys_id": "742b752983bab210f28198c6feaad3a7",
                        "sys_mod_count": "1",
                        "sys_tags": "",
                        "sys_updated_by": "system",
                        "sys_updated_on": "2026-02-01 10:42:41",
                        "table_name": "change_request",
                        "table_sys_id": "34a34e0883f6f210f28198c6feaad380"
                    },
                    {
                        "average_image_color": "",
                        "chunk_size_bytes": "700000",
                        "compressed": "true",
                        "content_type": "text/x-sql",
                        "download_link": "https://dev276659.service-now.com/api/now/attachment/f82b752983bab210f28198c6feaad3a8/file",
                        "file_name": "DCR_004_controlled_failure.sql",
                        "hash": "5d48a20d5bd0003a1d3bad56aa43127b33b4274f55978e6404aeb1b49d602aa1",
                        "image_height": "",
                        "image_width": "",
                        "size_bytes": "264",
                        "size_compressed": "198",
                        "state": "available",
                        "sys_created_by": "admin",
                        "sys_created_on": "2026-02-01 10:42:41",
                        "sys_id": "f82b752983bab210f28198c6feaad3a8",
                        "sys_mod_count": "1",
                        "sys_tags": "",
                        "sys_updated_by": "system",
                        "sys_updated_on": "2026-02-01 10:42:41",
                        "table_name": "change_request",
                        "table_sys_id": "34a34e0883f6f210f28198c6feaad380"
                    }
                ],
                "backout_plan": "",
                "business_duration": "",
                "business_service": "281a4d5fc0a8000b00e4ba489a83eedc",
                "cab_date_time": "",
                "cab_delegate": "",
                "cab_recommendation": "",
                "cab_required": "false",
                "calendar_duration": "",
                "category": "Software",
                "change_plan": "",
                "chg_model": "007c4001c343101035ae3f52c1d3aeb2",
                "close_code": "",
                "close_notes": "",
                "closed_at": "",
                "closed_by": "",
                "cmdb_ci": "0c43d5e2c61122750182c132a8b9e2d9",
                "comments": "",
                "comments_and_work_notes": "",
                "company": "",
                "conflict_last_run": "",
                "conflict_status": "Not Run",
                "contact_type": "",
                "contract": "",
                "copied_from": "",
                "correlation_display": "",
                "correlation_id": "",
                "delivery_plan": "",
                "delivery_task": "",
                "description": "--- Managed by r-able.com hyperautomation (TurboCharged, V2.2.2). Do not change manually. Do not deviate. ---\r\n--- This Change Request adds a new deployment to an already installed GoldenGate hub binaries ---\r\n--- Enter the required parameters on the right side of the \":\" below ---\r\nRun dcr\r\n",
                "due_date": "",
                "end_date": "",
                "escalation": "0",
                "expected_start": "",
                "follow_up": "",
                "group_list": "",
                "impact": "low",
                "implementation_plan": "",
                "justification": "",
                "knowledge": "false",
                "location": "",
                "made_sla": "true",
                "number": "CHG0030971",
                "on_hold": false,
                "on_hold_reason": "",
                "on_hold_task": "",
                "opened_at": "2026-01-27 19:28:56",
                "opened_by": "6816f79cc0a8016401c5a33be04be441",
                "order": "",
                "outside_maintenance_schedule": "false",
                "parent": "",
                "phase": "requested",
                "phase_state": "open",
                "priority": "low",
                "production_system": "false",
                "reason": "",
                "reassignment_count": "0",
                "requested_by": "6816f79cc0a8016401c5a33be04be441",
                "requested_by_date": "",
                "review_comments": "",
                "review_date": "",
                "review_status": "",
                "risk": "",
                "risk_impact_analysis": "",
                "route_reason": "",
                "scope": "3",
                "service_offering": "04b89573835e7210f28198c6feaad3f0",
                "short_description": "DCR",
                "sla_due": "",
                "start_date": "",
                "state": "new",
                "std_change_producer_version": "",
                "sys_class_name": "change_request",
                "sys_created_by": "admin",
                "sys_created_on": "2026-01-27 19:29:50",
                "sys_domain": "global",
                "sys_domain_path": "/",
                "sys_id": "34a34e0883f6f210f28198c6feaad380",
                "sys_mod_count": "9",
                "sys_tags": "",
                "sys_updated_by": "admin",
                "sys_updated_on": "2026-02-01 10:49:31",
                "task_effective_number": "CHG0030971",
                "test_plan": "",
                "time_worked": "",
                "type": "normal",
                "unauthorized": "false",
                "universal_request": "",
                "upon_approval": "proceed",
                "upon_reject": "cancel",
                "urgency": "low",
                "user_input": "",
                "watch_list": "",
                "work_end": "",
                "work_notes": "",
                "work_notes_list": "",
                "work_start": ""
            }
        ],
        "warnings": [
            "Encountered unknown value  while mapping field risk.",
            "Encountered unknown value Software while mapping field category."
        ]
    }
}

TASK [Cache the CR SYS_ID 2026-02-01T12:24:11Z | itsm_dcr] ****************************************************************************************************************************
ok: [localhost]

TASK [2. Download the Change Request attachment with its hardcoded SYS_ID from Step 1 | itsm_dcr] *************************************************************************************
changed: [localhost]

TASK [2.1 Debug the hardcoded-SYS-ID attachment download details | itsm_dcr] **********************************************************************************************************
ok: [localhost] => {
    "dcr_new_cr_attachment_out": {
        "changed": true,
        "failed": false,
        "record": {
            "elapsed": 0.41,
            "msg": "OK",
            "size": 76,
            "status_code": 200
        }
    }
}

PLAY RECAP ****************************************************************************************************************************************************************************
localhost                  : ok=7    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[ansible_admin@ctrl ansible]$ 

Please help me tackle this monster.
Nestor Kandinsky-Clerambeau.

1 Like

I’d approach this as follows, of course there are lots of other ways to do this and others will probably suggest better ideas!

  1. Save the output to a file, eg dcr_new_cr_request_found_out.json:
{
  dcr_new_cr_request_found_out: {
    changed: false,
    failed: false,
    records: [
      {
        active: true,
        activity_due: "",
        additional_assignee_list: "",
        approval: approved,
        approval_history: "",
        approval_set: 2026-01-27 19:29:50,
        assigned_to: 3c589a008334f210f28198c6feaad375,
        assignment_group: db53580b0a0a0a6501aa37c294a2ba6b,
        attachments: [
          {
            average_image_color: "",
            chunk_size_bytes: 700000,
            compressed: true,
            content_type: text/x-sql,
            download_link: https://dev276659.service-now.com/api/now/attachment/fc2b752983bab210f28198c6feaad3a5/file,
            file_name: DCR_002.sql,
            hash: 495a9dfd6868afb81786f3edb5183ebbde68fe136395373d7bacabb1fa36c24a,
            image_height: "",
            image_width: "",
            size_bytes: 76,
            size_compressed: 92,
            state: available,
            sys_created_by: admin,
            sys_created_on: 2026-02-01 10:42:41,
            sys_id: fc2b752983bab210f28198c6feaad3a5,
            sys_mod_count: 1,
            sys_tags: "",
            sys_updated_by: system,
            sys_updated_on: 2026-02-01 10:42:41,
            table_name: change_request,
            table_sys_id: 34a34e0883f6f210f28198c6feaad380
          },
          {
            average_image_color: "",
            chunk_size_bytes: 700000,
            compressed: true,
            content_type: text/x-sql,
            download_link: https://dev276659.service-now.com/api/now/attachment/742b752983bab210f28198c6feaad3a7/file,
            file_name: DCR_003.sql,
            hash: 468948ef7571706b68865cb9617fa979decc5664d30353742f03c024c0e6f3c5,
            image_height: "",
            image_width: "",
            size_bytes: 148,
            size_compressed: 141,
            state: available,
            sys_created_by: admin,
            sys_created_on: 2026-02-01 10:42:41,
            sys_id: 742b752983bab210f28198c6feaad3a7,
            sys_mod_count: 1,
            sys_tags: "",
            sys_updated_by: system,
            sys_updated_on: 2026-02-01 10:42:41,
            table_name: change_request,
            table_sys_id: 34a34e0883f6f210f28198c6feaad380
          },
          {
            average_image_color: "",
            chunk_size_bytes: 700000,
            compressed: true,
            content_type: text/x-sql,
            download_link: https://dev276659.service-now.com/api/now/attachment/f82b752983bab210f28198c6feaad3a8/file,
            file_name: DCR_004_controlled_failure.sql,
            hash: 5d48a20d5bd0003a1d3bad56aa43127b33b4274f55978e6404aeb1b49d602aa1,
            image_height: "",
            image_width: "",
            size_bytes: 264,
            size_compressed: 198,
            state: available,
            sys_created_by: admin,
            sys_created_on: 2026-02-01 10:42:41,
            sys_id: f82b752983bab210f28198c6feaad3a8,
            sys_mod_count: 1,
            sys_tags: "",
            sys_updated_by: system,
            sys_updated_on: 2026-02-01 10:42:41,
            table_name: change_request,
            table_sys_id: 34a34e0883f6f210f28198c6feaad380
          }
        ],
        backout_plan: "",
        business_duration: "",
        business_service: 281a4d5fc0a8000b00e4ba489a83eedc,
        cab_date_time: "",
        cab_delegate: "",
        cab_recommendation: "",
        cab_required: false,
        calendar_duration: "",
        category: Software,
        change_plan: "",
        chg_model: 007c4001c343101035ae3f52c1d3aeb2,
        close_code: "",
        close_notes: "",
        closed_at: "",
        closed_by: "",
        cmdb_ci: 0c43d5e2c61122750182c132a8b9e2d9,
        comments: "",
        comments_and_work_notes: "",
        company: "",
        conflict_last_run: "",
        conflict_status: Not Run,
        contact_type: "",
        contract: "",
        copied_from: "",
        correlation_display: "",
        correlation_id: "",
        delivery_plan: "",
        delivery_task: "",
        description: --- Managed by r-able.com hyperautomation (TurboCharged, V2.2.2). Do not change manually. Do not deviate. ---\r\n--- This Change Request adds a new deployment to an already installed GoldenGate hub binaries ---\r
\n--- Enter the required parameters on the right side of the \":\" below ---\r\nRun dcr\r\n,
        due_date: "",
        end_date: "",
        escalation: 0,
        expected_start: "",
        follow_up: "",
        group_list: "",
        impact: low,
        implementation_plan: "",
        justification: "",
        knowledge: false,
        location: "",
        made_sla: true,
        number: CHG0030971,
        on_hold: false,
        on_hold_reason: "",
        on_hold_task: "",
        opened_at: 2026-01-27 19:28:56,
        opened_by: 6816f79cc0a8016401c5a33be04be441,
        order: "",
        outside_maintenance_schedule: false,
        parent: "",
        phase: requested,
        phase_state: open,
        priority: low,
        production_system: false,
        reason: "",
        reassignment_count: 0,
        requested_by: 6816f79cc0a8016401c5a33be04be441,
        requested_by_date: "",
        review_comments: "",
        review_date: "",
        review_status: "",
        risk: "",
        risk_impact_analysis: "",
        route_reason: "",
        scope: 3,
        service_offering: 04b89573835e7210f28198c6feaad3f0,
        short_description: DCR,
        sla_due: "",
        start_date: "",
        state: new,
        std_change_producer_version: "",
        sys_class_name: change_request,
        sys_created_by: admin,
        sys_created_on: 2026-01-27 19:29:50,
        sys_domain: global,
        sys_domain_path: /,
        sys_id: 34a34e0883f6f210f28198c6feaad380,
        sys_mod_count: 9,
        sys_tags: "",
        sys_updated_by: admin,
        sys_updated_on: 2026-02-01 10:49:31,
        task_effective_number: CHG0030971,
        test_plan: "",
        time_worked: "",
        type: normal,
        unauthorized: false,
        universal_request: "",
        upon_approval: proceed,
        upon_reject: cancel,
        urgency: low,
        user_input: "",
        watch_list: "",
        work_end: "",
        work_notes: "",
        work_notes_list: "",
        work_start: ""
      }
    ],
    warnings: [
      Encountered unknown value  while mapping field risk.,
      Encountered unknown value Software while mapping field category.
    ]
  }
}
  1. Open the file using jpterm and work out the JMESPath query needed to get the attachment paths:
  2. Use the json_query module to get the paths:
- name: Set a fact for the attachment download paths
  ansible.builtin.set_fact:
    attachment_urls: "{{ dcr_new_cr_request_found_out | community.general.json_query('records[0].attachments[].download_link') }}"
  1. Use get_url to download the files in a loop and using the string before /filein the URL for the file name:
- name: Download attachments
  ansible.builtin.get_url:
    url: "{{ attachment_url }}"
    dest: "/tmp/{{ attachment_url | ansible.builtin.regex_search('[a-z0-9]{32}[\/]file$') }}"
  loop: "{{ attachment_urls }}"
  loop_control:
    loop_var: attachment_url
2 Likes

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.

2 Likes

You can do it without involving additional tasks files with the ansible.builtin.subelements filter.

- name: Using ansible.builtin.subelements
  ansible.builtin.debug:
    msg: "CR: {{ item[0].sys_id }}, Attachment: {{ item[1].sys_id }}"
  loop: "{{ dcr_new_cr_request_found_out.records
            | ansible.builtin.subelements('attachments', skip_missing=True) }}"

which produces

msg: 'CR: 34a34e0883f6f210f28198c6feaad380, Attachment: fc2b752983bab210f28198c6feaad3a5'
msg: 'CR: 34a34e0883f6f210f28198c6feaad380, Attachment: 742b752983bab210f28198c6feaad3a7'
msg: 'CR: 34a34e0883f6f210f28198c6feaad380, Attachment: f82b752983bab210f28198c6feaad3a8'

It also correctly handles the case of multiple records (i.e., multiple CR),
as well as zero or more attachments per CR.

1 Like

There’s another important point that isn’t a direct answer to your question, but rather more generally about tasks and data management.

Tasks take a lot of time compared to data manipulations. If you find yourself eking out lots of discrete datums and stashing them away with set_fact tasks, consider whether the same information can be derived from existing data at the time of use with appropriate jinja expressions.

For example, {{ dcr_new_cr_request_found_out.records | ansible.builtin.subelements('attachments', skip_missing=True) }} gives you a list of 2-item lists, the first item being a record, the second item being one of the record’s attachments. Looping over this list of pairs gives you access to all the relevant sys_ids etc without having to do a bunch of set_facts beforehand.

Take some time to browse through the list of available filters and lookups, for example:
ansible-doc -t filter --list
ansible-doc -t lookup --list
and dive deeper into any that look like they might be useful in whatever you’re working on (or recently worked on). For example:
ansible-doc -t filter ansible.builtin.subelements
If it seems like it should be useful but the examples don’t make it clear, it’s worth the time to whip up a test playbook with some toy data and play with it until it makes sense. Then when you hit a situation like the one you’re dealing with, you’ll have perhaps enough familiarity with these tools that you can handle it efficiently. That self-training time pays off later.

2 Likes

@chris I apologize for the late reply. Will test this today. Thank you.

1 Like

Thank you @utoddl . I will test your solution today and tomorrow (SUN). Much obliged. nestor.

1 Like

I am testing your solution because it is simple and elegant (and thank you for taking the time to include the links, that took time, but came around as indispensable).
I am having a problem with installing “jmespath”. No matter which way I install it, Ansible doesnt seem to be able to dind it.


[root@ctrl home]# dnf install python3-jmespath
Last metadata expiration check: 1:49:05 ago on Sat 07 Feb 2026 09:29:31 AM EST.
Dependencies resolved.
=================================================================================================
 Package                   Architecture    Version                  Repository              Size
=================================================================================================
Installing:
 python3-jmespath          noarch          0.9.0-11.el8             ol8_appstream           45 k

Transaction Summary
=================================================================================================
Install  1 Package

Total download size: 45 k
Installed size: 117 k
Is this ok [y/N]: y
Downloading Packages:
python3-jmespath-0.9.0-11.el8.noarch.rpm                         151 kB/s |  45 kB     00:00
-------------------------------------------------------------------------------------------------
Total                                                            150 kB/s |  45 kB     00:00
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                         1/1
  Installing       : python3-jmespath-0.9.0-11.el8.noarch                                    1/1
  Running scriptlet: python3-jmespath-0.9.0-11.el8.noarch                                    1/1
  Verifying        : python3-jmespath-0.9.0-11.el8.noarch                                    1/1

Installed:
  python3-jmespath-0.9.0-11.el8.noarch

Complete!
[root@ctrl home]# pip3.8 install jmespath
bash: pip3.8: command not found...
Install package 'python38-pip' to provide command 'pip3.8'? [N/y] y


 * Waiting in queue...
 * Loading list of packages....
The following packages have to be installed:
 python38-3.8.17-2.module+el8.9.0+90017+9913aa0c.x86_64 Interpreter of the Python programming language
 python38-libs-3.8.17-2.module+el8.9.0+90017+9913aa0c.x86_64    Python runtime libraries
 python38-pip-19.3.1-7.module+el8.9.0+90017+9913aa0c.noarch     A tool for installing and managing Python3 packages
 python38-pip-wheel-19.3.1-7.module+el8.9.0+90017+9913aa0c.noarch       The pip wheel
 python38-setuptools-41.6.0-5.module+el8.9.0+90017+9913aa0c.noarch      Easily build and distribute Python 3 packages
 python38-setuptools-wheel-41.6.0-5.module+el8.9.0+90017+9913aa0c.noarch        The setuptools wheel
Proceed with changes? [N/y] y


 * Waiting in queue...
 * Waiting for authentication...
 * Waiting in queue...
 * Downloading packages...
 * Requesting data...
 * Testing changes...
 * Installing packages...
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3.8 install --user` instead.
Collecting jmespath
  Downloading https://files.pythonhosted.org/packages/31/b4/b9b800c45527aadd64d5b442f9b932b00648617eb5d63d2c7a6587b7cafc/jmespath-1.0.1-py3-none-any.whl
Installing collected packages: jmespath
Successfully installed jmespath-1.0.1



[root@lnx001 ~]#  which jmespath-1.0.1
/usr/bin/which: no jmespath-1.0.1 in (/usr/share/Modules/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)
[root@lnx001 ~]#

This is the new playbook with your changes:

---
    - name: Oracle Immediate DCR Process ID 2872.56
      hosts: dbservers
      gather_facts: true
      vars_files:
        - vars/main.yml

      tasks:

        - name: Display Ansible date_time fact and register | itsm_dcr
          delegate_to: localhost
          run_once: true
          set_fact: 
            currenttime: "{{ ansible_date_time.iso8601 }}"
          tags: linux

############################### download from SNOW #########################

        - name: Retrieve new DCR change requests | itsm_dcr
          servicenow.itsm.change_request_info:
             instance:
               host: "{{ sn_instance}}"
               username: "{{ sn_username }}"
               password:  "{{ sn_password }}"
             query:
              - state: = new
              - short_description: LIKE DCR
          register: dcr_new_cr_request_found_out
          delegate_to: localhost

        - name: Debug the ServiceNow Change Request details to get the attachment SYS_ID | itsm_dcr
          debug: var=dcr_new_cr_request_found_out  

        - name: Cache the CR attachment SYS_ID {{ ansible_date_time.iso8601 }} | itsm_dcr
          ansible.builtin.set_fact:
            sys_id: "{{ dcr_new_cr_request_found_out.records[0].sys_id }}"      

        - name: Debug the CR SYS-ID | itsm_dcr
          debug: var=sys_id   

################################ CR NUMBER ###############################

        - name: Cache the CR number {{ ansible_date_time.iso8601 }} | itsm_dcr
          ansible.builtin.set_fact:
            cr_number: "{{ dcr_new_cr_request_found_out.records[0].number }}"

        - name: Debug the CR number | itsm_dcr
          debug: var=cr_number

        - 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
                                  }'
                             ) }}"

This is the output:

[ansible_admin@ctrl ansible]$ ansible-playbook ./playbooks/dcr_several.yml 

PLAY [Oracle Immediate DCR Process ID 2872.56] **********************************************************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************************************************************************
ok: [192.168.1.102]
[WARNING]: Using run_once with the free strategy is not currently supported. This task will still be executed for every host in the inventory list.

TASK [Display Ansible date_time fact and register | itsm_dcr] *******************************************************************************************************************************
ok: [192.168.1.102 -> localhost]

TASK [Retrieve new DCR change requests | itsm_dcr] ******************************************************************************************************************************************
[WARNING]: Encountered unknown value  while mapping field risk.
[WARNING]: Encountered unknown value Software while mapping field category.
ok: [192.168.1.102 -> localhost]

TASK [Debug the ServiceNow Change Request details to get the attachment SYS_ID | itsm_dcr] **************************************************************************************************
ok: [192.168.1.102] => {
    "dcr_new_cr_request_found_out": {
        "changed": false,
        "failed": false,
        "records": [
            {
                "active": "true",
                "activity_due": "",
                "additional_assignee_list": "",
                "approval": "approved",
                "approval_history": "",
                "approval_set": "2026-02-07 16:11:23",
                "assigned_to": "3c589a008334f210f28198c6feaad375",
                "assignment_group": "287ee6fea9fe198100ada7950d0b1b73",
                "attachments": [
                    {
                        "average_image_color": "",
                        "chunk_size_bytes": "700000",
                        "compressed": "true",
                        "content_type": "text/x-sql",
                        "download_link": "https://dev276659.service-now.com/api/now/attachment/cdef352783763210f28198c6feaad3b6/file",
                        "file_name": "DCR_001.sql",
                        "hash": "be2477f129a827a656c0b76392edbfa4b10568341786837b5f67ba7a25abb359",
                        "image_height": "",
                        "image_width": "",
                        "size_bytes": "141",
                        "size_compressed": "146",
                        "state": "available",
                        "sys_created_by": "admin",
                        "sys_created_on": "2026-02-07 16:11:18",
                        "sys_id": "cdef352783763210f28198c6feaad3b6",
                        "sys_mod_count": "1",
                        "sys_tags": "",
                        "sys_updated_by": "system",
                        "sys_updated_on": "2026-02-07 16:11:19",
                        "table_name": "change_request",
                        "table_sys_id": "7ddf352783763210f28198c6feaad328"
                    },
                    {
                        "average_image_color": "",
                        "chunk_size_bytes": "700000",
                        "compressed": "true",
                        "content_type": "text/x-sql",
                        "download_link": "https://dev276659.service-now.com/api/now/attachment/4def352783763210f28198c6feaad3b8/file",
                        "file_name": "DCR_002.sql",
                        "hash": "495a9dfd6868afb81786f3edb5183ebbde68fe136395373d7bacabb1fa36c24a",
                        "image_height": "",
                        "image_width": "",
                        "size_bytes": "76",
                        "size_compressed": "92",
                        "state": "available",
                        "sys_created_by": "admin",
                        "sys_created_on": "2026-02-07 16:11:18",
                        "sys_id": "4def352783763210f28198c6feaad3b8",
                        "sys_mod_count": "1",
                        "sys_tags": "",
                        "sys_updated_by": "system",
                        "sys_updated_on": "2026-02-07 16:11:19",
                        "table_name": "change_request",
                        "table_sys_id": "7ddf352783763210f28198c6feaad328"
                    },
                    {
                        "average_image_color": "",
                        "chunk_size_bytes": "700000",
                        "compressed": "true",
                        "content_type": "text/x-sql",
                        "download_link": "https://dev276659.service-now.com/api/now/attachment/4def352783763210f28198c6feaad3b9/file",
                        "file_name": "DCR_003.sql",
                        "hash": "468948ef7571706b68865cb9617fa979decc5664d30353742f03c024c0e6f3c5",
                        "image_height": "",
                        "image_width": "",
                        "size_bytes": "148",
                        "size_compressed": "141",
                        "state": "available",
                        "sys_created_by": "admin",
                        "sys_created_on": "2026-02-07 16:11:18",
                        "sys_id": "4def352783763210f28198c6feaad3b9",
                        "sys_mod_count": "1",
                        "sys_tags": "",
                        "sys_updated_by": "system",
                        "sys_updated_on": "2026-02-07 16:11:19",
                        "table_name": "change_request",
                        "table_sys_id": "7ddf352783763210f28198c6feaad328"
                    }
                ],
                "backout_plan": "",
                "business_duration": "",
                "business_service": "281a4d5fc0a8000b00e4ba489a83eedc",
                "cab_date_time": "",
                "cab_delegate": "",
                "cab_recommendation": "",
                "cab_required": "false",
                "calendar_duration": "",
                "category": "Software",
                "change_plan": "",
                "chg_model": "007c4001c343101035ae3f52c1d3aeb2",
                "close_code": "",
                "close_notes": "",
                "closed_at": "",
                "closed_by": "",
                "cmdb_ci": "0c43d5e2c61122750182c132a8b9e2d9",
                "comments": "",
                "comments_and_work_notes": "",
                "company": "",
                "conflict_last_run": "",
                "conflict_status": "Not Run",
                "contact_type": "",
                "contract": "",
                "copied_from": "",
                "correlation_display": "",
                "correlation_id": "",
                "delivery_plan": "",
                "delivery_task": "",
                "description": "--- Managed by MMIS DBA hyperautomation. Do not change manually. Do not deviate. ---\r\n--- Attach *.sql script(s) to this DCR to be run in MAMISP1 immediately. ---\r\n--- If these need to be run on a schedule, enter the desired \"Planned Start\" and \"End\" date.---\r\n--- Comments to mmis_dba_automation@mass.gov ---\r\n--",
                "due_date": "",
                "end_date": "",
                "escalation": "0",
                "expected_start": "",
                "follow_up": "",
                "group_list": "",
                "impact": "low",
                "implementation_plan": "",
                "justification": "",
                "knowledge": "false",
                "location": "",
                "made_sla": "true",
                "number": "CHG0031036",
                "on_hold": false,
                "on_hold_reason": "",
                "on_hold_task": "",
                "opened_at": "2026-02-07 16:11:06",
                "opened_by": "6816f79cc0a8016401c5a33be04be441",
                "order": "",
                "outside_maintenance_schedule": "false",
                "parent": "",
                "phase": "requested",
                "phase_state": "open",
                "priority": "low",
                "production_system": "false",
                "reason": "",
                "reassignment_count": "0",
                "requested_by": "6816f79cc0a8016401c5a33be04be441",
                "requested_by_date": "",
                "review_comments": "",
                "review_date": "",
                "review_status": "",
                "risk": "",
                "risk_impact_analysis": "",
                "route_reason": "",
                "scope": "3",
                "service_offering": "",
                "short_description": "PROD MAMISP1 DCR (Data Change Request) -artf",
                "sla_due": "",
                "start_date": "",
                "state": "new",
                "std_change_producer_version": "",
                "sys_class_name": "change_request",
                "sys_created_by": "admin",
                "sys_created_on": "2026-02-07 16:11:22",
                "sys_domain": "global",
                "sys_domain_path": "/",
                "sys_id": "7ddf352783763210f28198c6feaad328",
                "sys_mod_count": "0",
                "sys_tags": "",
                "sys_updated_by": "admin",
                "sys_updated_on": "2026-02-07 16:11:22",
                "task_effective_number": "CHG0031036",
                "test_plan": "",
                "time_worked": "",
                "type": "normal",
                "unauthorized": "false",
                "universal_request": "",
                "upon_approval": "proceed",
                "upon_reject": "cancel",
                "urgency": "low",
                "user_input": "",
                "watch_list": "",
                "work_end": "",
                "work_notes": "",
                "work_notes_list": "",
                "work_start": ""
            }
        ],
        "warnings": [
            "Encountered unknown value  while mapping field risk.",
            "Encountered unknown value Software while mapping field category."
        ]
    }
}

TASK [Cache the CR attachment SYS_ID 2026-02-07T16:21:11Z | itsm_dcr] ***********************************************************************************************************************
ok: [192.168.1.102]

TASK [Debug the CR SYS-ID | itsm_dcr] *******************************************************************************************************************************************************
ok: [192.168.1.102] => {
    "sys_id": "7ddf352783763210f28198c6feaad328"
}

TASK [Cache the CR number 2026-02-07T16:21:11Z | itsm_dcr] **********************************************************************************************************************************
ok: [192.168.1.102]

TASK [Debug the CR number | itsm_dcr] *******************************************************************************************************************************************************
ok: [192.168.1.102] => {
    "cr_number": "CHG0031036"
}
[WARNING]: Collection community.general does not support Ansible version 2.16.3

TASK [Dump CRs and Attachments] *************************************************************************************************************************************************************
fatal: [192.168.1.102]: FAILED! => {"msg": "You need to install \"jmespath\" prior to running json_query filter"}

PLAY RECAP **********************************************************************************************************************************************************************************
192.168.1.102              : ok=8    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

[ansible_admin@ctrl ansible]$ 

Thank you, @utoddl

Looks like jmespath is there but the playbook still fails:


[root@lnx001 ~]#  yum install python3-jmespath
Last metadata expiration check: 2:16:24 ago on Sat 07 Feb 2026 09:20:07 AM EST.
Package python3-jmespath-0.9.0-11.el8.noarch is already installed.
Dependencies resolved.
Nothing to do.
Complete!
[root@lnx001 ~]#


TASK [Dump CRs and Attachments] *************************************************************************************************************************************************************
fatal: [192.168.1.102]: FAILED! => {"msg": "You need to install \"jmespath\" prior to running json_query filter"}

PLAY RECAP **********************************************************************************************************************************************************************************
192.168.1.102              : ok=8    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

I suspect jmespath is installed on the system, but not where the python that Ansible uses can get to it (venv maybe).

But don’t get distracted by that. json_query needs jmespath, but json_query is only used for convenience by the debug tasks. Skip ahead to the subelements solution. json_query is quite powerful, but not necessary to solve your problem.

3 Likes

Understood, thank you, moving on.

@utoddl we are almost there!

I must have misunderstood what you wrote. It does run and downloads , but only the first file of the three. Did I miss something? I am assuming since there is a loop and must download all three. But it is only one it downloads.

One possibility is the ServiceNow ITSM module needs an iterator for the destination file? But they all should iterate with the {{ currenttime }} VAR, even though the trailing extension is _00000001.sql

dest: "{{ runtime }}{{ scratchpad }}/DCR_{{ currenttime }}_00000001.sql"

Here is the Change Request with the three attachments.

The master playbook:

---
    - name: Oracle Immediate DCR Process ID 2872.56
      hosts: dbservers
      gather_facts: true
      vars_files:
        - vars/main.yml

      tasks:

        - name: Display Ansible date_time fact and register | itsm_dcr
          delegate_to: localhost
          run_once: true
          set_fact: 
            currenttime: "{{ ansible_date_time.iso8601 }}"
          tags: linux

        - name: Retrieve new DCR change requests | itsm_dcr
          servicenow.itsm.change_request_info:
             instance:
               host: "{{ sn_instance}}"
               username: "{{ sn_username }}"
               password:  "{{ sn_password }}"
             query:
              - state: = new
              - short_description: LIKE DCR
          register: dcr_new_cr_request_found_out
          delegate_to: localhost

        - name: Debug the ServiceNow Change Request details to get the attachment SYS_ID | itsm_dcr
          debug: var=dcr_new_cr_request_found_out  

        - name: Cache the CR attachment SYS_ID {{ ansible_date_time.iso8601 }} | itsm_dcr
          ansible.builtin.set_fact:
            sys_id: "{{ dcr_new_cr_request_found_out.records[0].sys_id }}"      

        - name: Debug the CR SYS-ID | itsm_dcr
          debug: var=sys_id   

        - name: Cache the CR number {{ ansible_date_time.iso8601 }} | itsm_dcr
          ansible.builtin.set_fact:
            cr_number: "{{ dcr_new_cr_request_found_out.records[0].number }}"

        - name: Debug the CR number | itsm_dcr
          debug: var=cr_number

        - 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 second smaller playbook with a list of tasks:

- 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

############################### download from SNOW #########################    

- name: Download the Change Request attachment | itsm_dcr
  servicenow.itsm.attachment: 
    instance:
      host: "{{ sn_instance}}"
      username: "{{ sn_username }}"
      password:  "{{ sn_password }}"
    dest: "{{ runtime }}{{ scratchpad }}/DCR_{{ currenttime }}_00000001.sql"
#    sys_id: "{{ dcr_new_cr_request_found_out.records[0].attachments[0].sys_id }}" 
    sys_id: "{{ attachment.sys_id }}" 
  loop: "{{ cr.attachments }}"
  loop_control:
    loop_var: attachment            
  register: dcr_new_cr_attachment_out  

- name: Debug the CR attachment download details | itsm_dcr
  debug: var=dcr_new_cr_attachment_out   

The output will be posted in the post below in this very thread, as it is too large to post in one reply

@utoddl continuing with the output for the post above:

[ansible_admin@ctrl ansible]$ ansible-playbook ./playbooks/dcr_several.yml 

PLAY [Oracle Immediate DCR Process ID 2872.56] *******************************************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************************************************************************************************************************************************************************************
ok: [192.168.1.102]
[WARNING]: Using run_once with the free strategy is not currently supported. This task will still be executed for every host in the inventory list.

TASK [Display Ansible date_time fact and register | itsm_dcr] ****************************************************************************************************************************************************************************************************************************
ok: [192.168.1.102 -> localhost]

TASK [Retrieve new DCR change requests | itsm_dcr] ***************************************************************************************************************************************************************************************************************************************
[WARNING]: Encountered unknown value  while mapping field risk.
[WARNING]: Encountered unknown value Software while mapping field category.
ok: [192.168.1.102 -> localhost]

TASK [Debug the ServiceNow Change Request details to get the attachment SYS_ID | itsm_dcr] ***********************************************************************************************************************************************************************************************
ok: [192.168.1.102] => {
    "dcr_new_cr_request_found_out": {
        "changed": false,
        "failed": false,
        "records": [
            {
                "active": "true",
                "activity_due": "",
                "additional_assignee_list": "",
                "approval": "approved",
                "approval_history": "",
                "approval_set": "2026-02-07 21:51:04",
                "assigned_to": "3c589a008334f210f28198c6feaad375",
                "assignment_group": "287ee6fea9fe198100ada7950d0b1b73",
                "attachments": [
                    {
                        "average_image_color": "",
                        "chunk_size_bytes": "700000",
                        "compressed": "true",
                        "content_type": "text/x-sql",
                        "download_link": "https://dev276659.service-now.com/api/now/attachment/30ad4feb83fa3210f28198c6feaad306/file",
                        "file_name": "DCR_001.sql",
                        "hash": "be2477f129a827a656c0b76392edbfa4b10568341786837b5f67ba7a25abb359",
                        "image_height": "",
                        "image_width": "",
                        "size_bytes": "141",
                        "size_compressed": "146",
                        "state": "available",
                        "sys_created_by": "admin",
                        "sys_created_on": "2026-02-07 21:50:59",
                        "sys_id": "30ad4feb83fa3210f28198c6feaad306",
                        "sys_mod_count": "1",
                        "sys_tags": "",
                        "sys_updated_by": "system",
                        "sys_updated_on": "2026-02-07 21:51:01",
                        "table_name": "change_request",
                        "table_sys_id": "1c9dcbeb83fa3210f28198c6feaad3aa"
                    },
                    {
                        "average_image_color": "",
                        "chunk_size_bytes": "700000",
                        "compressed": "true",
                        "content_type": "text/x-sql",
                        "download_link": "https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad307/file",
                        "file_name": "DCR_002.sql",
                        "hash": "495a9dfd6868afb81786f3edb5183ebbde68fe136395373d7bacabb1fa36c24a",
                        "image_height": "",
                        "image_width": "",
                        "size_bytes": "76",
                        "size_compressed": "92",
                        "state": "available",
                        "sys_created_by": "admin",
                        "sys_created_on": "2026-02-07 21:51:00",
                        "sys_id": "78ad4feb83fa3210f28198c6feaad307",
                        "sys_mod_count": "1",
                        "sys_tags": "",
                        "sys_updated_by": "system",
                        "sys_updated_on": "2026-02-07 21:51:01",
                        "table_name": "change_request",
                        "table_sys_id": "1c9dcbeb83fa3210f28198c6feaad3aa"
                    },
                    {
                        "average_image_color": "",
                        "chunk_size_bytes": "700000",
                        "compressed": "true",
                        "content_type": "text/x-sql",
                        "download_link": "https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad308/file",
                        "file_name": "DCR_003.sql",
                        "hash": "468948ef7571706b68865cb9617fa979decc5664d30353742f03c024c0e6f3c5",
                        "image_height": "",
                        "image_width": "",
                        "size_bytes": "148",
                        "size_compressed": "141",
                        "state": "available",
                        "sys_created_by": "admin",
                        "sys_created_on": "2026-02-07 21:51:00",
                        "sys_id": "78ad4feb83fa3210f28198c6feaad308",
                        "sys_mod_count": "1",
                        "sys_tags": "",
                        "sys_updated_by": "system",
                        "sys_updated_on": "2026-02-07 21:51:01",
                        "table_name": "change_request",
                        "table_sys_id": "1c9dcbeb83fa3210f28198c6feaad3aa"
                    },
                    {
                        "average_image_color": "",
                        "chunk_size_bytes": "700000",
                        "compressed": "true",
                        "content_type": "text/x-sql",
                        "download_link": "https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad309/file",
                        "file_name": "DCR_004_controlled_failure.sql",
                        "hash": "5d48a20d5bd0003a1d3bad56aa43127b33b4274f55978e6404aeb1b49d602aa1",
                        "image_height": "",
                        "image_width": "",
                        "size_bytes": "264",
                        "size_compressed": "198",
                        "state": "available",
                        "sys_created_by": "admin",
                        "sys_created_on": "2026-02-07 21:51:00",
                        "sys_id": "78ad4feb83fa3210f28198c6feaad309",
                        "sys_mod_count": "1",
                        "sys_tags": "",
                        "sys_updated_by": "system",
                        "sys_updated_on": "2026-02-07 21:51:01",
                        "table_name": "change_request",
                        "table_sys_id": "1c9dcbeb83fa3210f28198c6feaad3aa"
                    }
                ],
                "backout_plan": "",
                "business_duration": "",
                "business_service": "281a4d5fc0a8000b00e4ba489a83eedc",
                "cab_date_time": "",
                "cab_delegate": "",
                "cab_recommendation": "",
                "cab_required": "false",
                "calendar_duration": "",
                "category": "Software",
                "change_plan": "",
                "chg_model": "007c4001c343101035ae3f52c1d3aeb2",
                "close_code": "",
                "close_notes": "",
                "closed_at": "",
                "closed_by": "",
                "cmdb_ci": "0c43d5e2c61122750182c132a8b9e2d9",
                "comments": "",
                "comments_and_work_notes": "",
                "company": "",
                "conflict_last_run": "",
                "conflict_status": "Not Run",
                "contact_type": "",
                "contract": "",
                "copied_from": "",
                "correlation_display": "",
                "correlation_id": "",
                "delivery_plan": "",
                "delivery_task": "",
                "description": "--- Managed by MMIS DBA hyperautomation. Do not change manually. Do not deviate. ---\r\n--- Attach *.sql script(s) to this DCR to be run in MAMISP1 immediately. ---\r\n--- If these need to be run on a schedule, enter the desired \"Planned Start\" and \"End\" date.---\r\n--- Comments to mmis_dba_automation@mass.gov ---\r\n--",
                "due_date": "",
                "end_date": "",
                "escalation": "0",
                "expected_start": "",
                "follow_up": "",
                "group_list": "",
                "impact": "low",
                "implementation_plan": "",
                "justification": "",
                "knowledge": "false",
                "location": "",
                "made_sla": "true",
                "number": "CHG0031038",
                "on_hold": false,
                "on_hold_reason": "",
                "on_hold_task": "",
                "opened_at": "2026-02-07 21:50:41",
                "opened_by": "6816f79cc0a8016401c5a33be04be441",
                "order": "",
                "outside_maintenance_schedule": "false",
                "parent": "",
                "phase": "requested",
                "phase_state": "open",
                "priority": "low",
                "production_system": "false",
                "reason": "",
                "reassignment_count": "0",
                "requested_by": "6816f79cc0a8016401c5a33be04be441",
                "requested_by_date": "",
                "review_comments": "",
                "review_date": "",
                "review_status": "",
                "risk": "",
                "risk_impact_analysis": "",
                "route_reason": "",
                "scope": "3",
                "service_offering": "",
                "short_description": "PROD MAMISP1 DCR (Data Change Request) -artf",
                "sla_due": "",
                "start_date": "",
                "state": "new",
                "std_change_producer_version": "",
                "sys_class_name": "change_request",
                "sys_created_by": "admin",
                "sys_created_on": "2026-02-07 21:51:04",
                "sys_domain": "global",
                "sys_domain_path": "/",
                "sys_id": "1c9dcbeb83fa3210f28198c6feaad3aa",
                "sys_mod_count": "0",
                "sys_tags": "",
                "sys_updated_by": "admin",
                "sys_updated_on": "2026-02-07 21:51:04",
                "task_effective_number": "CHG0031038",
                "test_plan": "",
                "time_worked": "",
                "type": "normal",
                "unauthorized": "false",
                "universal_request": "",
                "upon_approval": "proceed",
                "upon_reject": "cancel",
                "urgency": "low",
                "user_input": "",
                "watch_list": "",
                "work_end": "",
                "work_notes": "",
                "work_notes_list": "",
                "work_start": ""
            }
        ],
        "warnings": [
            "Encountered unknown value  while mapping field risk.",
            "Encountered unknown value Software while mapping field category."
        ]
    }
}

TASK [Cache the CR attachment SYS_ID 2026-02-07T22:08:13Z | itsm_dcr] ********************************************************************************************************************************************************************************************************************
ok: [192.168.1.102]

TASK [Debug the CR SYS-ID | itsm_dcr] ****************************************************************************************************************************************************************************************************************************************************
ok: [192.168.1.102] => {
    "sys_id": "1c9dcbeb83fa3210f28198c6feaad3aa"
}

TASK [Cache the CR number 2026-02-07T22:08:13Z | itsm_dcr] *******************************************************************************************************************************************************************************************************************************
ok: [192.168.1.102]

TASK [Debug the CR number | itsm_dcr] ****************************************************************************************************************************************************************************************************************************************************
ok: [192.168.1.102] => {
    "cr_number": "CHG0031038"
}

TASK [Handle each CR] ********************************************************************************************************************************************************************************************************************************************************************
TASK [Handle CR attachments] *************************************************************************************************************************************************************************************************************************************************************
ok: [192.168.1.102] => (item={'size_bytes': '141', 'file_name': 'DCR_001.sql', 'sys_mod_count': '1', 'average_image_color': '', 'image_width': '', 'sys_updated_on': '2026-02-07 21:51:01', 'sys_tags': '', 'table_name': 'change_request', 'sys_id': '30ad4feb83fa3210f28198c6feaad306', 'image_height': '', 'sys_updated_by': 'system', 'download_link': 'https://dev276659.service-now.com/api/now/attachment/30ad4feb83fa3210f28198c6feaad306/file', 'content_type': 'text/x-sql', 'sys_created_on': '2026-02-07 21:50:59', 'size_compressed': '146', 'compressed': 'true', 'state': 'available', 'table_sys_id': '1c9dcbeb83fa3210f28198c6feaad3aa', 'chunk_size_bytes': '700000', 'hash': 'be2477f129a827a656c0b76392edbfa4b10568341786837b5f67ba7a25abb359', 'sys_created_by': 'admin'}) => {
    "msg": "handling CR 1c9dcbeb83fa3210f28198c6feaad3aa, Attachment 30ad4feb83fa3210f28198c6feaad306."
}
ok: [192.168.1.102] => (item={'size_bytes': '76', 'file_name': 'DCR_002.sql', 'sys_mod_count': '1', 'average_image_color': '', 'image_width': '', 'sys_updated_on': '2026-02-07 21:51:01', 'sys_tags': '', 'table_name': 'change_request', 'sys_id': '78ad4feb83fa3210f28198c6feaad307', 'image_height': '', 'sys_updated_by': 'system', 'download_link': 'https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad307/file', 'content_type': 'text/x-sql', 'sys_created_on': '2026-02-07 21:51:00', 'size_compressed': '92', 'compressed': 'true', 'state': 'available', 'table_sys_id': '1c9dcbeb83fa3210f28198c6feaad3aa', 'chunk_size_bytes': '700000', 'hash': '495a9dfd6868afb81786f3edb5183ebbde68fe136395373d7bacabb1fa36c24a', 'sys_created_by': 'admin'}) => {
    "msg": "handling CR 1c9dcbeb83fa3210f28198c6feaad3aa, Attachment 78ad4feb83fa3210f28198c6feaad307."
}
ok: [192.168.1.102] => (item={'size_bytes': '148', 'file_name': 'DCR_003.sql', 'sys_mod_count': '1', 'average_image_color': '', 'image_width': '', 'sys_updated_on': '2026-02-07 21:51:01', 'sys_tags': '', 'table_name': 'change_request', 'sys_id': '78ad4feb83fa3210f28198c6feaad308', 'image_height': '', 'sys_updated_by': 'system', 'download_link': 'https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad308/file', 'content_type': 'text/x-sql', 'sys_created_on': '2026-02-07 21:51:00', 'size_compressed': '141', 'compressed': 'true', 'state': 'available', 'table_sys_id': '1c9dcbeb83fa3210f28198c6feaad3aa', 'chunk_size_bytes': '700000', 'hash': '468948ef7571706b68865cb9617fa979decc5664d30353742f03c024c0e6f3c5', 'sys_created_by': 'admin'}) => {
    "msg": "handling CR 1c9dcbeb83fa3210f28198c6feaad3aa, Attachment 78ad4feb83fa3210f28198c6feaad308."
}
ok: [192.168.1.102] => (item={'size_bytes': '264', 'file_name': 'DCR_004_controlled_failure.sql', 'sys_mod_count': '1', 'average_image_color': '', 'image_width': '', 'sys_updated_on': '2026-02-07 21:51:01', 'sys_tags': '', 'table_name': 'change_request', 'sys_id': '78ad4feb83fa3210f28198c6feaad309', 'image_height': '', 'sys_updated_by': 'system', 'download_link': 'https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad309/file', 'content_type': 'text/x-sql', 'sys_created_on': '2026-02-07 21:51:00', 'size_compressed': '198', 'compressed': 'true', 'state': 'available', 'table_sys_id': '1c9dcbeb83fa3210f28198c6feaad3aa', 'chunk_size_bytes': '700000', 'hash': '5d48a20d5bd0003a1d3bad56aa43127b33b4274f55978e6404aeb1b49d602aa1', 'sys_created_by': 'admin'}) => {
    "msg": "handling CR 1c9dcbeb83fa3210f28198c6feaad3aa, Attachment 78ad4feb83fa3210f28198c6feaad309."
}

TASK [Download the Change Request attachment | itsm_dcr] *********************************************************************************************************************************************************************************************************************************
changed: [192.168.1.102] => (item={'size_bytes': '141', 'file_name': 'DCR_001.sql', 'sys_mod_count': '1', 'average_image_color': '', 'image_width': '', 'sys_updated_on': '2026-02-07 21:51:01', 'sys_tags': '', 'table_name': 'change_request', 'sys_id': '30ad4feb83fa3210f28198c6feaad306', 'image_height': '', 'sys_updated_by': 'system', 'download_link': 'https://dev276659.service-now.com/api/now/attachment/30ad4feb83fa3210f28198c6feaad306/file', 'content_type': 'text/x-sql', 'sys_created_on': '2026-02-07 21:50:59', 'size_compressed': '146', 'compressed': 'true', 'state': 'available', 'table_sys_id': '1c9dcbeb83fa3210f28198c6feaad3aa', 'chunk_size_bytes': '700000', 'hash': 'be2477f129a827a656c0b76392edbfa4b10568341786837b5f67ba7a25abb359', 'sys_created_by': 'admin'})
changed: [192.168.1.102] => (item={'size_bytes': '76', 'file_name': 'DCR_002.sql', 'sys_mod_count': '1', 'average_image_color': '', 'image_width': '', 'sys_updated_on': '2026-02-07 21:51:01', 'sys_tags': '', 'table_name': 'change_request', 'sys_id': '78ad4feb83fa3210f28198c6feaad307', 'image_height': '', 'sys_updated_by': 'system', 'download_link': 'https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad307/file', 'content_type': 'text/x-sql', 'sys_created_on': '2026-02-07 21:51:00', 'size_compressed': '92', 'compressed': 'true', 'state': 'available', 'table_sys_id': '1c9dcbeb83fa3210f28198c6feaad3aa', 'chunk_size_bytes': '700000', 'hash': '495a9dfd6868afb81786f3edb5183ebbde68fe136395373d7bacabb1fa36c24a', 'sys_created_by': 'admin'})
changed: [192.168.1.102] => (item={'size_bytes': '148', 'file_name': 'DCR_003.sql', 'sys_mod_count': '1', 'average_image_color': '', 'image_width': '', 'sys_updated_on': '2026-02-07 21:51:01', 'sys_tags': '', 'table_name': 'change_request', 'sys_id': '78ad4feb83fa3210f28198c6feaad308', 'image_height': '', 'sys_updated_by': 'system', 'download_link': 'https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad308/file', 'content_type': 'text/x-sql', 'sys_created_on': '2026-02-07 21:51:00', 'size_compressed': '141', 'compressed': 'true', 'state': 'available', 'table_sys_id': '1c9dcbeb83fa3210f28198c6feaad3aa', 'chunk_size_bytes': '700000', 'hash': '468948ef7571706b68865cb9617fa979decc5664d30353742f03c024c0e6f3c5', 'sys_created_by': 'admin'})
changed: [192.168.1.102] => (item={'size_bytes': '264', 'file_name': 'DCR_004_controlled_failure.sql', 'sys_mod_count': '1', 'average_image_color': '', 'image_width': '', 'sys_updated_on': '2026-02-07 21:51:01', 'sys_tags': '', 'table_name': 'change_request', 'sys_id': '78ad4feb83fa3210f28198c6feaad309', 'image_height': '', 'sys_updated_by': 'system', 'download_link': 'https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad309/file', 'content_type': 'text/x-sql', 'sys_created_on': '2026-02-07 21:51:00', 'size_compressed': '198', 'compressed': 'true', 'state': 'available', 'table_sys_id': '1c9dcbeb83fa3210f28198c6feaad3aa', 'chunk_size_bytes': '700000', 'hash': '5d48a20d5bd0003a1d3bad56aa43127b33b4274f55978e6404aeb1b49d602aa1', 'sys_created_by': 'admin'})

TASK [Debug the CR attachment download details | itsm_dcr] *******************************************************************************************************************************************************************************************************************************
ok: [192.168.1.102] => {
    "dcr_new_cr_attachment_out": {
        "changed": true,
        "msg": "All items completed",
        "results": [
            {
                "ansible_loop_var": "attachment",
                "attachment": {
                    "average_image_color": "",
                    "chunk_size_bytes": "700000",
                    "compressed": "true",
                    "content_type": "text/x-sql",
                    "download_link": "https://dev276659.service-now.com/api/now/attachment/30ad4feb83fa3210f28198c6feaad306/file",
                    "file_name": "DCR_001.sql",
                    "hash": "be2477f129a827a656c0b76392edbfa4b10568341786837b5f67ba7a25abb359",
                    "image_height": "",
                    "image_width": "",
                    "size_bytes": "141",
                    "size_compressed": "146",
                    "state": "available",
                    "sys_created_by": "admin",
                    "sys_created_on": "2026-02-07 21:50:59",
                    "sys_id": "30ad4feb83fa3210f28198c6feaad306",
                    "sys_mod_count": "1",
                    "sys_tags": "",
                    "sys_updated_by": "system",
                    "sys_updated_on": "2026-02-07 21:51:01",
                    "table_name": "change_request",
                    "table_sys_id": "1c9dcbeb83fa3210f28198c6feaad3aa"
                },
                "changed": true,
                "failed": false,
                "invocation": {
                    "module_args": {
                        "dest": "/runtime/dcr/DCR_2026-02-07T22:08:13Z_00000001.sql",
                        "instance": {
                            "access_token": null,
                            "api_key": null,
                            "api_path": "api/now",
                            "client_certificate_file": null,
                            "client_id": null,
                            "client_key_file": null,
                            "client_secret": null,
                            "custom_headers": null,
                            "grant_type": null,
                            "host": "https://dev276659.service-now.com",
                            "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                            "refresh_token": null,
                            "timeout": 10.0,
                            "username": "admin",
                            "validate_certs": true
                        },
                        "sys_id": "30ad4feb83fa3210f28198c6feaad306"
                    }
                },
                "record": {
                    "elapsed": 0.17,
                    "msg": "OK",
                    "size": 141,
                    "status_code": 200
                }
            },
            {
                "ansible_loop_var": "attachment",
                "attachment": {
                    "average_image_color": "",
                    "chunk_size_bytes": "700000",
                    "compressed": "true",
                    "content_type": "text/x-sql",
                    "download_link": "https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad307/file",
                    "file_name": "DCR_002.sql",
                    "hash": "495a9dfd6868afb81786f3edb5183ebbde68fe136395373d7bacabb1fa36c24a",
                    "image_height": "",
                    "image_width": "",
                    "size_bytes": "76",
                    "size_compressed": "92",
                    "state": "available",
                    "sys_created_by": "admin",
                    "sys_created_on": "2026-02-07 21:51:00",
                    "sys_id": "78ad4feb83fa3210f28198c6feaad307",
                    "sys_mod_count": "1",
                    "sys_tags": "",
                    "sys_updated_by": "system",
                    "sys_updated_on": "2026-02-07 21:51:01",
                    "table_name": "change_request",
                    "table_sys_id": "1c9dcbeb83fa3210f28198c6feaad3aa"
                },
                "changed": true,
                "failed": false,
                "invocation": {
                    "module_args": {
                        "dest": "/runtime/dcr/DCR_2026-02-07T22:08:13Z_00000001.sql",
                        "instance": {
                            "access_token": null,
                            "api_key": null,
                            "api_path": "api/now",
                            "client_certificate_file": null,
                            "client_id": null,
                            "client_key_file": null,
                            "client_secret": null,
                            "custom_headers": null,
                            "grant_type": null,
                            "host": "https://dev276659.service-now.com",
                            "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                            "refresh_token": null,
                            "timeout": 10.0,
                            "username": "admin",
                            "validate_certs": true
                        },
                        "sys_id": "78ad4feb83fa3210f28198c6feaad307"
                    }
                },
                "record": {
                    "elapsed": 0.19,
                    "msg": "OK",
                    "size": 76,
                    "status_code": 200
                }
            },
            {
                "ansible_loop_var": "attachment",
                "attachment": {
                    "average_image_color": "",
                    "chunk_size_bytes": "700000",
                    "compressed": "true",
                    "content_type": "text/x-sql",
                    "download_link": "https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad308/file",
                    "file_name": "DCR_003.sql",
                    "hash": "468948ef7571706b68865cb9617fa979decc5664d30353742f03c024c0e6f3c5",
                    "image_height": "",
                    "image_width": "",
                    "size_bytes": "148",
                    "size_compressed": "141",
                    "state": "available",
                    "sys_created_by": "admin",
                    "sys_created_on": "2026-02-07 21:51:00",
                    "sys_id": "78ad4feb83fa3210f28198c6feaad308",
                    "sys_mod_count": "1",
                    "sys_tags": "",
                    "sys_updated_by": "system",
                    "sys_updated_on": "2026-02-07 21:51:01",
                    "table_name": "change_request",
                    "table_sys_id": "1c9dcbeb83fa3210f28198c6feaad3aa"
                },
                "changed": true,
                "failed": false,
                "invocation": {
                    "module_args": {
                        "dest": "/runtime/dcr/DCR_2026-02-07T22:08:13Z_00000001.sql",
                        "instance": {
                            "access_token": null,
                            "api_key": null,
                            "api_path": "api/now",
                            "client_certificate_file": null,
                            "client_id": null,
                            "client_key_file": null,
                            "client_secret": null,
                            "custom_headers": null,
                            "grant_type": null,
                            "host": "https://dev276659.service-now.com",
                            "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                            "refresh_token": null,
                            "timeout": 10.0,
                            "username": "admin",
                            "validate_certs": true
                        },
                        "sys_id": "78ad4feb83fa3210f28198c6feaad308"
                    }
                },
                "record": {
                    "elapsed": 0.18,
                    "msg": "OK",
                    "size": 148,
                    "status_code": 200
                }
            },
            {
                "ansible_loop_var": "attachment",
                "attachment": {
                    "average_image_color": "",
                    "chunk_size_bytes": "700000",
                    "compressed": "true",
                    "content_type": "text/x-sql",
                    "download_link": "https://dev276659.service-now.com/api/now/attachment/78ad4feb83fa3210f28198c6feaad309/file",
                    "file_name": "DCR_004_controlled_failure.sql",
                    "hash": "5d48a20d5bd0003a1d3bad56aa43127b33b4274f55978e6404aeb1b49d602aa1",
                    "image_height": "",
                    "image_width": "",
                    "size_bytes": "264",
                    "size_compressed": "198",
                    "state": "available",
                    "sys_created_by": "admin",
                    "sys_created_on": "2026-02-07 21:51:00",
                    "sys_id": "78ad4feb83fa3210f28198c6feaad309",
                    "sys_mod_count": "1",
                    "sys_tags": "",
                    "sys_updated_by": "system",
                    "sys_updated_on": "2026-02-07 21:51:01",
                    "table_name": "change_request",
                    "table_sys_id": "1c9dcbeb83fa3210f28198c6feaad3aa"
                },
                "changed": true,
                "failed": false,
                "invocation": {
                    "module_args": {
                        "dest": "/runtime/dcr/DCR_2026-02-07T22:08:13Z_00000001.sql",
                        "instance": {
                            "access_token": null,
                            "api_key": null,
                            "api_path": "api/now",
                            "client_certificate_file": null,
                            "client_id": null,
                            "client_key_file": null,
                            "client_secret": null,
                            "custom_headers": null,
                            "grant_type": null,
                            "host": "https://dev276659.service-now.com",
                            "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                            "refresh_token": null,
                            "timeout": 10.0,
                            "username": "admin",
                            "validate_certs": true
                        },
                        "sys_id": "78ad4feb83fa3210f28198c6feaad309"
                    }
                },
                "record": {
                    "elapsed": 0.18,
                    "msg": "OK",
                    "size": 264,
                    "status_code": 200
                }
            }
        ],
        "skipped": false
    }
}

PLAY RECAP *******************************************************************************************************************************************************************************************************************************************************************************
192.168.1.102              : ok=12   changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[ansible_admin@ctrl ansible]$ 

Thank you for your continuing support, @utoddl

It looks like it downloaded all the attachments, but you set dest identically on all of them. That is:

dest: "{{ runtime }}{{ scratchpad }}/DCR_{{ currenttime }}_00000001.sql"

which resolved to /runtime/dcr/DCR_2026-02-07T22:08:13Z_00000001.sql. If you download them all to the same file name, the last one will be the only one remaining when the job ends.

I don’t know what sets the currenttime variable, but it doesn’t change during the lifetime of that task. I’d recommend using extended: true loop control so you can use ansible_loop.index in the dest: to ensure each dest is unique. Like so:

- name: Download the Change Request attachment | itsm_dcr
  servicenow.itsm.attachment:
    instance:
      host: "{{ sn_instance}}"
      username: "{{ sn_username }}"
      password:  "{{ sn_password }}"
    dest: "{{ runtime }}{{ scratchpad }}/DCR_{{ ansible_loop.index }}_00000001.sql"
    sys_id: "{{ attachment.sys_id }}"
  loop: "{{ cr.attachments }}"
  loop_control:
    extended: true
    loop_var: attachment           
  register: dcr_new_cr_attachment_out

You can read about this and other Extended loop variables.

1 Like


wowza!

1 Like

@utoddl I cannot thank you enough, kind sir. Not just for providing the elegant and short solution, but also for a few other things. Chief among those is “include_tasks”. Let me explain. I have posted a question in this forum a few months ago. The question was how to include multiple playbooks references in different places inside a master one. The great folks here told me “no, cant be done”. I took it as the final word and never thought of it twice. It wasnt that I was deceived on purpose. After all, my question was about including entire playbooks, not tasks. But this “include_tasks” gives me that extra control. Thank you for that as well. Plus the timeliness of your answers.
Now, I have to re-write the playbooks so the multiple downloaded .SQL scripts get the same individual looping treatment you showed me in the download module.
Thank you so very much!
Nestor Kandinsky-Clerambeau. :+1:

@utoddl I didnt have to change a thing for the rest of the playbook. it runs the entire Data Change Request ServiceNow process perfectly. Wow.

1 Like