【问题标题】:Iterating over Ansible debug output迭代 Ansible 调试输出
【发布时间】:2019-08-20 00:20:10
【问题描述】:

以下是我的任务:

  - 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']}}

我运行 playbook 时的输出是:

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

【问题讨论】:

    标签: ansible ansible-facts


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,这对我有用。我正在尝试使用 to_json 将输出字符串转换为 json,但它失败了。
    • from_json,真厉害!
    • 当标准输出包含多个值时,相同的调试语句不起作用。例如:"stdout": "{\"name\":\"nginx-79cdd9df6b-8xbpz\",\"namespace\":\"kube-system\"}"\n"{\"name\":\"nginx-19ce8df6a-7xcqt\",\"namespace\":\"kube-system\"}"
    • 在该示例中,您需要单独解码每一行,可能通过迭代 stdout_lines
    猜你喜欢
    • 2017-06-25
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 2022-01-22
    • 2021-04-22
    • 2014-03-20
    • 2019-11-21
    • 1970-01-01
    相关资源
    最近更新 更多