Saturday, 6 December 2025

Ansible 15. template in ansible

1️⃣ What is an Ansible Template?

In Ansible, a template is a file (usually with .j2 extension, meaning Jinja2 template) that contains dynamic content. You can define placeholders or variables in the file, and when Ansible runs, it replaces these placeholders with actual values from your variables, host facts, or inventory.

  • Template file → usually in templates/ folder in your Ansible project

  • Module usedansible.builtin.template

  • Purpose → To generate configuration files dynamically based on variables.

Example placeholder in template:

# db_config.conf.j2 db_name={{ db_name }} db_user={{ db_user }} db_password={{ db_password }}


2️⃣ How It Works

Suppose you want to create a database configuration file for Oracle. Instead of writing separate files for each database, you can use a template:

  • Template contains variables: {{ db_name }}, {{ db_user }}, etc.

  • Playbook provides values for these variables.

  • Template module copies the rendered file to the target server.

Scenario:
You want to create an init.ora (Oracle initialization parameter file) for multiple Oracle databases dynamically using Ansible.


Step 1: Create a template file

templates/init.ora.j2

# Oracle Initialization Parameter File db_name={{ db_name }} memory_target={{ memory_target }} processes={{ processes }} audit_file_dest={{ audit_file_dest }}

Step 2: Create a playbook

create_oracle_init.yml

--- - name: Deploy Oracle init.ora files hosts: oracle_servers become: yes vars: databases: - name: PRODDB memory_target: 2G processes: 300 audit_file_dest: /u01/app/oracle/admin/PRODDB/adump - name: TESTDB memory_target: 1G processes: 150 audit_file_dest: /u01/app/oracle/admin/TESTDB/adump tasks: - name: Generate init.ora from template ansible.builtin.template: src: init.ora.j2 dest: "/u01/app/oracle/admin/{{ item.name }}/init.ora" owner: oracle group: oinstall mode: 0644 loop: "{{ databases }}" loop_control: label: "{{ item.name }}"

Step 3: What happens when you run this playbook

  • For PRODDB, the template will create:

db_name=PRODDB memory_target=2G processes=300 audit_file_dest=/u01/app/oracle/admin/PRODDB/adump
  • For TESTDB, it will create:

db_name=TESTDB memory_target=1G processes=150 audit_file_dest=/u01/app/oracle/admin/TESTDB/adump

✅ No need to manually edit files for each database.


4️⃣ Why this is useful

  • Automates repetitive tasks for multiple databases.

  • Ensures consistency across environments (dev, test, prod).

  • Variables can come from inventory, host facts, or external files.

  • Reduces human errors when configuring multiple Oracle databases.


No comments:

Post a Comment

Building a Safer PostgreSQL CI/CD Pipeline with GitHub Actions: Dev → PR Review → Test Promotion

In my previous post, we explored a simple push-to-main deployment strategy . While functional, that model is not considered an industry best...