9-Day4-1-NotifyHandlers
**Lab Exercise:- Notify Handlers for Event-Driven Actions
Objective:
Participants will learn to use notify and handlers to implement event-driven actions in Ansible. The labs will demonstrate triggering handlers based on task outcomes, including optional exercises for advanced learning.
Lab 1.1: Basic Notify and Handlers
Scenario:
You want to install Apache, start the service, and restart it only if the configuration file is updated.
Steps:
Create the Playbook:
Save as
~/day4/notify_basic.yaml:- name: Notify Handlers Demo - Basic hosts: web_servers tasks: - name: Install Apache yum: name: httpd state: present - name: Update Apache Configuration copy: src: ~/day4/httpd.conf dest: /etc/httpd/conf/httpd.conf notify: Restart Apache - name: Start Apache service: name: httpd state: started handlers: - name: Restart Apache service: name: httpd state: restarted
Create a Sample Config File:
Save
httpd.confin~/day4/:# Basic Apache Config ServerName localhost
Run the Playbook:
ansible-playbook ~/day4/notify_basic.yaml -i ~/day3/inventory.iniExpected Output:
Apache is installed.
If
httpd.confis updated, the "Restart Apache" handler is triggered.
Lab 1.2: Multiple Handlers
Scenario:
Expand the setup to include additional services like enabling the firewall and restarting Apache only after the firewall is configured.
Steps:
Create the Playbook:
Save as
~/day4/multiple_handlers.yaml:
Run the Playbook:
Expected Output:
The firewall configuration is reloaded if HTTP is enabled.
Apache restarts only if its configuration file is updated.
Lab 1.3: Conditional Notifications
Scenario:
Add a conditional notification for restarting Apache only if the server has more than 1GB of free memory.
Steps:
Create the Playbook:
Save as
~/day4/conditional_notify.yaml:
Run the Playbook:
Expected Output:
Apache restarts only if there’s more than 1GB of free memory.
Optional Lab: Chain Multiple Handlers
Scenario:
Update a custom HTML file and restart Apache only if the update is successful.
Create the Playbook:
Save as
~/day4/chain_handlers.yaml:
Create the
index.htmlFile:Save in
~/day4/:
Run the Playbook:
Expected Output:
Apache restarts only if
index.htmlcontains "Welcome."
Key Learning Points:
Notify and Handlers:
Trigger handlers based on task outcomes.
Chain multiple handlers for dependent actions.
Conditional Notifications:
Use conditional logic to control when handlers are triggered.
Optional Exercises:
Allow participants to explore chaining and advanced notifications.
This lab ensures a hands-on understanding of notify and handlers in Ansible with real-world scenarios and customization opportunities.
Last updated