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

Ansible J2模板语法报错:如何正确设置CPU变量的备选值?

Ansible Jinja2模板语法问题解决

问题场景

此前你使用default过滤器处理自定义变量无法解析的场景,写法运行正常:

{{ hostvars[h]['myvar'][0]['myothervar'] | default('foobar') }}

现在需要实现:当Ansible无法连接目标机器获取ansible_processor_vcpus时,输出上述自定义变量的内容,但以下写法触发报错:

{{ hostvars[h]['ansible_processor_vcpus'] | hostvars[h]['myvar'][0]['myothervar'] }}

报错信息:

AnsibleError: template error while templating string: expected token 'end of print statement', got '['.

错误原因

你错误地将变量表达式当作过滤器使用,Jinja2中|符号后必须是合法的过滤器名称,不能直接放置变量引用。

正确语法

要实现需求,需将自定义变量作为default过滤器的参数传入,正确写法如下:

{{ hostvars[h]['ansible_processor_vcpus'] | default(hostvars[h]['myvar'][0]['myothervar']) }}

如果需要兼顾自定义变量本身也可能无法解析的情况,可以嵌套default过滤器:

{{ hostvars[h]['ansible_processor_vcpus'] | default(hostvars[h]['myvar'][0]['myothervar'] | default('foobar')) }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:34:57