샘플 Ansible 설정
샘플 Ansible 설정 (Sample Ansible setup)
플레이북, 인벤토리, 롤, 변수에 대해 배웠어요. 이 섹션에서는 그 모든 요소를 합쳐 웹 서비스를 자동화하는 샘플 설정을 정리해요.
샘플 설정은 플레이북, 롤, 인벤토리, 변수 파일을 기능별로 정리해요. 플레이·작업 수준의 태그(tags)는 더 세밀한 제어 범위를 제공하죠. 이 방식은 강력하고 유연하지만, Ansible 콘텐츠를 조직하는 다른 방법도 있어요. 여러분의 Ansible 사용은 여러분의 필요에 맞아야 하므로, 이 방식을 수정하고 콘텐츠를 그에 맞게 정리해도 좋아요.
출처: 문서
본문
샘플 디렉터리 레이아웃 (Sample directory layout)
이 레이아웃은 대부분의 작업을 롤에 정리하고, 각 환경에 하나의 인벤토리 파일을 두며, 상위 디렉터리에 몇 개의 플레이북을 둬요:
production # inventory file for production servers
staging # inventory file for staging environment
group_vars/
group1.yml # here we assign variables to particular groups
group2.yml
host_vars/
hostname1.yml # here we assign variables to particular systems
hostname2.yml
library/ # if any custom modules, put them here (optional)
module_utils/ # if any custom module_utils to support modules, put them here (optional)
filter_plugins/ # if any custom filter plugins, put them here (optional)
site.yml # main playbook
webservers.yml # playbook for webserver tier
dbservers.yml # playbook for dbserver tier
tasks/ # task files included from playbooks
webservers-extra.yml # <-- avoids confusing playbook with task files
roles/
common/ # this hierarchy represents a "role"
tasks/ #
main.yml # <-- tasks file can include smaller files if warranted
handlers/ #
main.yml # <-- handlers file
templates/ # <-- files for use with the template resource
ntp.conf.j2 # <------- templates end in .j2
files/ #
bar.txt # <-- files for use with the copy resource
foo.sh # <-- script files for use with the script resource
vars/ #
main.yml # <-- variables associated with this role
defaults/ #
main.yml # <-- default lower priority variables for this role
meta/ #
main.yml # <-- role dependencies and optional Galaxy info
library/ # roles can also include custom modules
module_utils/ # roles can also include custom module_utils
lookup_plugins/ # or other types of plugins, like lookup in this case
webtier/ # same kind of structure as "common" was above, done for the webtier role
monitoring/ # ""
fooapp/ # ""
참고: 기본적으로 Ansible은 플레이북이 한 디렉터리에 저장되고 롤은
roles/라는 하위 디렉터리에 저장된다고 가정해요. 자동화할 작업이 더 많아지면 플레이북을playbooks/라는 하위 디렉터리로 옮기는 것을 고려할 수 있어요. 그렇게 하면ansible.cfg파일의roles_path설정으로roles/디렉터리 경로를 구성해야 해요.
대안 디렉터리 레이아웃 (Alternative directory layout)
각 인벤토리 파일을 해당 group_vars/host_vars와 함께 별도 디렉터리에 둘 수도 있어요. 특히 환경마다 group_vars/host_vars가 공통되는 부분이 많지 않을 때 유용해요. 레이아웃은 다음 예시처럼 보일 수 있어요:
inventories/
production/
hosts # inventory file for production servers
group_vars/
group1.yml # here we assign variables to particular groups
group2.yml
host_vars/
hostname1.yml # here we assign variables to particular systems
hostname2.yml
staging/
hosts # inventory file for staging environment
group_vars/
group1.yml # here we assign variables to particular groups
group2.yml
host_vars/
stagehost1.yml # here we assign variables to particular systems
stagehost2.yml
library/
module_utils/
filter_plugins/
site.yml
webservers.yml
dbservers.yml
roles/
common/
webtier/
monitoring/
fooapp/
이 레이아웃은 더 큰 환경에서 더 많은 유연성을 주고, 서로 다른 환경 간 인벤토리 변수를 완전히 분리해 줘요. 하지만 파일이 더 많아져 유지하기가 더 어려워요. 그룹·호스트 변수 정리에 대한 자세한 내용은 "Organizing host and group variables"를 참고하세요.
샘플 그룹·호스트 변수 (Sample group and host variables)
변수가 담긴 이 샘플 그룹·호스트 파일들은 각 머신 또는 머신 그룹에 적용되는 값을 담아요. 예를 들어 애틀랜타의 데이터센터는 자체 NTP 서버가 있어요. 그래서 ntp.conf 파일을 설정할 때 이 예제처럼 유사한 코드를 쓸 수 있어요:
---
# file: group_vars/atlanta
ntp: ntp-atlanta.example.com
backup: backup-atlanta.example.com
마찬가지로 webservers 그룹의 호스트들은 데이터베이스 서버에는 적용되지 않는 일부 설정이 있어요:
---
# file: group_vars/webservers
apacheMaxRequestsPerChild: 3000
apacheMaxClients: 900
기본값이나 보편적으로 참인 값은 group_vars/all이라는 파일에 넣어요:
---
# file: group_vars/all
ntp: ntp-boston.example.com
backup: backup-boston.example.com
필요하면 host_vars 디렉터리의 시스템에 특정한 하드웨어 차이를 정의할 수 있어요:
---
# file: host_vars/db-bos-1.example.com
foo_agent_port: 86
bar_agent_port: 99
동적 인벤토리를 사용하면 Ansible이 많은 동적 그룹을 자동으로 만들어요. 그 결과 class:webserver 같은 태그는 group_vars/ec2_tag_class_webserver 파일에서 변수를 자동으로 불러와요.
참고:
hostvars라는 특별한 변수로 호스트 변수에 접근할 수 있어요. 이 변수 목록은 "Special Variables"를 참고하세요.hostvars변수는 호스트별 변수에만 접근할 수 있고 그룹 변수에는 접근할 수 없어요.
기능별로 정리된 샘플 플레이북 (Sample playbooks organized by function)
이 설정으로 단일 플레이북이 전체 인프라를 정의할 수 있어요. site.yml 플레이북은 다른 두 플레이북을 가져와요. 하나는 웹 서버용, 하나는 데이터베이스 서버용이에요:
---
# file: site.yml
- import_playbook: webservers.yml
- import_playbook: dbservers.yml
webservers.yml 플레이북도 상위 레벨에 있으며, webservers 그룹의 구성을 webservers 그룹과 관련된 롤에 매핑해요:
---
# file: webservers.yml
- hosts: webservers
roles:
- common
- webtier
이 설정으로 site.yml을 실행하면 전체 인프라를 구성할 수 있어요. 대안으로 인프라의 일부만 구성하려면 webservers.yml을 실행해요. 이는 Ansible의 --limit 파라미터와 비슷하지만 조금 더 명시적이에요:
ansible-playbook site.yml --limit webservers
ansible-playbook webservers.yml
기능 기반 롤의 샘플 작업·핸들러 파일 (Sample task and handler files in a function-based role)
Ansible은 롤 하위 디렉터리에서 main.yml이라는 어떤 파일이든 로드해요. 이 샘플 tasks/main.yml 파일은 NTP를 구성해요:
---
# file: roles/common/tasks/main.yml
- name: be sure ntp is installed
yum:
name: ntp
state: present
tags: ntp
- name: be sure ntp is configured
template:
src: ntp.conf.j2
dest: /etc/ntp.conf
notify:
- restart ntpd
tags: ntp
- name: be sure ntpd is running and enabled
ansible.builtin.service:
name: ntpd
state: started
enabled: true
tags: ntp
여기 핸들러 파일 예시가 있어요. 핸들러는 특정 작업이 변경을 보고할 때만 트리거돼요. 핸들러는 각 플레이의 끝에서 실행돼요:
---
# file: roles/common/handlers/main.yml
- name: restart ntpd
ansible.builtin.service:
name: ntpd
state: restarted
자세한 내용은 Roles 문서를 참고하세요.
샘플 설정으로 가능한 것 (What the sample setup enables)
위에서 설명한 기본 조직 구조는 많은 자동화 옵션을 가능하게 해요. 전체 인프라를 재구성하려면:
ansible-playbook -i production site.yml
모든 곳의 NTP를 재구성하려면:
ansible-playbook -i production site.yml --tags ntp
웹 서버만 재구성하려면:
ansible-playbook -i production webservers.yml
보스턴의 웹 서버만 재구성하려면:
ansible-playbook -i production webservers.yml --limit boston
보스턴의 첫 10개 웹 서버만, 그리고 다음 10개를 재구성하려면:
ansible-playbook -i production webservers.yml --limit boston[0:9]
ansible-playbook -i production webservers.yml --limit boston[10:19]
샘플 설정은 기본적인 ad hoc 명령도 지원해요:
ansible boston -i production -m ping
ansible boston -i production -m command -a '/sbin/reboot'
특정 Ansible 명령으로 어떤 작업이 실행되거나 어떤 호스트 이름이 영향을 받을지 확인하려면:
# confirm what task names would be run if I ran this command and said "just ntp tasks"
ansible-playbook -i production webservers.yml --tags ntp --list-tasks
# confirm what hostnames might be communicated with if I said "limit to boston"
ansible-playbook -i production webservers.yml --limit boston --list-hosts
배포 또는 구성을 위한 정리 (Organizing for deployment or configuration)
샘플 설정은 전형적인 구성 토폴로지를 보여줘요. 다중 티어 배포를 할 때는 어플리케이션을 배포하기 위해 티어 사이를 오가는 추가 플레이북이 필요할 가능성이 높아요. 이 경우 site.yml을 deploy_exampledotcom.yml 같은 플레이북으로 확장할 수 있어요. 다만 일반적인 개념은 여전히 적용돼요. Ansible로 같은 유틸리티를 사용해 배포와 구성을 모두 할 수 있어요. 따라서 그룹을 재사용하고, 어플리케이션 배포와 별개로 OS 구성을 별도의 플레이북이나 롤에 유지할 가능성이 높아요.
'플레이북'을 스포츠 은유로 생각해 보세요 — 모든 인프라에 사용할 수 있는 한 세트의 플레이가 있고, 시간과 목적에 따라 사용하는 상황별 플레이가 있는 거예요.
로컬 Ansible 모듈 사용하기 (Using local Ansible modules)
플레이북의 YAML 파일을 기준으로 ./library 디렉터리가 있다면, 이 디렉터리를 사용해 Ansible 모듈을 모듈 경로에 자동으로 추가할 수 있어요. 이렇게 하면 모듈을 플레이북과 함께 정리할 수 있어요. 예를 들어 이 섹션 시작 부분의 디렉터리 구조를 참고하세요.
더 알아보기 (Learn more)
- 기능별 그룹·롤, 환경별 인벤토리, 역할 분담된 작업·핸들러가 이 샘플 설정의 핵심이에요.
--tags,--limit,--list-tasks,--list-hosts로 실행 범위를 정밀하게 제어할 수 있어요../library디렉터리로 커스텀 모듈을 플레이북과 함께 사용할 수 있어요.