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

Ansible问题:如何解析JSON数据到变量并获取文件路径

Ansible注册变量提取path字段问题解决

我将某Ansible任务的输出注册到了task_output变量,该变量结构如下:

"ansible_loop_var": "item",
"changed": false,
"files": [
   {
       "path": "file/path"
   }
]

尝试了以下多种表达式捕获其中的path字段,但均未生效:

  • {{ task_output.files | map(attribute='path') }}
  • {{ task_output[0].files[0] | map(attribute='path') }}
  • {{ task_output[0].files | map(attribute='path') }}
  • {{ task_output.files[0] | map(attribute='path') }}
  • {{ task_output.json.files | map(attribute='path') }}
  • {{ task_output | map(attribute='path') }}

正确提取方式

  1. 提取单个path值(适用于files仅含一个元素的场景):
{{ task_output.files[0].path }}
  1. 提取所有path组成列表(适用于files含多个元素的场景):
{{ task_output.files | map(attribute='path') | list }}

无效表达式的问题说明

  • 使用map(attribute='path')但未追加| list:map过滤器返回的是生成器对象,直接输出无法显示实际值,必须转换为列表
  • 错误添加task_output[0]索引:task_output本身是单个字典对象,不是数组,不需要用索引访问
  • 错误使用task_output.json:只有当任务输出是原始JSON字符串时才需要.json解析,这里task_output已经是结构化的变量,无需额外解析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 16:24:58