使用带有 gitlab 的 Ansibles URI 模块的 HTTP 错误 400 api

HTTP Error 400 using Ansibles URI Module with gitlab api

我正在尝试使用 ansibles uri module 提交到 git 实验室项目 和 gitlab api.

最终目标是将 JSON 移动到一个模板中,并将来自多台机器的信息提交到 gitlab 项目中的不同文件。

但现在我无法正确使用 uri 模块。

我能够使用 gitlab api 并在 ansible linux 框上卷曲。

PAYLOAD=$(cat << 'JSON'
{
  "branch": "master",
  "commit_message": "some commit message",
  "actions": [
    {
      "action": "create",
      "file_path": "Leer/test",
      "content": "some content"
    }
]
}
JSON
)
curl --request POST --header "PRIVATE-TOKEN: xxxxxxxxxxxxxxxx" --header "Content-Type: application/json" --data "$PAYLOAD" http://gitlab/api/v4/projects/2/repository/commits

并将其翻译成以下ansible角色git-commit:

- name: commit to gitlab
  uri:
    url: http://gitlab/api/v4/projects/2/repository/commits
    method: POST
    body_format: json
    headers:
      PRIVATE-TOKEN: "xxxxxxxxxxxxxxxx"
    body: |
      '{
        "branch": "master",
        "commit_message": "some ansible commit message",
        "actions": [
         {
           "action": "create",
           "file_path": "Leer/test2",
           "content": "some new content"
         }
        ]
      }'

使用了 Playbook 中的角色 git.yml:

---
- hosts: 10.101.127.116
  connection: local
  gather_facts: no
  become: true
  roles:
  - git-commit

和运行剧本:

ansible-playbook -k git.yml

但我收到以下 http 错误 400:

fatal: [10.101.127.116]: FAILED! => 
{
"changed": false,
"connection": "close",
"content": "", 
"content_length": "0", 
"content_type": "text/html; charset=utf-8", "date": 
"Thu, 18 Apr 2019 13:11:13 GMT", 
"msg": "Status code was 400 and not [200]: HTTP Error 400: Bad Request", "redirected": false, 
"server": "nginx", 
"status": 400, 
"url": "http://gitlab/api/v4/projects/2/repository/commits", 
"x_request_id": "WNfjPOBkVk5", "x_runtime": "0.002530"
}

感谢任何形式的帮助

您错误地使用了 YAML 引用:

   body: |
      '{

意味着 body 字面上是单引号字符,然后是一个左括号,因为 yaml | 字符本身就是一个引号结构。

您可以删除两个单引号(单引号字符在 JSON 中不合法),或者您可以删除竖线,然后将单引号向上移动到 body:等级

您可能会发现使用 YAML 到 JSON 的转换工具有助于查看文档的外观;网上有几个,remarshal在你的电脑上运行