Introduction
Welcome to another episode of Ansible Pilot! I'm Luca Berton, and today we'll be diving into Ansible troubleshooting, focusing on the "FATAL template error while templating string" runtime error. Join me as we explore how to reproduce, troubleshoot, and fix this challenging issue.
The Demo
Let's jump straight into a live Playbook to understand the error practically. In this example, we have a playbook (template_error_string_error.yml) attempting to create an empty file with a variable referencing ~/example.txt.
``yaml
template_error_string_error.yml
---
- name: file module demo
hosts: all
vars:
myfile: "{{ ~/example.txt }}"
tasks:
- name: Creating an empty file
ansible.builtin.file:
path: "{{ myfile }}"
state: touch
`
Executing this playbook (ansible-playbook -i inventory template_error_string_error.yml) results in a fatal error:
`bash
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 }}"}
`
Understanding the Error
The error message is clear: "template error while templating string: unexpected '~'." The issue lies in the attempt to use the tilde (~) symbol in the variable, which is not a valid attribute for templating.
Fixing the Code
To resolve the issue, we need to correct our playbook. The fixed version (template_error_string_fix.yml) uses the correct variable format:
`yaml
template_error_string_fix.yml
---
- name: file module demo
hosts: all
vars:
myfile: "~/example.txt"
tasks:
- name: Creating an empty file
ansible.builtin.file:
path: "{{ myfile }}"
state: touch
`
Executing the fixed playbook (ansible-playbook -i Playbook/inventory troubleshooting/template_error_string_fix.yml) should now complete without errors:
`bash
TASK [Creating an empty file] *
changed: [demo.example.com]
``
Conclusion
In this tutorial, we walked through reproducing, troubleshooting, and fixing the "FATAL template error while templating string" error in Ansible. The key takeaway