Ansible 'fatal: template error while templating string' Fix (Guide)
By Luca Berton · Published 2024-01-01 · Category: installation
Fix Ansible template error while templating string. Resolve undefined variables, syntax errors, and Jinja2 issues in playbooks and templates with examples.

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.
See also: Ansible 'chgrp failed' Error: Fix Group Ownership Permission Issues
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.
# 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:
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.
See also: Ansible 'Destination Does Not Exist' Error: Fix Path Issues
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:
# 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:
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 is to ensure that variables are formatted correctly in your playbooks.
I hope this guide helps you navigate and resolve similar issues in your Ansible automation journey. If you found this information valuable, consider subscribing for more Ansible insights.
See also: Ansible 'Missing Required Arguments' Error: Fix Missing Module Parameters
Playbook
The best way of talking about Ansible troubleshooting is to jump in a live Playbook to show you practically thenot a valid attribute for a Play error and how to solve it!
error code
• 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
error execution
• output$ ansible-playbook -i Playbook/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
fix code
• 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
fix execution
• output$ ansible-playbook -i Playbook/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
Conclusion
Now you know better how to troubleshoot the template error while templating string error.Common Causes
Undefined variable
# ERROR: 'my_var' is undefined
- debug: msg="{{ my_var }}"
# FIX: Use default filter
- debug: msg="{{ my_var | default('fallback') }}"
# FIX: Define the variable
- hosts: all
vars:
my_var: "hello"
Missing quotes around Jinja2
# ERROR: YAML parsing fails
- debug:
msg: {{ my_var }}
# FIX: Quote the value
- debug:
msg: "{{ my_var }}"
Undefined in when clause
# ERROR if var doesn't exist
- debug: msg="skip"
when: my_var == "value"
# FIX: Check if defined first
- debug: msg="skip"
when: my_var is defined and my_var == "value"
Nested variable access on None
# ERROR if 'result' has no 'stdout'
- debug: msg="{{ result.stdout }}"
# FIX: Use default
- debug: msg="{{ result.stdout | default('') }}"
# FIX: Check first
- debug: msg="{{ result.stdout }}"
when: result.stdout is defined
Template File Errors
Syntax error in .j2 file
{# WRONG: missing % #}
{ for item in list }
{# CORRECT #}
{% for item in list %}
{{ item }}
{% endfor %}
Unbalanced brackets
{# WRONG: missing closing bracket #}
value={{ my_dict['key'] }
{# CORRECT #}
value={{ my_dict['key'] }}
Jinja2 in when (don't use {{ }})
# WRONG: double templating
- debug: msg="hello"
when: "{{ my_var }} == 'value'"
# CORRECT: when already templates
- debug: msg="hello"
when: my_var == 'value'
Debugging Templates
# Verbose output shows template errors
ansible-playbook site.yml -vvv
# Test template rendering
ansible localhost -m template -a "src=test.j2 dest=/tmp/test.out"
# Debug variables before using them
- debug: var=my_complex_var
- debug: msg="{{ my_complex_var | type_debug }}"
Common Fixes
| Error | Fix |
|-------|-----|
| 'X' is undefined | Add default() filter or define variable |
| no filter named 'X' | Install missing collection or check filter name |
| Unexpected templating type error | Check variable type matches usage |
| recursive loop detected | Variable references itself |
| AnsibleUndefinedVariable | Variable not in scope (wrong host/group) |
Safe Variable Access
# Multiple fallbacks
value: "{{ primary_var | default(secondary_var) | default('final_fallback') }}"
# Nested dict access
value: "{{ mydict.get('key', 'default') }}"
# Optional dict key
value: "{{ mydict['key'] | default(omit) }}"
FAQ
"recursive loop detected in template"?
A variable references itself: my_var: "{{ my_var }}_suffix". Use a different variable name.
How do I escape {{ in templates?
{% raw %}
This {{ is not }} templated
{% endraw %}
Template works locally but fails on remote?
The remote host may have different facts or variables. Check hostvars[inventory_hostname] for what's available.
Related Articles
• template lookups in Ansible • inventory configuration in Ansible • recursive permission changes with ansible.builtin.file • Ansible role best practicesCategory: installation
Watch the video: Ansible 'fatal: template error while templating string' Fix (Guide) — Video Tutorial