Ansible has a features which is called "template" module, by
using it you can generate configuration files dynamically by
using Jinja2 templating.
The template module allows you to create configuration files by
combining a template file with variables and facts from your
Ansible playbook. It uses the Jinja2 templating to put
varibales details and build configuration files as per your
requirement.
Below is the basic syntax for using the template module in an
Ansible playbook:
- name: Test Configuration File
hosts: target_hosts
tasks:
- name: Create Configuration File
template:
src: /path/to/template_file.j2 # Path to your Jinja2 template
dest: /path/to/output_file # Path where the generated file will be saved
vars:
variable_name1: value1 # Define variables to use in the template
variable_name2: value2
In the above syntax, you specify the source template file
(src) and the destination file (dest) where the generated
configuration file will be saved. You can also define variables
under the vars section, which will be used during your playbook.
Let's take a small example first where we will update motd
file on target hosts. We have created a template for motd file.
Below is the content of file.
# cat template/motd.j2
Welcome to my world !!!
Your server name is {{ ansible_hostname }}
My Server Family is {{ ansible_distribution }}
Your Server Kernel Version is {{ ansible_kernel }}
Now we will write playbook to update motd on target hosts.
# cat template/update-motd.yml
- name: Example of jinja file
hosts: all
gather_facts: true
tasks:
- name: Copy motd.j2 template
template:
src: /root/template/motd.j2
dest: /etc/motd
Now you will run the playbook and it will update your motd on
target hosts. Please see below command output to see updated
motd on target hosts.
# ansible all -a 'cat /etc/motd'
test1 | CHANGED | rc=0 >>
Welcome to my world !!!
Your server name is test1
My Server Family is RedHat
Your Server Kernel Version is 3.10.0-1160.el7.x86_64
test2 | CHANGED | rc=0 >>
Welcome to my world !!!
Your server name is test2
My Server Family is Rocky
Your Server Kernel Version is 5.14.0-284.11.1.el9_2.x86_64
test3 | CHANGED | rc=0 >>
Welcome to my world !!!
Your server name is test3
My Server Family is AlmaLinux
Your Server Kernel Version is 4.18.0-477.10.1.el8_8.x86_64
This is a basic example of how you can use the Ansible template
module to dynamically generate files based on variables and
templates. In more complex use cases, you can use conditionals,
loops, and more advanced Jinja2 templating features to create
highly customizable configuration files.