lab06
inside ansible-labs
lab06
folderinventory
folder from lab05
to lab06
cp -r ../lab05/inventory ./inventory
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.
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.
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:
ansible_hostname | upper
: The hostname of the machine in uppercaseversion
: The version of nginx
to be installedansible_date_time.date
: The current datetasks/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
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
Create a playbook named nginx.yml
with the following content:
---
- name: Install nginx
hosts: all
become: yes
roles:
- lab.nginx
Run the playbook using the following command:
ansible-playbook -i inventory nginx.yml
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.
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.