Ansible:如何从YAML中的JSON响应中提取嵌套的字典值

时间:2019-09-10 18:11:33

标签: ansible yaml

在剧本中,我们通过其Web API对密码库进行查询。问题是我要获取的值位于一个dict中,而该dict本身又位于另一个dict中,而且我不知道如何使用yaml语法从嵌套dict中获取该值。这是Web请求的内容:

[localhost] => {
    "cache_control": "no-store",
    "changed": false,
    "connection": "close",
    "content_length": "190",
    "content_type": "application/json",
    "cookies": {},
    "cookies_string": "",
    "date": "Tue, 10 Sep 2019 18:00:18 GMT",
    "elapsed": 0,
    "invocation": {
        "module_args": {
            "attributes": null,
            "backup": null,
            "body": null,
            "body_format": "raw",
            "client_cert": null,
            "client_key": null,
            "content": null,
            "creates": null,
            "delimiter": null,
            "dest": null,
            "directory_mode": null,
            "follow": false,
            "follow_redirects": "safe",
            "force": false,
            "force_basic_auth": false,
            "group": null,
            "headers": {
                "X-Vault-Token": "<token>"
            },
            "http_agent": "ansible-httpget",
            "method": "GET",
            "mode": null,
            "owner": null,
            "regexp": null,
            "remote_src": null,
            "removes": null,
            "return_content": false,
            "selevel": null,
            "serole": null,
            "setype": null,
            "seuser": null,
            "src": null,
            "status_code": [
                200
            ],
            "timeout": 30,
            "unix_socket": null,
            "unsafe_writes": null,
            "url": "http://<serverip>:8200/v1/cubbyhole/ansible",
            "url_password": null,
            "url_username": null,
            "use_proxy": true,
            "validate_certs": false
        }
    },
    "json": {
        "auth": null,
        "data": {
            "ansible_password": "<thepassword>"
        },
        "lease_duration": 0,
        "lease_id": "",
        "renewable": false,
        "request_id": "77f067f4-8deb-538b-26d2-8b70f8c83e71",
        "warnings": null,
        "wrap_info": null
    },
    "msg": "OK (190 bytes)",
    "redirected": false,
    "status": 200,
    "url": "http://<serverip>:8200/v1/cubbyhole/ansible"
}

我要检索的数据是位于“数据”字典中的密码,它本身就是json字典的一部分。

我尝试过的每种语法似乎都无法比json dict更深入。有关如何进行的任何线索?

剧本看起来像:(调试部分是最后一次尝试获取密码值的尝试)

  - name: get password
    uri:
      url: "http://<serverip>:8200/v1/cubbyhole/ansible"
      method: GET
      validate_certs: no
      headers:
        X-Vault-Token: "{{ansible_token}}"
    register: secret_result

    debug:
          msg: "{{item.key['data']}}"
        with_dict: 
          - '{{ secret_result }}'

我看了很多帖子,但是大多数帖子都足够不同,以致于他们的解决方案不适用。我还尝试了从这些帖子(with_dict,with_subelements)派生的大量语法,但没有用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

简单地:

- debug:
    msg: "{{ secret_result.json['data']['ansible_password'] }}"