Ansible

Ansible Handler & Vars

Joon0464 2021. 7. 23. 14:42

https://www.inflearn.com/course/ansible-%EC%8B%AC%ED%99%94/lecture/10806?tab=curriculum&speed=1 

 

[심화] 앤서블(Ansible)을 깊이 있게 활용하기 - 인프런 | 학습 페이지

지식을 나누면 반드시 나에게 돌아옵니다. 인프런을 통해 나의 지식에 가치를 부여하세요....

www.inflearn.com

1. 핸들러란?

핸들러는 파일이 정상적으로 전송된 것을 확인하고 nginx 서비스를 재시작한다. 만약 파일이 정상적으로 전송되지 않으면 동작하지 않게 된다. 따라서 불필요한 작업을 줄일 수 있게 된다.
또한 변경사항을 감지하여 변경사항이 발생한 것에 대해서만 핸들러가 동작하게 된다. 변경사항이 없으면 실행되지 않아 불필요한 작업을 줄이게 된다.

따라서 서비스와 같이 변경사항이 발생해야만 적용해야하는 곳에서 핸들러가 주로 쓰인다.

2. Handler를 사용한 nginx 구성 플레이북 작성

# vi nginx_install_w_handlers.yml
---
- name: Install nginx on the nodes
  hosts: nodes
  become: yes
  vars:
    lnx_name: "{{ 'Ubuntu' if ansible_distribution == 'Ubuntu'
                   else 'CentOS' if ansible_distribution == 'CentOS'
                   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

handler가 설정되어 있으므로 

# vi CentOS.yml

- 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.apache.org dest=/usr/share/nginx/html/ mode=0644
  notify:
    - Restart nginx web server
# vi Ubuntu.yml

- 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.org dest=/usr/share/nginx/html/ mode=0644 validate_certs=no
  notify:
    - Restart nginx web server

notify가 변경사항을 감지하고 handler를 호출하게 된다.

# ansible-playbook nginx_install_w_hadlers.yml

플레이북을 실행하면 Handler에 의해 nginx 서비스가 재시작되는것을 볼 수 있다.

만약 한 번 더 동일한 플레이북을 실행시키면 handler가 동작하지 않는 것을 볼 수 있다.

이처럼 handler를 사용하면 task의 전체 실행을 줄일 수 있다.

 

3. Vars(변수)

변수의 우선순위 (아래로 갈수록 우선순위가 높다.)

  1. role defaults
  2. inventory file or script group vars
  3. inventory group_vars/all
  4. playbook group_vars/all
  5. inventory group_vars/*
  6. playbook group_vars/*
  7. inventory file or script host vars
  8. inventory host_vars/*
  9. playbook host_vars/*
  10. host facts
  11. play vars
  12. play vars_prompt
  13. play vars-files
  14. role vars (defined in role/vars/main.yml)
  15. block vars (only for tasks in block)
  16. task vars (only for the task)
  17. role (and include_role) params
  18. include params
  19. include_vars
  20. set_facts / registered vars
  21. extra vars (always win precedence)

tree

이번 vars의 동작 원리를 이해하기 쉽도록 tree 패키지를 설치한다.

tree 패키지란 리눅스 드렉터리 구조를 트리구조로 보여주는 프로그램이다.

sudo yum -y install tree

tree 패키지를 yum을 사용하여 설치한다.

현재 playbook의 구조를 tree를 사용하여 한 눈에 볼 수 있다.

Playbook 내용 살펴보기

# vi nginx_install_wo_vars.yml

---
- name: Install nginx on the nodes
  hosts: nodes
  become: yes

  tasks:
  - name: nginx for Any Linux
    include_tasks: "{{ lnx_name }}.yml"

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

이전의 nginx_install_w_handlers.yml 플레이북에서 vars가 빠진 상태이다.

include_tasks에 사용되는 {{ lnx_name }}의 변수를 정의할 vars가 사라졌기 때문에 외부 파일에서 따로 정의해야한다.

# vi CentOS.yml

- 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.apache.org dest=/usr/share/nginx/html/ mode=0644
  notify:
    - Restart nginx web server
# vi Ubuntu.yml

- 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.org dest=/usr/share/nginx/html/ mode=0644 validate_certs=no
  notify:
    - Restart nginx web server

Ubuntu.yml 과 CentOS.yml은 이전과 동일하게 작성되어있다.

 

group_vars 사용해보기

playbook 작성 구조
/etc/ansible/hosts에 정의된 nodes

group vars를 사용하기 위해서는 group_vars라는 디렉토리 내부에 /etc/ansible/hosts에 정의 되어있는 호스트 그룹 이름으로된 파일로 vars를 정의해야한다.

# vi ./group_vars/nodes

lnx_name: "{{ 'Ubuntu' if ansible_distribution == 'Ubuntu'
               else 'CentOS' if ansible_distribution == 'CentOS'
               else 'Just Linux' }}"

nodes에 변수를 정의하려면 이전에 작성한 nginx_install playbook 내에 정의했던 vars의 내용을 그대로 적으면 된다.

이전에 작성하여 사용했던 nginx_install_w_handlers.yml 파일에 존재하는 vars

ansible-playbook nginx_install_wo_vars.yml

플레이북을 실행하여 설치를 진행해본다.

정상적으로 변수를 불러오게 되어 nginx가 설치된다.

host_vars 사용해보기

# rm -rf group_vars

group_vars가 host_vars보다 우선순위가 더 높으므로 group_vars를 제거해야만 host_vars를 사용할 수 있다.

host_vars의 디렉토리가 설치할 플레이북과 같은 경로에 있어야 host_vars를 사용할 수 있다.

# vi ./host_vars/192.168.1.101

lnx_name: "{{ 'Ubuntu' if ansible_distribution == 'Ubuntu'
               else 'CentOS' if ansible_distribution == 'CentOS'
               else 'Just Linux' }}"
               
# mv 192.168.1.101 192.168.1.102
# mv 192.168.1.101 192.168.1.103
# mv 192.168.1.101 192.168.1.104
# mv 192.168.1.101 192.168.1.201
# mv 192.168.1.101 192.168.1.202
# mv 192.168.1.101 192.168.1.203
# mv 192.168.1.101 192.168.1.204

host_vars 디렉토리 내부에 192.168.1.101과 같이 변수를 읽어올 대상의 IP로 파일 이름을 지정한다. 파일의 작성 내용은 이전과 동일하다.

모든 호스트에 적용하기 위해서 192.168.1.101 파일을 작성한 후 복사하여 102, 103, 104, 201, 202, 203, 204 호스트를 위한 vars 파일을 생성한다.

host_vars내의 파일들

ansible-playbook nginx_install_wo_vars.yml

플레이북을 실행시키면 정상적으로 nginx가 모든 노드에 설치된다.