• task의 맨 뒤에 notify action 설정(handler의 이름으로 호출) → 함수의 기능과 유사
  • 여러 번 조건을 만족해도 단 한번만 실행
  • handler는 변경이 있을 때 작업을 수행(Handler 는 특정 이벤트가 일어났을 때 실행)
  • handler는 특별한 task의 list이며 이름으로 참조 → handlers로 선언한 이름을 기반으로 task의 notify에서 호출(Task에서 notify로 handler를 call할 때만 실행됨)
  • 대개 service restart 등에 사용 → 예시) rc-local.services를 restart할때 handler 사용
  • 'notify' action은 play의 각 task들이 끝날때 시작
  • Handler는 Task와 기능적으로 많이 유사 → Task가 하는 모든 일을 할 수 있음

Nginx 서비스 설치 및 실행 과정


Nginx 서비스 설치 및 nginx의 html 파일 다운하는 yaml 파일

  • handler를 사용하여 task 작업 후에 Nginx 서비스가 실행 될 수 있게 설정

    $ vi nginx_install.yml
    ---
    - hosts: test
      remote_user: hippo                                                          # 사용자 id -> hippo
      become_method: su                                                         # sudo로 하면 아래 비밀번호 입력할 때 까지 root 권한을 가질 수 없어 문제 발생
      gather_facts: no
      tasks:
        - name: install epel-release
          yum: name=epel-release state=latest
    
        - name: install nginx web server
          yum: name=nginx state=present
    
        - name: Upload basic index.html for web server
          get_url:
            url : https://www.nginx.com
            dest : /usr/share/nginx/html/index.html mode=0644   # get_url 모듈을 사용할 수 없다면 shell 모듈로 "wget 명령어" 사용하여 해당 파일 다운
          notify:                                                                        # handler를 호출하기 위해 handler 이름 지정
            - Restart nginx web server
            - Print nginx service status
    
        - name: confirm to change index.html
          shell: "cat /usr/share/nginx/html/index.html"
          register: change_result
    
        - name: print change file result
          debug:
            msg:
              - "{{ change_result.stdout.split('\n') }}"
    
      handlers:
        - name: Restart nginx web server
          service: name=nginx state=restarted enabled=yes
    
        - name: Print nginx service status
          shell: "/bin/systemctl status nginx"
          register: nginx_status
          debug:
            msg:
              - "{{ nginx_status.stdout.split('\n') }}"

+ Recent posts