Search code examples
ansibleyamluriansible-2.x

How to format long POST body string with Ansible URI Module?


I need to issue a lot of POST requests as part of the Ansible playbook I'm putting together. I'm using the uri module and need to send the data in the x-www-form-urlencoded format with the key/value pairs as shown from the example Ansible documentation below:

- uri:
    url: https://your.form.based.auth.example.com/index.php
    method: POST
    body: "name=your_username&password=your_password&enter=Sign%20in"
    status_code: 302
    headers:
      Content-Type: "application/x-www-form-urlencoded"
  register: login

My problem is that my body strings are very long, some with 20+ parameters as one large run-on line. I'd like to be able to specify the parameters as a list such as:

body: 
  name: your_username
  password: your_password
  enter: SignIn
  ...

And have the result automatically sent in the same format (x-www-form-urlencoded, not JSON). Is there an easy way to do this?

Thanks!


Solution

  • In YAML, you can use newlines and backslashes to ignore them in a doublequoted string:

    body: "param1=value1&\
      param2=value2&\
      param3=value3"
    

    Normally, the newlines will be turned into spaces, but the backslash prevents that, and the lines will be joined together without spaces.

    Edit: Another way would be to store a variable before and than use a jinja2 filter:

    vars:
      query:
        - param1=value1
        - param2=value2
        - param3=value3
    ...
      body: "{{ query | join('&') }}"