DevOps Classroom Series – 30/Dec/2020

Ansible handlers

  • There will be certain tasks which should be executed only when the preceding task executes
  • As an example scenario, start and enable the apache service only when the apache is installed
---
- name: install apache
  hosts: webservers
  become: yes
  tasks:
  - name: install apache
    package:
      name: apache2
      state: present
  - name: enable and restart apache
    service:
      name: apache2
      enabled: yes
      state: restarted
  • In the above case we need to run the task enable and restart apache only when apache is installed, if apache is already installed, then there is no need to enable and restart apache
  • To solve these kind of scenarios ansible supports handlers. Handlers will be executed only when the tasks registered notify
---
- name: install apache
  hosts: webservers
  become: yes
  tasks:
  - name: install apache
    package:
      name: apache2
      state: present
    notify:
    - enable and restart apache
  handlers:
  - name: enable and restart apache
    service:
      name: apache2
      enabled: yes
      state: restarted
  • Refer Here for ansible handlers documentation
  • Lets implement handlers in our tomcat solution
  • Exercise: Now try Writing an ansible playbook for install tomcat8 on ubuntu and centos
  • Refer Here for the handler implementation
  • Refer Here for the implementation of adding executable permissions
  • Refer Here for adding service file
  • Refer Here for daemon reload
  • Refer Here for java path fix
  • Lets rerun our ansible playbook
    • Even though all the steps are configured ansible is rerun 3 tasks every time, we need them to be idempotent Preview
  • Lets look at extracting tomcat step, which needs to be done only once
    • Lets review the ansible module stat Refer Here
    • for understanding what stat returns check the Return value section.
    • Refer Here to use file not exists condition to run ansible extract zip task
    • Refer Here for ansible service fix
  • We still have problem with one area i.e. tomcat.service file is hard coded. it always copies the same content, we need to ensure our tomcat.service file is dynamic.
  • Our playbook should show the debug messages to the user
  • Our Playbook should fail if this is executed on any other operating system as it is written for ubuntu.
  • Next steps
    • ansible templates
    • ansible Jinja filters
    • Effective variable handling
    • multi environment handling
    • reusability

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin