1. Ansible Playbook
- 자동화 작업을 정의하고 실행하는 방법을 제공하는 YAML 파일
- 여러 호스트에 걸쳐 복잡한 작업 실행
- 구조화되고 유연한 자동화 시나리오 지원
1.1 주요 개념
- 플레이(Play)
- 여러 개의 "플레이"(play)
- 각 플레이는 특정 호스트에 대한 작업을 정의
- 한 플레이에서 여러 작업을 순서대로 실행
- 태스크(Task)
- 각 플레이는 여러 개의 태스크로 구성
- 실제로 실행될 작업
- 특정 Ansible 모듈을 호출
- 각 호스트에서 순차적으로 실행되며, 상태를 변경하는 작업 포함 가능태스
- 핸들러(Handlers)
- 특정 조건이 충족될 때만 실행
1.2 Playbook + Handlers
---
- name: Web server setup
hosts: webservers
become: yes
tasks:
- name: Install Apache
apt:
name: apache2
state: present
- name: Modify Apache config
copy:
src: /local/path/to/config
dest: /etc/apache2/apache2.conf
notify: Restart Apache
handlers:
- name: Restart Apache
service:
name: apache2
state: restarted
name: 플레이 이름hosts: 호스트 그룹 정의, 그룹에 속한 모든 서버에서 작업이 실행됨become: (yes인 경우, 권한 상승이 필요하다는 뜻) sudo 사용 여부tasks: 실행할 작업 목록name: 태스크의 이름
notify: 핸들러 호출
1.3 멱등성 확인 : host 추가 playbook
nano first-playbook.yml
- /etc/ansible/hosts 파일에 새로운 host를 등록하는 yml
- 호스트 주소가 localhost이니 자신 내부에서 실행하여 해당 파일이 생긴다
---
- name: Add an ansible hosts
hosts: localhost
tasks:
- name: Add a ansible hosts
blockinfile:
path: /etc/ansible/hosts
block: |
[newtarget]
192.168.0.52
- 실행하기
sudo ansible-playbook first-playbook.yml
- newtarget 그룹이 추가 되었는 지 확인
cat /etc/ansible/hosts

→ 실행을 몇번 반복해도 newtarget 그룹이 하나만 추가
1.4 파일 전송 playbook
- 아까 만든 hello.txt를 다시 보낼 거라 타겟 서버의 hello.txt는 삭제해둡시다~
nano second-playbook.yml
- target 그룹에 hello.txt를 보낸다는 yml
- name: Ansible Copy Example to target
hosts: target
tasks:
- name: copy file with playbook
copy:
src: ~/hello.txt
dest: /home/ubuntu/tmp
owner: ubuntu
mode: 0644
- 실행하기
sudo ansible-playbook second-playbook.yml
- 권한 오류

- 해결법
ansible-playbook second-playbook.yml
사유: 공개키가 ubuntu 계정만을 타겟으로 잡아서 안되는 경우가 있음

1.5 미션!

- 특정 폴더 : /home/ubuntu/ny
- download_file.yml
---
- name: Copy ny.txt to /home/ubuntu/ny
hosts: target
become: yes
tasks:
- name: Ensure target directory exists
file:
path: /home/ubuntu/ny
state: directory
mode: '0755'
- name: Copy ny.txt to the target directory
copy:
src: /home/ubuntu/ny.txt
dest: /home/ubuntu/ny/ny.txt
mode: '0644'
- 실행
ansible-playbook download_file.yml

- 성공!


'IaC👩💻 > Ansible' 카테고리의 다른 글
| [Ansible] Galaxy (0) | 2024.08.23 |
|---|---|
| [Ansible] 모듈 (0) | 2024.08.23 |
| [Ansible] 개요 및 설치 (0) | 2024.08.23 |