Include Additional Content in Ansible Template File

While putting together an Ansible Playbook to generate a configuration file from an Ansible Template, I needed a way to include additional content from a text file within the generated configuration file. I could not find an Ansible Module to do this, but Ansible uses the Jinja2 templating engine, and with one additional line in the Ansible Template file, I was able to include the contents of the text file in the generated configuration file.

The Ansible Template is stored in ~/Development/ansible-lab/templates/ and the additional content is stored in ~/Development/ansible-lab/files/.

In this particular case, the Ansible Template is generating an Apache VirtualHost configuration file and the Ansible Template, named apache_vhost.conf.j2, contains the following contents:

NameVirtualHost *:80

<VirtualHost *:80>
    ServerName {{ item.servername }}
    DocumentRoot /var/www/html/{{ item.documentrootdir }}
    ServerAdmin {{ item.serveradmin }}
    ErrorLog logs/{{ item.errorlog }}-error_log
    CustomLog logs/{{ item.customlog }}-access_log common

    <Directory /var/www/html/{{ item.documentrootdir }}>
        Options None

{% include "files/" + item.documentrootdir + ".conf" ignore missing %}


The include line is Jinja2 syntax that will include the contents of the specified file if it exists.

So, for example, when Ansible is generating the Apache VirtualHost configuration file for, the include line would check if there is a file named in the files directory. If the file exists, its contents would be included in the generated Apache VirtualHost configuration file otherwise it would simply be ignored (the added ignore missing parameters allows this).

One thing to note, the Ansible Playbook was originally stored in directory ~/Development/ansible-lab/playbooks/ but it had to be moved to ~/Development/ansible-lab/ for all of this to work. There appears to be a pathing problem if the Ansible Playbook is in another directory. Supposedly this was fixed, but I have not investigated the issue further.


Using include to dynamically point to HTML

Template Designer Documentation #Include