You need to enable JavaScript to run this app. Ansible Jinja2解析JSON提取卷属性报'str对象'无volume_id_attributes错误
优惠活动
大模型
产品
解决方案
定价
更多

Ansible Jinja2解析JSON提取卷属性报'str对象'无volume_id_attributes错误

核心问题原因
  • Jinja2 对字典类型变量执行默认for循环时,循环获取的是字典的键(key),而非键对应的字典值(value)。
  • 对应到你的代码逻辑:svm.ontap_info.volume_info 是典型的嵌套字典结构,所有alfred_backup:Application_Backups、alfred_prod:Application_Backups这类字符串都是这个字典的键,真正包含volume_id_attributes、volume_space_attributes的卷属性对象是这些键对应的字典值。
  • 因为你循环时拿到的是字符串形式的键,而非属性对象,自然会触发'str object' has no attribute 'volume_id_attributes'的未定义变量报错,这也是你单独打印{{ volume }}时只能看到字符串键值的原因。
修正方案

根据是否需要获取卷的字符串标识,可选择以下三种兼容写法:

  1. 仅需要提取卷属性时,直接遍历字典的值集合:
{% for volume_attr in svm.ontap_info.volume_info.values() %}
    {% set volume_name = volume_attr.volume_id_attributes.name %}
    {% set volume_size_total = volume_attr.volume_space_attributes.size_total %}
{% endfor %}
  1. 需要同时保留卷的字符串标识和属性时,遍历字典的键值对:
{% for volume_key, volume_attr in svm.ontap_info.volume_info.items() %}
    {% set volume_identifier = volume_key %}
    {% set volume_name = volume_attr.volume_id_attributes.name %}
    {% set volume_size_total = volume_attr.volume_space_attributes.size_total %}
{% endfor %}
  1. 低版本Ansible不支持直接调用字典方法时,通过键索引取值:
{% for volume_key in svm.ontap_info.volume_info %}
    {% set volume_attr = svm.ontap_info.volume_info[volume_key] %}
    {% set volume_name = volume_attr.volume_id_attributes.name %}
    {% set volume_size_total = volume_attr.volume_space_attributes.size_total %}
{% endfor %}

补充:你提供的JSON片段存在结构截断错位(第一个应用备份的条目未闭合花括号就接了下一个数据库备份的条目),实际运行时需先确认任务返回的JSON结构是合法闭合的,避免嵌套层级错位导致的取值报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 12:15:05