在 Ansible 中,使用模板功能时可能会遇到“Fatal template error while templating string”错误。这种错误通常是由于模板字符串中的语法问题或不支持的字符引起的。以下是如何复现、排查和修复这一错误的步骤。
错误示例
以下是一个会导致“Fatal template error while templating string”错误的 Ansible Playbook 示例:
---
- name: file module demo
hosts: all
vars:
myfile: "{{ ~/example.txt }}"
tasks:
- name: Creating an empty file
ansible.builtin.file:
path: "{{ myfile }}"
state: touch
错误信息
运行上述 Playbook 时,可能会遇到以下错误:
$ ansible-playbook -i demo/inventory troubleshooting/template_error_string_error.yml
PLAY [file module demo] **************************************************
TASK [Gathering Facts] **************************************************
ok: [demo.example.com]
TASK [Creating an empty file] ********************************************
fatal: [demo.example.com]: FAILED! => {"msg": "An unhandled exception occurred while templating '{{ ~/example.txt }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: template error while templating string: unexpected '~'. String: {{ ~/example.txt }}"}
PLAY RECAP *******************************************************************
demo.example.com : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
问题原因
- 不支持的字符:模板字符串中使用了不支持的字符(如
~)。Ansible 模板中不能直接使用~符号。 - 语法问题:模板字符串的语法不正确,导致 Ansible 无法解析。
解决方法
- 修正变量格式:将变量中的
~替换为正确的路径格式。 - 避免嵌套模板表达式:确保模板字符串中没有嵌套的
{{ }}表达式。 - 使用
vars或lookup插件:如果需要动态变量,可以使用vars或lookup插件。
修复后的 Playbook 如下所示:
---
- name: file module demo
hosts: all
vars:
myfile: "~/example.txt"
tasks:
- name: Creating an empty file
ansible.builtin.file:
path: "{{ myfile }}"
state: touch
修复步骤
- 修正变量格式:将变量中的
~替换为正确的路径格式。 - 重新运行 Playbook:验证修复是否有效。
验证修复
修复问题后,重新运行 Playbook:
$ ansible-playbook -i demo/inventory troubleshooting/template_error_string_fix.yml
PLAY [file module demo] **************************************************
TASK [Gathering Facts] **************************************************
ok: [demo.example.com]
TASK [Creating an empty file] ********************************************
changed: [demo.example.com]
PLAY RECAP *******************************************************************
demo.example.com : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
总结
Ansible 中的“Fatal template error while templating string”错误通常是由于以下原因导致的:
- 不支持的字符:模板字符串中使用了不支持的字符(如
~)。 - 语法问题:模板字符串的语法不正确,导致 Ansible 无法解析。
- 嵌套模板表达式:模板字符串中嵌套了
{{ }}表达式。
通过以下步骤可以有效解决这种错误:
- 修正变量格式:确保变量中不包含不支持的字符。
- 避免嵌套模板表达式:确保模板字符串中没有嵌套的
{{ }}表达式。 - 使用
vars或lookup插件:如果需要动态变量,可以使用vars或lookup插件。 - 重新运行 Playbook:验证修复是否有效。
如果问题仍未解决,可以参考 Ansible 的 官方文档或社区支持获取更多帮助