You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible技术问题:如何从字典变量提取指定属性到模板中?

解决Ansible任务报告中从字典变量提取数据的问题

你需要从test变量的results数组中提取每个测试项的item和msg字段,原Jinja2模板的错误在于循环对象不对,且未正确遍历数组元素。

变量示例

ok: [localhost] => {
    "test": {
        "changed": false,
        "failed": true,
        "msg": "One or more items failed",
        "results": [
            {
                "ansible_loop_var": "item",
                "changed": false,
                "elapsed": 4.0650629,
                "failed": true,
                "item": "prdrimaknmcs01.perceptive.cloud",
                "msg": "timeout while waiting for prdrimaknmcs01.perceptive.cloud:9091 to start listening",
                "wait_attempts": 2
            },
            {
                "ansible_loop_var": "item",
                "changed": false,
                "elapsed": 4.0600610999999995,
                "failed": true,
                "item": "prdrimaknmcs02.perceptive.cloud",
                "msg": "timeout while waiting for prdrimaknmcs02.perceptive.cloud:9091 to start listening",
                "wait_attempts": 2
            }
        ],
        "skipped": false
    }
}

错误模板的问题

原模板循环的是test字典本身,而不是test.results数组;同时test.results.msg无法直接获取值,因为results是数组,必须遍历每个元素才能拿到对应的msg。

正确的Jinja2模板

# 测试结果报告
{% if test.results | length > 0 %}
以下是测试结果:
{% for result in test.results %}
- 目标主机:{{ result.item }}
  错误信息:{{ result.msg }}
{% endfor %}
{% else %}
无测试结果
{% endif %}

补充:生成报告文件并发送邮件的Ansible任务示例

- name: 生成测试报告文件
  template:
    src: report.j2
    dest: /tmp/test_report.txt
  delegate_to: localhost

- name: 发送测试报告邮件
  mail:
    subject: "Ansible测试任务报告"
    body: "{{ lookup('file', '/tmp/test_report.txt') }}"
    to: "your_email@example.com"
    from: "ansible@example.com"
  delegate_to: localhost

内容的提问来源于stack exchange,提问作者StanS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:18:27