ansible-training

Lab 06 - Using Templates with Jinja2

Table of Contents

Objectives

Prerequisites

Guide

Step 01: Create a nginx role

Create a role named lab.nginx using the following command:

ansible-galaxy role init --init-path=./roles/ lab.nginx

Now let’s update role’s files to install the nginx package and start the service.

Step 02: Update defaults/main.yml

Update the defaults/main.yml file, removing all file content and include the following content:

---
version: "1.18.0"
template_file: "templates/index.html.j2"

With these variables, you may use a specific version of nginx and a template file to configure it.

Step 03: Create a template file

Create a file named index.html.j2 inside templates with the following content:

<!DOCTYPE html>

<html>
  <head>
    <title>Welcome to </title>
  </head>
  <body>
    <h1>Welcome to </h1>
    <p>This is a sample page created using Jinja2 template.</p>
    <p>Version: </p>
    <p>Date: </p>
  </body>
</html>

Take a look at the variables used inside the template file. You can use any variable available in Ansible to create a dynamic template.

On this example, you are using the following variables:

Step 04: Update tasks/main.yml

Update the tasks/main.yml file removing all content and to include the following content:

---
- name: Install nginx
  package:
    name: nginx
    state: present

- name: Start nginx
  service:
    name: nginx
    state: started
    enabled: yes

- name: Create index.html
  template:
    src: ""
    dest: /usr/share/nginx/html/index.html
  notify: Restart nginx

Step 05: Update handlers/main.yml

Update the handlers/main.yml file removing all content and to include the following content:

---
- name: Restart nginx
  service:
    name: nginx
    state: restarted

Step 06: Create a playbook

Create a playbook named nginx.yml with the following content:

---
- name: Install nginx
  hosts: all
  become: yes
  roles:
    - lab.nginx

Step 07: Run the playbook

Run the playbook using the following command:

ansible-playbook -i inventory nginx.yml

Step 08: Access the server

Open a web browser and access the server using the following URL:

You should see the index.html file created using the Jinja2 template.

For each server, the hostname and the date should be different.

Conclusion

You’ve learned how to use Jinja2 templates with Ansible. You’ve created a role that uses a template file to create a dynamic index.html file for nginx server.