본문 바로가기

클라우드/앤서블(Ansible)

앤서블 Ansible 작업 제어 5 / 블록

# 블록

play와 task의 중간 단계에 있는 논리적인 작업 그룹

논리적으로 작업을 그룹으로 묶는다. 조건문, 권한 상승과 같은 여러가지 키워드를 적용 할 수 있다. (반복문x)

블록으로 묶어놓은 작업에 오류가 있으면 대응해주는 예외처리기능이 있다.

 

# 작업의 그룹화

더보기

tasks:
  - name: Install, configure, and start Apache
    block:
      - name: Install httpd and memcached
        yum:
          name:
          - httpd
          - memcached
          state: present
          
      - name: Apply the foo config template
        template:
          src: templates/src.j2
          dest: /etc/foo.conf
          
      - name: Start service bar and enable it
        service:
          name: bar
          state: started
          enabled: True
    when: ansible_facts['distribution'] == 'CentOS'
    become: true
    ignore_errors: yes
    

해당 블록은 'CentOS' 배포판만 권한 상승으로 실행되고, 실패가 있더라도 무시하고 후속작업이 있으면 실행한다.

 

 

# 실패 처리 (예외 처리)- Rescue

debug,command,debug 블록의 세가지 작업 중 하나라도 오류가 있으면, 후속작업은 실행되지 않는데 Rescue 섹션의 작업이 실행되어 오류를 잡거나 rollback하는데에 사용된다. 블록의 작업 중 실패가 없으면 Rescue 섹션은 실행되지 않는다.

 

 

# 실패 처리 (예외 처리)- Always

더보기

tasks:
- name: Always do
  block:
    - name: Print a message
      debug:
        msg: ' I execute normally '
        
    - name: Force a failure
      command: /bin/false
      
    - name: Never print this
      debug:
              msg: ' I never execute :-( '
        
  always:
    - name: Print when errors
      debug:
              msg: ' This always executes:-) '
        

성공, 실패에 상관없이 항상 실행 된다.

rescue 구문에서도 실패가 있을 수 있기 때문에 always와 같이 사용하기도 한다.

 

 

# 실패 처리 (예외 처리) - handler

더보기

tasks:
- name: Attempt and graceful roll back demo
  block:
    - name: Print a message
      debug:
        msg: ' I execute normally '
      changed_when: yes
      notify: run me even after an error

    - name: Force a failure
      command: /bin/false
  rescue:
    - name: Make sure all handlers run
      meta: flush_handlers
handlers:
  - name: Run me even after an error
    debug:
      msg: 'This handler runs even on error'

블록을 실행 첫번째 작업은 실행이 되어서 notify 알림을 전송, 두번째 작업에서 오류가 나면 플레이북은 중단되어버린다.

작업이 다 끝나야만 핸들러 작업이 시작된다. 다음번 실행시에 이미 첫번째 작업이 실행되어 알림을 주어 changed상태이기 때문에, 다음 작업시에 changed상태가 될거라는걸 보장 할 수 없다. 그래서 핸들러를 flush(비움)해주어 핸들러를 무조건 작동시게한다. 강제로 핸들러 작업을 실행해야 하는 경우 meta 모듈로 flush handler(핸들러를 초기화 하여 무조건 작동할수 있게함)를 실행한다.

 

meta모듈은 특수모듈로 Ansible의 내부 명령 실행 및 상태에 영향을 줄 수 있는 여러가지 기능이 있다. 리눅스 운영체제의 리눅스 커널을 관리하는거라고 생각하면 된다. 

 

 

 

 

 

 

# 1 예제

 

 

# 2 예제

 

# 3 예제

 

 

# 4 예제