Ansible

220621_1_앤서블_심화_handler

kimhope 2022. 6. 22. 00:46
728x90

핸들러


핸들러란

처리를 도와주는 역할

  • 작업을 도와줌
  • 핸들러를 사용하면 불필요하게 실행되는 태스크를 줄일 수 있음

 

핸들러 동작 조건

  • 전 단계에서 작업이 정상적으로 실행되고
  • 변경 사항이 발생한 경우에 동작

 


 

핸들러 동작 과정

nginx_install_w_handlers.yml

  • nginx 설치를 위한 메인 코드에 핸들러 추가
---
- name: Install nginx on the nodes
  hosts: nodes
  become: yes
  vars:
    lnx_name: "{{ 'CentOS' if ansible_distribution == 'CentOS'
                   else 'Ubuntu' if ansible_distribution == 'Ubuntu'
                   else 'Just Linux' }}"

  tasks:
    - name: nginx for any linux
      include_tasks: "{{ lnx_name }}.yml"

  handlers:
    - name: restart nginx web server
      service: name=nginx state=restarted

 

CentOS.yml

  • nginx 설치에 핸들러의 실행을 요청하는 옵션 추가
  • notify: 핸들러가 동작할 경우 실행되는 명령
- name: install epel-release
  action: "{{ ansible_pkg_mgr }} name=epel-release state=latest"
- name: install nginx web server
  action: "{{ ansible_pkg_mgr }} name=nginx state=present"
- name: upload default index.html for web server
  get_url: url=https://www.nginx.com dest=/usr/share/nginx/html/ mode=0644
  notify:
    - restart nginx web server

 

Ubuntu.yml

  • nginx 설치에 핸들러의 실행을 요청하는 옵션 추가
  • 우분투 노드에서 nginx.com url은 오류가 발생하므로 apache.com으로 변경
- name: install nginx web server
  action: "{{ ansible_pkg_mgr }} name=nginx state=present update_cache=yes"
- name: upload default index.html for web server
  get_url: url=https://www.apache.com dest=/usr/share/nginx/html/ 
           mode=0644 validate_certs=no
  notify:
    - restart nginx web server

 

플레이북 실행

  • 첫 번째 실행
  • 핸들러가 동작함
[vagrant@ansible-server install]$ anp nginx_install_w_handlers.yml

 

 

  • 두 번째 실행
  • 핸들러가 실행되지 않음 > 변경 사항이 없기 때문에

728x90