Shashikant shah

Saturday, 17 October 2020

What is ansible Handlers and Tags part-5

 Ansible Handlers.

Sometimes you want a task to run only when a change is made on a machine. For example, you may want to restart a service if a task updates the configuration of that service, but not if the configuration is unchanged. Ansible uses handlers to address this use case. Handlers are tasks that only run when notified.

We will write a playbook handlers.yml to install httpd package and then use a handler to start the httpd service. This handler will be executed only when change is made.

# vi handlers.yml

---
- hosts: jenkins
  gather_facts: True
  become: yes
  vars:
          my_content: "This files created using var concept"
  tasks:
   - name: create a file var_file.txt..
     copy:
            dest: /tmp/var_file.txt
            content: "{{ my_content }}"
     notify: httpd service start

   - name: install httpd service
     yum:
         name: httpd
         state: latest
  handlers:
   - name: httpd service start
     service:
          name: httpd
          state: restarted








2. Multi handlers.yml

---
 - name: Handlers Example
   hosts: server1
   gather_facts: false
   become: true
   tasks:
     - name: print message-1
       debug:
         msg: "First Message"
       changed_when: true
       notify: run_handler
     - name: print message-2
       debug:
         msg: "Second Message"
       changed_when: true
       notify: run_handler
   handlers:
     - name: run_handler
       debug:
         msg: "Today's date and time: {{ '%d-%m-%Y %H:%M:%S' | strftime }}"










What is tags.

Ansible tags are another great feature which can help you execute respective tasks from the playbook. By default all the tasks from the playbook are executed but with tags we can control this behavior and execute only the tasks with the matching tags.










Output :-







Disable tags :-















No comments:

Post a Comment