환경 기준:

  • 컨트롤 노드: Ubuntu 서버 (여기서 Ansible 실행)
  • 관리 대상 노드: Debian 서버 (여기에 Nginx + Quiz_AI 배포)

실습하면서 “쿡북에서 추천하는 Ansible 프로젝트 구조” 로 정리하고, 남이 만든 nginx role(geerlingguy.nginx) 을 내 프로젝트에 붙여본 과정까지 정리한 글입니다.


1. 목표와 전체 구조

처음 목표:

  • 원래 쓰던 Ubuntu 서버는 “관리하는 쪽(컨트롤 노드)”
  • 새로 만든 Debian 서버는 “서비스가 돌아가는 쪽(관리 대상 노드)”
  • Ansible로 Debian 서버에

    • nginx 설치
    • quiz_ai_testpro 코드 배포
    • 가상환경 세팅
    • nginx를 Quiz_AI용으로 설정 까지 한 번에 자동화하는 흐름 만들기

Ansible 관점에서 보면 구조는 이렇게 된다:

[Ubuntu 서버]  --(SSH + Ansible)-->  [Debian 서버]
   컨트롤 노드                         관리 대상 노드

2. Ansible 프로젝트 기본 디렉토리 구성

작업 디렉토리:

mkdir -p ~/ansible_deb
cd ~/ansible_deb

2.1. 디렉토리 뼈대 만들기

쿡북에서 추천하는 구조를 기준으로 폴더를 만들었다:

mkdir -p collections playbooks roles roles_galaxy
mkdir -p inventories/group_vars/all inventories/host_vars

최종 구조:

ansible_deb/
  collections/
  inventories/
    group_vars/
      all/
    host_vars/
  playbooks/
  roles/
  roles_galaxy/

3. 인벤토리 & ansible.cfg 설정

3.1. inventories/hosts.ini

관리 대상인 Debian 서버deb 그룹에 넣었다:

# inventories/hosts.ini
[deb]
DEB_SERVER_IP ansible_user=admin ansible_ssh_private_key_file=~/.ssh/deb_server.pem
  • DEB_SERVER_IP : Debian 서버 공인 IP
  • ansible_user : 그 서버에 SSH 접속할 계정 (여기선 admin)
  • ansible_ssh_private_key_file : 해당 서버 접속에 사용할 키 경로

3.2. ansible.cfg

ansible_deb 루트에 ansible.cfg 파일 생성:

[defaults]
# 기본 인벤토리 위치
inventory = ./inventories/hosts.ini

# 기본 원격 유저
remote_user = admin

gathering = smart

# roles / collections 경로
collections_path = collections
roles_path = roles_galaxy:roles

# 파이썬 자동 감지
interpreter_python = auto_silent

[ssh_connection]
pipelining = true
ssh_args = -C -o ControlMaster=yes -o ControlPersist=60s -o StrictHostKeyChecking=accept-new

이렇게 해두면:

  • ansible deb -m ping 처럼 -i inventories/...를 매번 안 써도 됨
  • roles_galaxy 에 설치한 Galaxy role도 자동으로 인식

3.3. 연결 테스트

cd ~/ansible_deb
ansible deb -m ping

성공 시 다음과 같은 로그 뜸

DEB_SERVER_IP | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

→ Ubuntu에서 Debian까지 Ansible 연결 OK


4. 내 플레이북으로 Quiz_AI 코드와 venv 세팅하기

처음에는 내가 직접 작성한 플레이북들로 기본 환경을 준비했다.

4.1. quiz_ai 코드 clone 플레이북

# playbooks/setup_quizai_code.yml
- hosts: deb
  become: yes

  vars:
    project_root: /home/admin/quiz_ai_testpro

  tasks:
    - name: git, python3-venv 설치
      apt:
        name:
          - git
          - python3-venv
        state: present
        update_cache: yes

    - name: quiz_ai_testpro 코드 가져오기 (git clone)
      become: no  # admin 유저 권한으로 clone
      git:
        repo: "https://github.com/juwon1116/quiz_ai_testpro.git"
        dest: ""
        version: main   # 사용하는 브랜치에 맞게 변경 가능
        force: yes

실행:

ansible-playbook playbooks/setup_quizai_code.yml

Debian 서버에서 확인:

ls /home/admin/quiz_ai_testpro
# README.md, requirements.txt, testpro/ ...

4.2. Django 프로젝트 루트, venv 구조

프로젝트 내부 구조:

/home/admin/quiz_ai_testpro/
  ├─ .venv/        ← 가상환경(나중에 생성)
  └─ testpro/      ← 여기 안에 manage.py, apps, static, media 등

testpro/:

cd /home/admin/quiz_ai_testpro/testpro
ls
# manage.py, requirements.txt, accounts, quiz_app, static, media ...

4.3. venv, requirements 설치 플레이북

# playbooks/setup_quizai_venv.yml
- hosts: deb
  become: yes

  vars:
    project_root: /home/admin/quiz_ai_testpro/testpro
    venv_path: /home/admin/quiz_ai_testpro/.venv

  tasks:
    - name: python3-venv 패키지 설치
      apt:
        name: python3-venv
        state: present
        update_cache: yes

    - name: 가상환경 생성 (.venv)
      command: python3 -m venv ""
      args:
        creates: "/bin/activate"

    - name: requirements 설치 (가상환경 안에서)
      pip:
        requirements: "/requirements.txt"
        virtualenv: ""
        virtualenv_python: python3

실행:

ansible-playbook playbooks/setup_quizai_venv.yml

5. Ansible Galaxy에서 nginx role 설치하기

이제 내가 직접 만든 nginx 플레이북 대신, 커뮤니티에서 만든 nginx role을 가져다 쓰는 실습을 했다.

5.1. Galaxy에서 role 설치

cd ~/ansible_deb
mkdir -p roles_galaxy  # 이미 있어도 상관 없음

ansible-galaxy role install geerlingguy.nginx -p roles_galaxy

설치 후 확인:

ls roles_galaxy
# geerlingguy.nginx

이 안에는:

  • tasks/main.yml
  • tasks/setup-Debian.yml
  • defaults/main.yml
  • templates/nginx.conf.j2

등이 들어 있고, 우리가 앞에서 내용도 일부 뜯어봤다.


5.2. 가장 단순한 형태로 role 사용해 보기

# playbooks/nginx_with_role.yml
- hosts: deb
  become: yes

  roles:
    - geerlingguy.nginx

실행:

ansible-playbook playbooks/nginx_with_role.yml
  • ok=11 changed=2 failed=0 → role이 os를 감지하고, 필요한 task만 실행해서 nginx 설치/설정 완료

이렇게 하면:

  • 더 이상 직접 apt로 nginx를 설치하는 플레이북이 없어도,
  • geerlingguy.nginx만 호출해서 nginx 설치 + 기본 설정까지 한 번에 가능.

6. nginx role + quizai용 vhost 붙이기

마지막으로, Galaxy nginx role 위에 내 quizai 서비스용 vhost 설정을 덮어써서 적용

6.1. quizai_nginx.yml

# playbooks/quizai_nginx.yml
- hosts: deb
  become: yes

  roles:
    - role: geerlingguy.nginx
      nginx_remove_default_vhost: true

      nginx_vhosts:
        - listen: "80"
          server_name: "quizai.test"   # 나중에 진짜 도메인으로 변경
          root: "/home/admin/quiz_ai_testpro/testpro/static"
          index: "index.html index.htm"

          extra_parameters: |
            location /static/ {
              alias /home/admin/quiz_ai_testpro/testpro/static/;
            }

            location /media/ {
              alias /home/admin/quiz_ai_testpro/testpro/media/;
            }

            location / {
              proxy_pass http://127.0.0.1:8000;
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header X-Forwarded-Proto $scheme;
            }

포인트:

  • nginx_remove_default_vhost: true → nginx 기본 vhost 제거 default 사이트 비활성화

  • nginx_vhosts 리스트에 quizai용 서버 블록 1개 추가

    • server_name: quizai.test 테스트용 이름
    • root: static 파일 경로
    • extra_parameters:

      • /static/, /media/alias로 정적 파일 서빙
      • /proxy_pass http://127.0.0.1:8000; 로 Django 뒤에 붙이는 reverse proxy

실행:

ansible-playbook playbooks/quizai_nginx.yml

그리고 Debian 서버에서 확인:

ssh admin@DEB_SERVER_IP
sudo nginx -t
sudo systemctl status nginx
  • 설정 테스트 성공
  • nginx 서비스 정상 active (running) 상태

까지 확인.


결론

  1. 쿡북 스타일 Ansible 프로젝트 구조 만들기
  2. Ubuntu → Debian 구조로 컨트롤/관리 노드 구분
  3. 내가 만든 플레이북으로:

    • nginx 설치
    • quiz_ai_testpro clone
    • venv + requirements 설치
  4. Ansible Galaxy nginx role을 프로젝트에 설치해서:

    • 간단한 플레이북(nginx_with_role.yml)으로 테스트
    • nginx_vhosts + extra_parameters를 이용해 quizai reverse proxy vhost 세팅

다음에 이어서 할 수 있는 것들

  • roles/quizai/ 를 만들어서
    • git pull
    • migrate
    • collectstatic
    • systemd 서비스 재시작

결론

이렇게 하면 최종 배포용 플레이북을 단순하게 만들 수 있다. playbook은 얇게, role은 두껍게 구조가 완성된다. 하지만 솔찍하게 필요 한지는 잘 모르겠은 아직은 내가 다루는 프로젝트가 적어서 그런듯