본문 바로가기

Ansible

Ansible Roles ②Tasks(Apache 설치 유무에 따라 자동 설치/삭제)

반응형

tasks 디렉토리?

- Ansible 역할(Role)에서 해당 역할이 수행할 작업을 정의하는 곳.

- 각각의 작업을 수행하는 Ansible 테스크 파일들이 위치하고 있음.

- 일반적으로 tasks 디렉토리에는 여러 테스크 파일이 포함되어 있으며, 주로 YAML 형식으로 작성됨.

- 각 테스크 파일은 하나의 작업을 수행하며, 역할이 수행해야 하는 여러 작업을 모듈화하여 구성할 수 있음.

 

 

 

 

예제: Apache 설치 유무에 따라 자동으로 설치 또는 삭제하는 태스크 생성 

1.  기본 세팅

 

설정 파일, roles, 호스트 파일, 기타 필요한 디렉터리 생성:

# Role과 Inventory 폴더 생성
mkdir roles inventory

# 앤서블 설정파일과 호스트파일 생성
touch ansible.cfg inventory/inventory.ini

# 호스트파일 내용
# /inventory/inventory.ini
[web_servers]
web		web_host=192.168.77.114		web_user=ubuntu

# 앤서블 설정파일 내용
# /ansible.cfg
[defaults]
inventory = inventory.ini				# inventory 파일 지정
roles_path = ~/ansible_test/roles		# role을 찾을 디렉토리 경로 설정

# web_server라는 role 생성
ansible-galaxy init roles/web_server

 

 

 

2. tasks 폴더에 테스크 파일 생성

 

apache 설치 태스크 파일:

# vi roles/web_server/tasks/install_apache.yml
---
# apache 설치
- name: Install Apache web server
  ansible.builtin.package:
    name: apache2
    state: present
  become: true

# apache 실행
- name: Ensure Apache web server is running
  ansible.builtin.service:
    name: apache2
    state: started

 

 

apache 삭제 태스크 파일:

# vi roles/web_server/tasks/uninstall_apache.yml
---
# apache 중지
- name: Stop Apache web server
  ansible.builtin.service:
    name: apache2
    state: stopped

# apache 삭제
- name: Uninstall Apache web server
  ansible.builtin.apt:
    name: apache2
    state: absent
  become: true

 

 

web_server 역할이 수행할 태스크 작성(main.yml):

# vi roles/web_server/tasks/main.yml
---
# apache 설치 유무 확인
- name: Collect package facts
  ansible.builtin.package_facts:
    manager: auto
  register: package_facts

# 설치가 안돼있으면 설치
- name: Check if Apache2 is installed
  include_tasks: uninstall_apache.yml
  when: "'apache2' in package_facts.ansible_facts.packages"

# 설치되어있으면 삭제
- name: Check if Apache2 is not installed
  include_tasks: install_apache.yml
  when: "'apache2' not in package_facts.ansible_facts.packages"

 

 

3. 플레이북 작성

apache를 설치한 host완 적용할 role 설정.

앞서 inventory.ini 에 등록한 web_server 에 설치할 예정.

 

# roles/web_server.yaml
---
# 호스트와 역할 config
- name: Configure Web Servers
  become: true
  hosts: web_servers
  roles:
    - web_server

 

 

최종 디렉토리 구조:

 

 

 

4. 플레이북 실행

 

# ansible-playbook -i <인벤토리 파일> <플레이북 파일>
ansible-playbook -i inventory/inventory.ini roles/web_server.yaml

 

 

 

호스트에서 확인:

 

 

 

설치된 상태에서 다시 플레이북을 실행하면 apache 삭제됨:

 

 

 

호스트에서 확인:

 

 

 

 

 

 

 

 

반응형

'Ansible' 카테고리의 다른 글

Ansible Missing sudo password  (0) 2024.01.30
Ansible Roles ①개념(+ Ansible로 Apache 설치)  (0) 2024.01.15
Ansible.Builtin 모듈  (0) 2024.01.12
Ansible 구성요소  (0) 2024.01.11