Generate Employee Details Using Jinja2
This practical task demonstrates how Jinja2 templates are used to generate dynamic flat files by replacing variables with actual values during an active playbook execution.
Files & Components
Employee Name: {{ empname }}
Age: {{ empage }}
experience: {{ empexp }}
role: {{ emprole }}---
- hosts: localhost
vars:
empname: shan
empage: 27
empexp: 3
emprole: devops
tasks:
- name: Generate employee details
template:
src: employee.j2
dest: /tmp/employee.txtExecution & Final Output
terminal
# Run the Ansible Playbook
$ ansible-playbook jinja.yml
# View the newly generated dynamic text file
$ cat /tmp/employee.txtEmployee Name: shan
Age: 27
experience: 3
role: devopsStep-by-Step Explanation
- 1. Read Ansible reads the
employee.j2template file and detects the custom placeholder syntax items written inside double curly braces{{ }}. - 2. Parse It matches those template keys against the variable data models defined securely in the
vars:section of the playbook. - 3. Replace The native
templatemodule automatically substitutes every placeholder variable with its actual corresponding real-time runtime value. - 4. Create The completed, fully flattened destination text file is securely provisioned on the host at
/tmp/employee.txt.