【问题标题】:Ansible URI module post form-urlencoded JSON dataAnsible URI 模块发布表单 urlencoded JSON 数据
【发布时间】:2021-01-22 15:16:33
【问题描述】:

我正在尝试使用 ansible URI 模块访问 API。如果我设置tasks[0].uri.body.json_data: <literal string> 它可以工作,但是,当我尝试将变量注入tasks[0].uri.body.json_data: <string with variable value injected> 时,它会显示以下错误 json format error.

我只是想知道在这种情况下如何注入变量值。

提前谢谢你。

下面的示例代码

$ 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

【问题讨论】:

    标签: json ansible jinja2


    【解决方案1】:

    在 YAML 中创建数据然后过滤 to_json 更容易。例如

    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 }}"
    

    给予

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-09
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多