Ansible template not substituting if any variable not defined

1,493 views
Skip to first unread message

John Gateley

unread,
Mar 18, 2017, 1:50:02 PM3/18/17
to Ansible Project
HI y'all,

I switched to a new computer, so this is a clean installation of ansible etc.
One of my playbooks is not working properly. I tracked it down to using a template and one of the variables isn't defined.
Here's  the scenario:

role/tasks/main.yml:

---

# tasks file for apache_virtual_host


- name: create virtual host file

  template: src=apache.conf dest="/etc/apache2/sites-available/{{ virtual_host }}.conf"


- name: create virtual host file2

  template: src=apache2.conf dest="/etc/apache2/sites-available/{{ virtual_host }}2.conf"


And here are the two src files from role/template/. Notice the second does not have {{ foo }}

apache.conf:

<VirtualHost *:80>

ServerName {{ virtual_host }}

ServerAlias: {{ foo }}

</VirtualHost>


apache2.conf

<VirtualHost *:80>

ServerName {{ virtual_host }}

ServerAlias:

</VirtualHost>


And here are the result files where virtual_host is defined to be foo.com, but foo is not defined:

foo.conf

<VirtualHost *:80>

ServerName {{ virtual_host }}

ServerAlias: {{ foo }}

</VirtualHost>


foo2.conf

<VirtualHost *:80>

ServerName foo.com

ServerAlias:

</VirtualHost>


Notice that in the foo.conf file, NO SUBSTITUTION OCCURRED AT ALL even though virtual_host is defined.

I was very careful to remove the destination files on the target system so that the template was triggered.


Any help debugging this greatly appreciated


John


Brian Coca

unread,
Mar 20, 2017, 12:50:25 PM3/20/17
to Ansible Project
you can set:

error_on_undefined_vars = False

in ansible.cfg, but this will also skip any errors in templating in plays.


----------
Brian Coca

Arthur Reyes

unread,
Mar 20, 2017, 1:27:22 PM3/20/17
to Ansible Project
Use defaults, to handle undefined variables without ignoring errors:

ServerAlias: {{ foo | default('bar') }}

John Gateley

unread,
Mar 20, 2017, 11:07:20 PM3/20/17
to Ansible Project
Thank you Brian and Arthur.

I already had the error_on_undefined_vars set to False.

Based on Brian's comment I am going to switch to not having undefined variables - tlooks like my original approach is a code-smell.

However, I still believe there is a bug here, probably introduced in a recent version of Ansible.. My current version is:

ansible-playbook 2.2.1.0


My previous version is unknown, but probably a year and a half old.

The bug is that if a variable is undefined for a template, no substitutions at all are occurring, leaving the bracket notation in place. In the old version, substitutions for defined variables would occur, and for undefined variables they would be replaced with the empty string.

Thanks again,

John

Reply all
Reply to author
Forward
0 new messages