Task

Generate Employee Details Using Jinja2

Ansible · 12 min · Practical

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.j2
Employee Name: {{ empname }}
Age: {{ empage }}
experience: {{ empexp }}
role: {{ emprole }}
jinja.yml
---
- hosts: localhost
  vars:
    empname: shan
    empage: 27
    empexp: 3
    emprole: devops
  tasks:
    - name: Generate employee details
      template:
        src: employee.j2
        dest: /tmp/employee.txt

Execution & Final Output

terminal

# Run the Ansible Playbook
$ ansible-playbook jinja.yml

# View the newly generated dynamic text file
$ cat /tmp/employee.txt
/tmp/employee.txt
Employee Name: shan
Age: 27
experience: 3
role: devops

Step-by-Step Explanation

  • 1. Read Ansible reads the employee.j2 template 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 template module 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.