Search code examples
ansiblejinja2urimicrosoft-teamswebhooks

Escape backslash in Ansible while posting json to teams webhook using uri module


I have a file called test.log where it contains a structure like below:

{"Check something" : "Pass" , "Result" : "Found something -

Name Path test C:\Windows\system32\xyz"}

While reading the file using lookup, the backslash is already escaped(\).

{"Check something" : "Pass" , "Result" : "Found something -

Name Path test C:\\Windows\\system32\\xyz"}

But when it is used to post this structure to teams using URI module, backslash is not being escaped and it is causing a bad payload format while posting and fails. How to escape backslash and post the structure to teams.

- uri:
    url: "{{webhook_url}}"
    method: POST
    body: "{'title': '{{title}}', 'text': '{{lookup(\"file\",\"{{filepath}}\") | replace (\"\'\",\"\\\'\") | replace (\"\\n\",\"   \\n\")}}'}"
    body_format: json

Error received in uri module is "content": "Bad payload received by generic incoming webhook"

Also, the backslash issue happens only when I use the replace function after reading the file. If I'm not using replace then the backslash is automatically escaped and doesn't cause any issues.


Solution

  • I would try this:

    - uri:
        url: "{{webhook_url}}"
        method: POST
        body: "{{ { 'title': title , 'text': text } | to_json }}"
        body_format: json
      vars:
        text: "{{lookup('file', filepath) }}"
    

    It's easier to use a vars block than to embed all that stuff.