0

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!

tinita
  • 3,987
  • 1
  • 21
  • 23
MichaelC
  • 15
  • 1
  • 8
  • You can write the body as JSON. See `body_format` in http://docs.ansible.com/ansible/latest/uri_module.html – tinita Jan 26 '18 at 19:34
  • The problem with that seems to be that the server will not accept a JSON formatted body in the POST. It requires the body is formatted as x-www-form-urlencoded. – MichaelC Jan 26 '18 at 21:11
  • Oh I see, I misunderstood the documentation, sorry – tinita Jan 26 '18 at 21:47
  • **See also:** YAML folded string https://stackoverflow.com/questions/3790454/in-yaml-how-do-i-break-a-string-over-multiple-lines – dreftymac Oct 26 '18 at 17:06

2 Answers2

1

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('&') }}"
tinita
  • 3,987
  • 1
  • 21
  • 23
1

You can use the form-urlencoded body format to avoid having to set the content type and encode the body by yourself.

- uri:
    url: https://your.form.based.auth.example.com/index.php
    method: POST
    body_format: form-urlencoded
    body: 
      name: your_username
      password: your_password
      enter: SignIn
    status_code: 302
  register: login
Nuno André
  • 4,739
  • 1
  • 33
  • 46