Ansible URI module post form-urlencoded JSON data

Viewed 1908

I am trying to access an API using ansible URI module. If I set tasks[0].uri.body.json_data: <literal string> it works, however, when I'm trying to inject variable into tasks[0].uri.body.json_data: <string with variable value injected>, it displays the following error json format error.

I'm just wondering how to inject the variable value in this case.

Thank you in advance.

Example code below

$ ansible-playbook test.yaml --extra-var id=1
---
# test.yaml
- name: Get person
  hosts: localhost
  vars:
    person_id: '{{ id }}'
  tasks:
  - name: Get person based on ID
    uri:
      url: https://example.com/api
      method: POST
      body_format: form-urlencoded
      validate_certs: no
      # return_content: yes
      body:
        auth_user: test
        auth_pwd: test
        json_data: '{"operation": "core/get", "class": "Person", "key": "{{person_id}}", "output_fields": "*"}' # NOT working (replaced "key": "1" with "key": "{{person_id}}")
        # json_data: '{"operation": "core/get", "class": "Person", "key": "1", "output_fields": "*"}' # WORKING
    register: login
  - debug:
      var: person_id
  - debug:
      var: login.json
1 Answers

It's easier to create the data in YAML and then filter to_json. For example

shell> cat pb.yml
- hosts: localhost
  vars:
    person_id: "{{ id }}"
    json_data:
      operation: "core/get"
      class: "Person"
      key: "{{ person_id }}"
      output_fields: "*"
  tasks:
    - debug:
        msg: "{{ json_data|to_json }}"

gives

shell> ansible-playbook pb.yml --extra-var id=1
  ...
  msg: '{"operation": "core/get", "class": "Person", "key": "1", "output_fields": "*"}'
Related