Ansible:从JSON获取特定值

时间:2019-07-24 11:56:24

标签: json ansible

我正在获取Ansible JSON格式的输出,需要从中获取请求ID,请帮忙

ok: [localhost] => {
    "op.content": {
        "_links": {
           "self": [
               {
                   "href": "url123"
               }
           ]
        }, 
       "entries": [
            {
               "_links": {
                  "self": [
                       {
                           "href": "url456"
                        }  
                ] 
            }, 
            "values": {
                "Request ID": "abc|abc", 
                "Status": "Assigned"
            }
        }
    ]
}

}

1 个答案:

答案 0 :(得分:1)

您可以使用json_query过滤器来获取JSON对象的Request ID值。这是如何解析它的示例。在我的示例中,我从文件中获取JSON对象,并将其存储在名为op_request的变量中。在json_query任务上,请注意如何转义内部带有圆点(.)的键:

---
- name: Get "Request ID" from JSON
  hosts: all
  connection: local
  gather_facts: no
  vars_files:
    - ./secret.yml
  vars:
    op_content_file: ./files/op_content.json
  tasks:
    - name: Read JSON file
      set_fact:
        op_content: '{{ lookup("file", op_content_file) }}'

    - name: Get RequestID from op_content variable
      set_fact:
        request_id: "{{ op_content | json_query('\"op.content\".entries[0].values.\"Request ID\"') }}"

我希望对您有帮助