Ansible로 PostgreSQL 운영 자동화 예제
Ansible을 활용해 PostgreSQL 설치, 설정, 서비스 관리까지 자동화하는 실무형 플레이북과 역할 구조를 설명하는 구현 예제
목차
목표와 개요
이 글은 Ansible로 PostgreSQL을 안정적으로 배포하고 운영 자동화를 구현하는 방법을 단계별로 정리한다. 대상은 Ansible과 기본 Linux 명령에 익숙한 운영자이며, 처음 접하는 사람도 이해할 수 있도록 구조와 핵심 요소를 차근히 설명한다. 주요 키워드는 ansible postgres 배포, postgres 자동화 playbook, ansible role postgres 예제다.
필요한 준비물
- 관리자 권한이 있는 제어 노드(Ansible 설치된 머신)
- SSH로 접속 가능한 대상 노드(배포 대상 서버)
- 대상 노드에서 sudo 권한을 사용할 수 있는 계정
- 기본적인 Ansible inventory와 Python 환경
구성 원칙
역할(Role) 기반으로 분리하면 재사용성과 유지보수가 쉬워진다. 다음 원칙을 따른다.
- tasks는 설치와 설정을 분리
- templates로 설정 파일 관리
- handlers로 서비스 재시작 처리
- 변수는 defaults와 vars로 계층 관리
역할 구조 예시
권장되는 디렉터리 구조는 다음과 같다. 이 구조를 기준으로 예제 파일을 제공한다.
roles/
postgres/
tasks/
main.yml
install.yml
configure.yml
handlers/
main.yml
templates/
postgresql.conf.j2
pg_hba.conf.j2
defaults/
main.yml
vars/
main.yml
간단한 플레이북
아래 플레이북은 inventory에 있는 db 서버 그룹에 postgres 역할을 적용한다. 이해를 돕기 위해 최소 구성만 포함한다.
- name: PostgreSQL 배포
hosts: db
become: true
roles:
- role: postgres
설치 tasks (roles/postgres/tasks/install.yml)
- name: PostgreSQL 패키지 설치
apt:
name: ['postgresql','postgresql-contrib']
state: present
update_cache: yes
when: ansible_os_family == 'Debian'
- name: PostgreSQL 패키지 설치 (RedHat)
yum:
name: ['postgresql-server','postgresql-contrib']
state: present
when: ansible_os_family == 'RedHat'
설정 tasks (roles/postgres/tasks/configure.yml)
- name: postgresql.conf 배포
template:
src: postgresql.conf.j2
dest: /etc/postgresql/12/main/postgresql.conf
owner: postgres
group: postgres
mode: '0644'
notify: Restart PostgreSQL
- name: pg_hba.conf 배포
template:
src: pg_hba.conf.j2
dest: /etc/postgresql/12/main/pg_hba.conf
owner: postgres
group: postgres
mode: '0640'
notify: Reload PostgreSQL
핸들러 (roles/postgres/handlers/main.yml)
- name: Restart PostgreSQL
service:
name: postgresql
state: restarted
- name: Reload PostgreSQL
service:
name: postgresql
state: reloaded
템플릿 예시
postgresql.conf와 pg_hba.conf는 환경별 변수로 제어한다. 주요 설정만 예로 든다.
# roles/postgres/templates/postgresql.conf.j2
# listen_addresses는 호스트 변수로 제어
listen_addresses = '{{ postgres_listen | default("'*'") }}'
port = {{ postgres_port | default(5432) }}
max_connections = {{ postgres_max_connections | default(100) }}
변수와 보안 고려사항
민감한 비밀번호는 Ansible Vault로 관리한다. 기본 값은 roles/postgres/defaults/main.yml에 두고, 환경별 오버라이드로 vars나 group_vars를 이용한다. 데이터 디렉터리 권한과 SELinux 설정도 배포 전 점검한다.
배포와 검증 순서
- 1) inventory와 group_vars 검토
- 2) 테스트 환경에서 플레이북 실행
- 3) 서비스 기동 상태와 포트 리스닝 확인
- 4) 간단한 쿼리로 DB 연결 검증
- 5) 운영 반영 전 백업 정책 확인
결론
Role 기반으로 Ansible 플레이북을 구성하면 PostgreSQL 배포와 운영 자동화가 명확해진다. 위 예제는 기본 뼈대를 제공하며, 실제 환경에서는 모니터링, 백업, 복제 설정을 추가하면 운영 안정성이 높아진다. 시작은 간단한 역할로, 필요에 따라 점진적으로 확장하는 방식을 추천한다.