Include Additional Content in Ansible Template File

• Updated May 27, 2014

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.


If you found this post useful and would like to help support this site - and get something for yourself - sign up for any of the services listed below through the provided affiliate links. I will receive a referral payment from any of the services you sign-up for.

Get faster shipping and more with Amazon Prime: About to order something from Amazon but want to get more value out of the money you would normally pay for shipping? Sign-up for a free 30-day trial of Amazon Prime to get free two-day shipping, access to thousands of movies and TV shows, and more.

Thanks for reading and take care.