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') }}
正确提取方式
- 提取单个path值(适用于files仅含一个元素的场景):
{{ task_output.files[0].path }}
- 提取所有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
相关产品推荐
相关产品推荐

