본문 바로가기
Infra2024년 9월 10일5분 읽기

Ansible 플레이북 실전 — 서버 100대 동시 설정

YS
김영삼
조회 133

Ansible 플레이북 기초

Ansible은 에이전트리스(agentless) 구조의 자동화 도구로, SSH를 통해 원격 서버를 관리합니다. 플레이북은 YAML 형식으로 인프라의 원하는 상태를 선언적으로 정의합니다.

인벤토리 구성

# inventory/production.yml
all:
  children:
    webservers:
      hosts:
        web[01:50].example.com:
      vars:
        http_port: 80
        nginx_worker_processes: auto
    dbservers:
      hosts:
        db[01:10].example.com:
      vars:
        postgresql_version: 15
    monitoring:
      hosts:
        mon[01:05].example.com:

그룹 변수와 호스트 변수

# group_vars/webservers.yml
---
nginx_version: "1.24"
ssl_certificate: /etc/ssl/certs/wildcard.pem
ssl_key: /etc/ssl/private/wildcard.key
deploy_user: deploy
app_root: /var/www/app

# host_vars/web01.example.com.yml
---
is_primary: true
upstream_weight: 5

실전 플레이북: 웹서버 설정

# playbooks/setup-webservers.yml
---
- name: Configure web servers
  hosts: webservers
  become: yes
  serial: 10        # 10대씩 순차 배포
  max_fail_percentage: 20

  pre_tasks:
    - name: Remove from load balancer
      uri:
        url: "http://lb.example.com/api/remove/{{ inventory_hostname }}"
        method: POST
      delegate_to: localhost

  roles:
    - common
    - nginx
    - app-deploy

  post_tasks:
    - name: Add back to load balancer
      uri:
        url: "http://lb.example.com/api/add/{{ inventory_hostname }}"
        method: POST
      delegate_to: localhost

  handlers:
    - name: restart nginx
      service:
        name: nginx
        state: restarted

롤(Role) 구조

# roles/nginx/tasks/main.yml
---
- name: Install Nginx
  apt:
    name: "nginx={{ nginx_version }}*"
    state: present
    update_cache: yes
  notify: restart nginx

- name: Deploy Nginx config
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    validate: "nginx -t -c %s"
  notify: restart nginx

- name: Enable and start Nginx
  service:
    name: nginx
    state: started
    enabled: yes

성능 최적화 전략

설정기본값권장값효과
forks550동시 실행 호스트 수
pipeliningFalseTrueSSH 연결 횟수 감소
gatheringimplicitsmart팩트 수집 캐싱
strategylinearfree빠른 호스트 먼저 진행
# ansible.cfg
[defaults]
forks = 50
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_facts
fact_caching_timeout = 3600

[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=60s

에러 처리와 디버깅

  • serialmax_fail_percentage로 롤링 업데이트 중 장애 전파를 방지합니다
  • --check 모드로 실제 변경 없이 시뮬레이션할 수 있습니다
  • block/rescue/always 구문으로 태스크 실패 시 복구 로직을 구현합니다
  • Ansible Vault로 비밀번호, API 키 등 민감 정보를 암호화하여 관리합니다
  • callback_plugins를 활용하면 실행 결과를 Slack, 이메일 등으로 알림할 수 있습니다

댓글 0

아직 댓글이 없습니다.
Ctrl+Enter로 등록