Skip to content

Latest commit

 

History

History
108 lines (81 loc) · 2.91 KB

Handlers.md

File metadata and controls

108 lines (81 loc) · 2.91 KB

LAB: Handlers

This scenario shows:

  • how to create handlers.

Prerequisite

Steps

  • Open 'roles/web_servers/tasks/main.yml', update followings (add notify: restart_apache):
  • The variables defined near notify calls the task that is defined in 'handlers/main.yml'
- name: change email address for admin (Ubuntu)
  tags: ubuntu,apache,apache2
  lineinfile:
    path: /etc/apache2/sites-available/000-default.conf
    regexp: 'ServerAdmin webmaster@localhost'
    line: '       ServerAdmin somebody@somewhere.com'
  when: ansible_distribution == "Ubuntu"
  notify: restart_apache

image

  • All 'roles/web_servers/tasks/main.yml':
- name: install apache and php
  tags: ubuntu,apache,apache2
  apt:
    name:
      - "{{ apache_package_name }}"
      - "{{ php_package_name }}"
    state: latest

- name: start apache
  tags: ubuntu,apache,apache2
  service:
    name: "{{ apache_service }}"
    state: started
    enabled: yes

- name: change email address for admin (Ubuntu)
  tags: ubuntu,apache,apache2
  lineinfile:
    path: /etc/apache2/sites-available/000-default.conf
    regexp: 'ServerAdmin webmaster@localhost'
    line: '       ServerAdmin somebody@somewhere.com'
  when: ansible_distribution == "Ubuntu"
  notify: restart_apache

- name: copy default (index) html file for site
  tags: apache,apache2,httpd
  copy:
    src: default_site.html
    dest: /var/www/html/index.html
    owner: root
    group: root
    mode: 0644

- name: install unzip
  package:
    name: unzip

- name: install terraform
  unarchive:
    src: https://releases.hashicorp.com/terraform/1.3.4/terraform_1.3.4_linux_amd64.zip
    dest: /usr/local/bin
    remote_src: yes
    owner: root
    group: root
    mode: 0755
  • Create 'handlers' directory under 'roles/web_servers' and create 'main.yml'
- name: restart_apache
  service:
    name: "{{ apache_service }}"
    state: restarted

image

  • Run:
ansible-playbook site.yml
  • Update the mail address to trigger the handler (restart_apache). Unless the task that has notify is changed, it cannot trigger handler task.

image

  • Handler is called.

image

  • File/Directory structure:

image