Using Ansible Template Module – In Just 3 Simple Steps
Most often, the system administrators have to manage configurations files on multiple servers. Which is normally a tedious and time taking task.
Ansible provides the facility to maintain such files as standard templates, which contains all the necessary configuration parameters along with dynamic values in the form of variables. During the playbook execution (depending on the conditions, if used) the variables will be replaced with the relevant values.
Note: Ansible uses Jinja2 templating language, thus the Ansible template files are created with extension J2 (i.e. templateFile.j2).
Example:
We shall use the Ansible template module to update the /etc/httpd/conf/httpd.conf configuration files on target managed nodes as per a pre-defined template configuration file present at Ansible control node.
Current Ansible Environment:
Pre-Requisites:
1- One Ansible Control Node
2- Two Ansible managed hosts (You may use as many as you want)
3- Network access between control node and managed nodes
4- SSH keys should have already been generated at control node and shared with managed nodes (see this article to configure SSH Keys: http://tiny.cc/ro75fz)
Step-1: Create a template file for “/etc/httpd/conf/httpd.conf” and configure “ansible_managed” variable at control node:
Place a template file httpd_conf_template.j2 at control node (i.e. 192.168.0.150)
Add one line same like circled in red in the below image
# {{ ansible_managed }}
See file contents highlighted in yellow in the below image:
Add one line (as shown below) in the file /etc/ansible/ansible.cfg
Step-2: Create a playbook to copy the template at managed hosts
Before execution of playbook
Following is the status of file => /etc/httpd/conf/httpd.conf present at target managed hosts:
Please see the file permissions (i.e. 777) and group and owner names (i.e. Fakhar)
Note the contents (in yellow) of file /etc/https/conf/httpd.conf at managed host => 192.168.0.160
Note the contents (in yellow) of file /etc/https/conf/httpd.conf at managed host => 192.168.0.170
Create a playbook with following contents at control node:
Create an inventory file with following contents:
See below image, how files are placed at control node? (just to explain better)
Step-3: Run the playbook with following command at control node (with root user) and check the results.
Please see below image for playbook execution results:
After execution of playbook
See the file permissions, owner and group names in the below image:
See the green circled contents of file => etc/httpd/conf/httpd.conf at node-1 (i.e. 192.168.0.160) in the below image. The new template files has been replaced.
See the green circled contents of file => /etc/httpd/conf/httpd.conf at node-2 (i.e. 192.168.0.170) in the below image. The new template files has been replaced.
The template file has been updated at both of the managed hosts successfully.