Day03 - harishgorla5/Ansible GitHub Wiki
Handlers, Templates, Loops, and Roles
A handler is a special task that only runs when explicitly notified by another task.
Avoid restarting services unnecessarily. Instead, only restart if something actually changed โ like config files.
- A task uses
notify: <handler-name>
- If the task causes a change, Ansible queues the handler
- Handlers are run at the end of the play (not immediately)
- name: Copy configuration file
copy:
src: my.cnf
dest: /etc/my.cnf
notify: Restart MariaDB
handlers:
- name: Restart MariaDB
service:
name: mariadb
state: restarted
A template language that allows:
- Variable substitution:
{{ var }}
- Control structures:
{% if %}
,{% for %}
- Filters:
{{ var | lower }}
,{{ list | join(',') }}
To generate dynamic config files based on host-specific data.
<h1>Hello from {{ inventory_hostname }}</h1>
{% if ansible_distribution == "Amazon" %}
<p>This is Amazon Linux.</p>
{% endif %}
- name: Deploy homepage
template:
src: index.html.j2
dest: /var/www/html/index.html
To repeat a task for each item in a list โ like creating users, installing packages, etc.
- name: Create users
user:
name: "{{ item }}"
state: present
loop:
- alice
- bob
- carol
To structure and reuse code for tasks like installing Apache, setting up MariaDB, etc.
apache/
โโโ tasks/main.yml
โโโ handlers/main.yml
โโโ templates/index.html.j2
โโโ vars/main.yml
ansible-galaxy init apache
- name: Setup Apache
hosts: web
become: true
roles:
- apache
- Install Apache with dynamic homepage using template
- Install MariaDB using role
- Use handlers to restart services on config change
- Use loops to add system users
project/
โโโ inventory
โโโ site.yml
โโโ roles/
โ โโโ apache/
โ โ โโโ tasks/main.yml
โ โ โโโ templates/index.html.j2
โ โ โโโ handlers/main.yml
โ โโโ mariadb/
โ โโโ tasks/main.yml
โ โโโ templates/my.cnf.j2
โ โโโ handlers/main.yml
- name: Install Apache
yum:
name: httpd
state: present
- name: Deploy dynamic homepage
template:
src: index.html.j2
dest: /var/www/html/index.html
notify: Restart Apache
- name: Restart Apache
service:
name: httpd
state: restarted
<h1>Hello from {{ inventory_hostname }}</h1>
<p>Powered by Ansible</p>
- name: Install MariaDB
yum:
name: mariadb-server
state: present
- name: Deploy DB config
template:
src: my.cnf.j2
dest: /etc/my.cnf
notify: Restart MariaDB
- name: Restart MariaDB
service:
name: mariadb
state: restarted
- name: Configure Web Server
hosts: web
become: true
roles:
- apache
- name: Configure DB Server
hosts: db
become: true
roles:
- mariadb
- name: Add system users
hosts: all
become: true
tasks:
- name: Create users
user:
name: "{{ item }}"
state: present
loop:
- dev
- qa
- ops
Concept | Real Use |
---|---|
Handlers | Restart httpd/mariadb on config change |
Jinja2 | Dynamic HTML and config file templates |
Loops | User creation and package installs |
Roles | Reusable, modular playbooks |