如何使用 Ansible URI 模块格式化长 POST 正文字符串?

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

作为我正在整理的 Ansible 剧本的一部分,我需要发出很多 POST 请求。我正在使用 uri 模块,需要使用 key/value 对以 x-www-form-urlencoded 格式发送数据,如下面的示例 Ansible 文档所示:

- 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

我的问题是我的正文字符串很长,有些有 20 多个参数作为一个大 运行-在线。我希望能够将参数指定为列表,例如:

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

并以相同的格式自动发送结果(x-www-form-urlencoded,而不是 JSON)。有没有简单的方法可以做到这一点?

谢谢!

在 YAML 中,您可以使用换行符和反斜杠在双引号字符串中忽略它们:

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

通常情况下,换行符会变成空格,但反斜杠会阻止这种情况,并且这些行会在没有空格的情况下连接在一起。

编辑: 另一种方法是在使用 jinja2 过滤器之前存储一个变量:

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