Ansible 자동화

서버 설정 관리와 애플리케이션 배포를 자동화하는 Ansible


서버 설정 관리와 애플리케이션 배포를 자동화하는 Ansible

목표: 인프라를 코드로 관리하고 반복 작업을 자동화할 수 있는 수준


🎯 Ansible 개요

아키텍처

graph TB
    subgraph "Ansible"
        CONTROL["🎛️ Control Node"] -->|"SSH/WinRM"| NODE1["💻 Managed Node 1"]
        CONTROL -->|"SSH/WinRM"| NODE2["💻 Managed Node 2"]
        CONTROL -->|"SSH/WinRM"| NODE3["💻 Managed Node 3"]
        
        subgraph "Control Node"
            PLAYBOOK["📋 Playbook"]
            INVENTORY["📁 Inventory"]
            MODULES["🔧 Modules"]
        end
    end

특징:

  • 에이전트리스 (SSH/WinRM)
  • 선언적 설정
  • 멱등성
  • YAML 기반

🛠️ 설치

# Python 필요
pip install ansible

# 또는 OS 패키지
# Ubuntu/Debian
sudo apt-get install ansible

# CentOS/RHEL
sudo yum install ansible

# macOS
brew install ansible

# 버전 확인
ansible --version

📁 프로젝트 구조

ansible-project/
├── ansible.cfg          # Ansible 설정
├── inventory/
│   ├── production       # 프로덕션 인벤토리
│   └── staging          # 스테이징 인벤토리
├── group_vars/          # 그룹 변수
│   ├── all.yml
│   └── webservers.yml
├── host_vars/           # 호스트 변수
│   └── web01.yml
├── roles/               # 역할
│   ├── common/
│   │   ├── tasks/
│   │   ├── handlers/
│   │   ├── templates/
│   │   ├── files/
│   │   ├── vars/
│   │   └── defaults/
│   └── nginx/
└── site.yml             # 메인 플레이북

📝 인벤토리

기본 인벤토리

# inventory/production
[webservers]
web01.example.com ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa
web02.example.com ansible_user=ubuntu

[dbservers]
db01.example.com ansible_user=ubuntu

[all:vars]
ansible_python_interpreter=/usr/bin/python3
env=production

YAML 인벤토리

# inventory/production.yml
all:
  children:
    webservers:
      hosts:
        web01.example.com:
          ansible_user: ubuntu
          ansible_ssh_private_key_file: ~/.ssh/id_rsa
        web02.example.com:
          ansible_user: ubuntu
    dbservers:
      hosts:
        db01.example.com:
          ansible_user: ubuntu
  vars:
    ansible_python_interpreter: /usr/bin/python3
    env: production

동적 인벤토리

# AWS EC2
pip install boto3
ansible-inventory -i aws_ec2.yml --graph

# aws_ec2.yml
plugin: aws_ec2
regions:
  - ap-northeast-2
keyed_groups:
  - key: tags.Environment
    prefix: env
  - key: tags.Role
    prefix: role

📋 플레이북

기본 플레이북

# site.yml
---
- name: Configure web servers
  hosts: webservers
  become: yes
  vars:
    http_port: 80
    max_clients: 200
  
  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600
    
    - name: Install nginx
      apt:
        name: nginx
        state: present
    
    - name: Start nginx service
      service:
        name: nginx
        state: started
        enabled: yes
    
    - name: Copy nginx configuration
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: reload nginx
    
    - name: Create web root directory
      file:
        path: /var/www/html
        state: directory
        owner: www-data
        group: www-data
        mode: '0755'
    
    - name: Copy index.html
      copy:
        src: index.html
        dest: /var/www/html/index.html
        owner: www-data
        group: www-data
        mode: '0644'
  
  handlers:
    - name: reload nginx
      service:
        name: nginx
        state: reloaded

조건과 반복

- name: Install packages
  apt:
    name: "{{ item }}"
    state: present
  loop:
    - nginx
    - postgresql
    - redis-server
  when: ansible_os_family == "Debian"

- name: Configure users
  user:
    name: "{{ item.name }}"
    state: present
    groups: "{{ item.groups }}"
  loop:
    - { name: 'deploy', groups: 'docker' }
    - { name: 'backup', groups: 'backup' }

🎭 역할 (Roles)

역할 생성

# 역할 구조 생성
ansible-galaxy init roles/nginx

역할 구조

roles/nginx/
├── defaults/
│   └── main.yml       # 기본 변수
├── vars/
│   └── main.yml       # 변수
├── tasks/
│   └── main.yml       # 태스크
├── handlers/
│   └── main.yml       # 핸들러
├── templates/
│   └── nginx.conf.j2  # 템플릿
├── files/
│   └── index.html     # 정적 파일
└── meta/
    └── main.yml       # 의존성

역할 사용

# site.yml
---
- name: Configure all servers
  hosts: all
  become: yes
  roles:
    - common
    - docker
    - role: nginx
      vars:
        nginx_port: 8080
      when: ansible_os_family == "Debian"

🚀 실행

기본 명령어

# Ping 테스트
ansible all -i inventory/production -m ping

# 명령 실행
ansible webservers -i inventory/production -a "uptime"
ansible webservers -i inventory/production -m shell -a "df -h"

# 플레이북 실행
ansible-playbook -i inventory/production site.yml

# 특정 태그만 실행
ansible-playbook -i inventory/production site.yml --tags nginx

# 체크 모드 (실제 실행 안 함)
ansible-playbook -i inventory/production site.yml --check

# 제한 실행
ansible-playbook -i inventory/production site.yml --limit web01.example.com

병렬 실행

# 포크 수 조정 (기본 5)
ansible-playbook -i inventory/production site.yml -f 20

📋 체크리스트

  • Ansible 설치
  • 인벤토리 작성
  • 플레이북 작성
  • 역할 생성
  • 변수 사용
  • 조건과 반복
  • 핸들러
  • 템플릿
  • 동적 인벤토리
  • 체크 모드
  • 병렬 실행

🔗 관련 노트

  • 01-05-인프라코드-Terraform — IaC
  • 02-01-Jenkins-파이프라인 — CI/CD
  • 02-04-모니터링-스택 — 모니터링

마지막 업데이트: 2026-06-01