0

Cài đặt PostgreSQL 16 bằng Ansible (và tùy chỉnh cấu hình)

Cần tự động hóa việc cài đặt PostgreSQL 16 và đảm bảo nó sử dụng đúng các tệp postgresql.confpg_hba.conf của bạn? Đây là cách thiết lập như một lập trình viên đã quá mệt mỏi với sshvim.

Cấu trúc thư mục

Chúng ta sẽ sử dụng cấu trúc role điển hình của Ansible. Thư mục roles/db của bạn sẽ trông như sau:

roles/db/
├── tasks/
│   ├── main.yml
│   └── install_postgres.yml
├── templates/
│   ├── pg_hba.conf.j2
│   └── postgresql.conf.j2

Tệp Inventory

Ví dụ hosts.ini:

[db]
my-postgres-host ansible_host=192.168.0.10 ansible_user=ubuntu

db.yml (Entry point)

- name: Setup PostgreSQL
  hosts: db
  become: yes
  roles:
    - db

roles/db/tasks/main.yml

---
- include_tasks: install_postgres.yml

roles/db/tasks/install_postgres.yml

---
- name: Update apt cache
  apt:
    update_cache: yes

- name: Install postgresql-common
  apt:
    name: postgresql-common
    state: present

- name: Run pgdg script
  command: /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh
  args:
    creates: /etc/apt/sources.list.d/pgdg.list

- name: Update apt cache after adding PGDG
  apt:
    update_cache: yes

- name: Install PostgreSQL 16 and contrib
  apt:
    name:
      - postgresql-16
      - postgresql-contrib-16
    state: present

- name: Set custom postgresql.conf
  template:
    src: postgresql.conf.j2
    dest: /etc/postgresql/16/main/postgresql.conf
    owner: postgres
    group: postgres
    mode: 0644
  notify: Restart PostgreSQL

- name: Set custom pg_hba.conf
  template:
    src: pg_hba.conf.j2
    dest: /etc/postgresql/16/main/pg_hba.conf
    owner: postgres
    group: postgres
    mode: 0640
  notify: Restart PostgreSQL

roles/db/handlers/main.yml

---
- name: Restart PostgreSQL
  service:
    name: postgresql
    state: restarted

roles/db/templates/postgresql.conf.j2

Cấu hình hoạt động tối thiểu (có thể tùy chỉnh thêm):

listen_addresses = '*'
port = 5432
max_connections = 100
shared_buffers = 128MB
logging_collector = on
log_directory = 'log'
log_filename = 'postgresql.log'

roles/db/templates/pg_hba.conf.j2

Cho phép truy cập cục bộ và truy cập từ xa dùng mật khẩu:

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             all                                     peer
host    all             all             127.0.0.1/32            md5
host    all             all             0.0.0.0/0               md5

Chạy Playbook

ansible-playbook -i hosts.ini db.yml

Mẹo bổ sung

Để đặt lại mật khẩu cho user postgres sau khi cài đặt:

- name: Set postgres user password
  become_user: postgres
  shell: psql -c "ALTER USER postgres WITH PASSWORD '{{ postgres_password }}';"

Khai báo postgres_password trong roles/db/vars/main.yml.

Vậy là xong — hạ tầng của bạn giờ đây sẽ tự động cài đặt PostgreSQL 16 với cấu hình được thiết lập theo yêu cầu cụ thể.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí