遍历Ansible调试输出

时间:2019-08-19 02:09:12

标签: ansible ansible-facts

以下是我的任务:

  - name: Get pods
    shell: kubectl -n kube-system get pods -o json | jq '.items[] | .metadata.name'
    register: result

  - debug:
    var=result2

  - debug:
    msg: name is {{result.stdout['name']}}

我运行剧本时的输出是:

    ok: [tester] => {
    "result": {
        "changed": true,
        ...
        "stderr": "",
        "stderr_lines": [],
        "stdout": "{\"name\":\"nginx-79cdd9df6b-8xbpz\",\"namespace\":\"kube-system\"}"
        "stdout_lines": [
            "{\"name\":\"nginx-79cdd9df6b-8xbpz\",\"namespace\":\"kube-system\"}"
        ]
    }
}

我想解析stdout并获取输出的name。但是,调试阶段无法使用result.stdout.nameresult.stdout['name']并显示以下错误:

the error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'name'\n\nThe error appears to...
: line 25, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.

如何解析调试变量的JSON输出?

1 个答案:

答案 0 :(得分:3)

查看调试输出,您可以看到result.stdout string 。内容是一个JSON编码的字典。如果要直接访问该字典的属性,则需要使用from_json过滤器反序列化JSON,如下所示:

- debug:
    msg: "{{ (result.stdout|from_json).name }}"