ThorneLabs

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
    </Directory>

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

</VirtualHost>

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 vhost1.example.com.conf, the include line would check if there is a file named vhost1.example.com.conf 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.

References