Ansible打印含嵌套变量的变量值报模板错误的解决方法
报错原因
两个问题导致执行失败:
- Jinja2模板不支持嵌套
{{ }}语法,你写的{{ Server.{{ Node_Name }}[2] }}属于非法写法,解析器读到嵌套的花括号就会抛出语法错误。 - 原Playbook没有加载存储
Server结构的a.yml文件,就算语法修正了也读不到对应数据。
修复方案
动态读取字典的键时,直接用[变量名]的索引格式即可,不需要给内部变量再加花括号包裹;同时提前加载a.yml里的变量。
给你两个可用的写法:
写法1:用include_vars加载变量文件
适合变量文件路径需要动态判断的场景:
--- - name: "Print Variable value" hosts: all gather_facts: no vars: Node_Name: Node tasks: - name: 加载a.yml中的变量 include_vars: a.yml - name: "Print the id" debug: msg: "The id is {{ Server[Node_Name][2] }}"
写法2:用vars_files预加载变量
如果变量文件路径固定,可以直接预加载,支持提前定义ID_Name变量:
--- - name: "Print Variable value" hosts: all gather_facts: no vars_files: - a.yml vars: Node_Name: Node ID_Name: "{{ Server[Node_Name][2] }}" tasks: - name: "Print the id" debug: msg: "The id is {{ ID_Name }}"
执行效果
执行你原来的命令:ansible-playbook xyz.yml -e "Node_Name=Node1"
会输出预期结果The id is ID1。
补充:如果担心传入的Node_Name不存在,可以加默认值容错,写法为
{{ Server[Node_Name][2] | default('对应节点不存在') }},避免键不存在时报错中断。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

