迭代 Ansible 调试输出

Iterating over Ansible debug output

以下是我的任务:

  - 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 输出?

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

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