Ansible URI Module and ServiceNow Attachment API

215 Views Asked by At

I have used Ansible with URI module to attach a PDF or CSV file to an existing incident and it gets attached with no issues.

But when I try to download the same attachment, either the CSV is garbled or encrypted or PDF says, cannot be loaded. Please see the code and the error below.

Ansible code to upload a CSV or PDF file

            - name: "Attach output CSV file to incident"
              ansible.builtin.uri:
                      url: "{{ SN_HOST }}api/now/attachment/upload" 
                      user: "{{ SN_USERNAME }}"
                      password: "{{ SN_PASSWORD }}"
                      method: POST
                      return_content: true
                      validate_certs: false
                      force_basic_auth: no
                      status_code: 201
                      body_format: form-multipart
                      headers:
                          Accept: 'application/json'
                          Content-Type: 'multipart/form-data'
                      body:
                        table_name:
                            content: incident
                        table_sys_id:
                            content: 'c6957640470388444c736d4315'
                        uploadFile:
                            filename: "../../win_playbooks/reports/User_Manual.pdf"
              register: attach_file

Error when trying to open the attached PDF file

enter image description here

Error when trying to open the downloaded attached CSV file

enter image description here

When I use the ServiceNow REST API explorer or the ServiceNow UI manually to upload and download the attached PDF or CSV file, it works perfectly. I guess the issue is that, when I try to upload the PDF or CSV from the above mentioned Ansible code, it is not working.

1

There are 1 best solutions below

0
On

As a temporary fix, I directly used curl command inside an Ansible task which does not encode any file when attached to a ServiceNow Incident Record.

I believe the behavior of the Ansible uri module which when used with body_format: form-multipart will auto encode with base64 (charset=UTF-8) and at present, it seems there is no way to bypass encoding with this body format.

body_format, "The serialization format of the body. When set to json, form-multipart, or form-urlencoded, encodes the body argument, if needed ..."

So curl is the only option for now.