在Ansible中处理来自REST调用的JSON

时间:2018-09-30 12:06:45

标签: json rest ansible

我正在调用REST API,并尝试重新组合返回的JSON的选定字段以将其用于PUT请求,但是由于我缺乏使用ansible和python的经验而失败了...

---
- hosts: localhost

  tasks:
    - uri:
        url: "https://test.com/info?comp=COMP1"
        return_content: yes
      register: response1

    - debug:
        msg: "{{ response1.json | to_nice_json }}"

    - set_fact:
        modified_properties: " " # json_query 'magic' ??
    # loop or with_items 'magic' ??

    - uri:
        method: PUT
        url: "https://test.com/put"
        body_format: json
        body: '{"properties": "{{modified_properties}}" }'

response1.json如下:

{
    "id": "1", 
    "role": {
        "id": "2", 
        "props": [
            {
                "id": "1", 
                "name": "TestName1", 
                "value": "TestVal1"
            }, 
            {
                "id": "2", 
                "name": "TestName2", 
                "value": "TestVal2"
            }, 
            {
                "id": "3", 
                "name": "TestName3", 
                "value": "TestVal3"
            }
        ], 
        "type": "some_type"
    }, 
    "user": "testuser"
}

modified_properties对于PUT请求必须像这样:

{"TestName1":"TestVal1","TestName2":"TestVal2","TestName3":"TestVal3"}

我尝试了以下操作:

    - set_fact:
        modified_properties: '"{{item.name}}": "{{item.value}}"'
      with_list: "{{ response1.json.role.props }}

但这只会将最后一对保存在modified_properties中:

"TestName3": "TestVal3"

我试图将set_fact扩展为combineunion,但不知道如何...

任何帮助表示赞赏!谢谢!

0 个答案:

没有答案