Ansible, an open-source automation tool, helps system administrators and DevOps teams to efficiently manage infrastructure and streamline complex tasks. One of Ansible’s powerful features is the use of templates, which allows for the dynamic generation of configuration files and other resources. Here we will go through a real-world network configuration of a small lab environment.

Don’t forget to join my Discord: https://discord.gg/YbSYGsQYES
Important information!
This solution is quick and easy to be used in a lab environment. It is not suitable for production use!
Understanding Ansible Templates
Before diving into the practical aspects, let’s gain a fundamental understanding of Ansible templates. Templates are files containing variables, which Ansible will fill in with values during runtime. These variables can come from various sources, including host-specific facts, group variables, or user-defined variables.
Creating an Ansible Template
To create an Ansible template, you need to use Jinja2 syntax, the default templating engine in Ansible. Jinja2 allows you to embed variables, loops, conditionals, and filters within your templates.
This will be in the templates directory of a role, let’s call it interfaces.j2:
source /etc/network/interfaces.d/*
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
allow-hotplug enp0s3
iface enp0s3 inet static
address {{ common_ip }}
gateway {{ common_gateway }}
Now, to use the template with actual values, define variables in your Ansible playbook, host_vars, group_vars or inventory files.
These variables will replace the placeholders in the template when running the playbook.
This is the main.yml file in the tasks of the role:
- name: Set the hostname
ansible.builtin.hostname:
name: "{{ common_hostname }}"
- name: Set the network interface
ansible.builtin.template:
src: interfaces.j2
dest: /etc/network/interfaces
owner: root
group: root
mode: "0644"
backup: true
Conclusion
Ansible templates provide a powerful and flexible way to dynamically generate configuration files, reducing repetitive tasks and minimizing the risk of errors. By understanding and utilizing templates effectively, system administrators and DevOps teams can enhance their infrastructure management processes, leading to more efficient and scalable automation.
Remember to experiment with different Jinja2 features like filters and custom functions to unlock the full potential of Ansible templates in your automation workflows. Happy automating!
Don’t forget to join my Discord: https://discord.gg/YbSYGsQYES