如何通过 Ansible Playbook 和 postgresql_db 模块自动化备份 PostgreSQL 中的“testdb”数据库?

备份 PostgreSQL 数据库

Ansible 模块:community.postgresql.postgresql_db

community.postgresql.postgresql_db 是 Ansible 社区维护的 PostgreSQL 模块集合的一部分,用于在远程主机上添加或删除 PostgreSQL 数据库。 该模块需要 Ansible Core 2.11 或更高版本,不支持早期版本(如 2.9 或 2.10)。

主要参数:

  • name(字符串):数据库的名称。
  • state(字符串):present(创建)、absent(删除)、dump(备份)、restore(恢复)或 rename(重命名)。
  • target(字符串):备份文件的目标路径。
  • target_opts(字符串):备份文件的选项,例如压缩格式(如 .gz)。

该模块依赖于 Python 的 PostgreSQL 库 psycopg2,因此在使用此模块之前,必须确保目标主机上已安装 python3-psycopg2。

示例:通过 Ansible Playbook 备份 PostgreSQL 数据库

接下来,我们将通过一个实际的 Ansible Playbook 将当前 PostgreSQL 服务器中的 testdb 数据库备份到 /backups 文件夹中。

Ansible Playbook 示例代码:

---
- name: PostgreSQL 示例
  hosts: all
  become: true
  vars:
    db_name: testdb
    backup_dir: "/backups"

  tasks:
    - name: 确保 psycopg2 工具已安装
      ansible.builtin.package:
        name: python3-psycopg2
        state: present

    - name: 创建备份目录
      ansible.builtin.file:
        path: "{{ backup_dir }}"
        mode: 0777
        owner: postgres
        state: directory

    - name: 备份数据库
      community.postgresql.postgresql_db:
        state: dump
        name: "{{ db_name }}"
        target: "{{ backup_dir }}/{{ db_name }}.gz"
      become: true
      become_user: postgres

执行过程:

$ ansible-playbook -i virtualmachines/demo/inventory postgresql/db_backup.yml
PLAY [postgresql 示例] ******************************************************
TASK [收集主机信息] ******************************************************
ok: [demo.example.com]
TASK [确保 psycopg2 工具已安装] ******************************************************
ok: [demo.example.com]
TASK [创建备份目录] ******************************************************
changed: [demo.example.com]
TASK [备份数据库] ******************************************************
changed: [demo.example.com]
PLAY RECAP *******************************************************************
demo.example.com           : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

幂等性测试(部分):

$ ansible-playbook -i virtualmachines/demo/inventory postgresql/db_backup.yml
PLAY [postgresql 示例] ******************************************************
TASK [收集主机信息] ******************************************************
ok: [demo.example.com]
TASK [确保 psycopg2 工具已安装] ******************************************************
ok: [demo.example.com]
TASK [创建备份目录] ******************************************************
ok: [demo.example.com]
TASK [备份数据库] ******************************************************
changed: [demo.example.com]
PLAY RECAP *******************************************************************
demo.example.com           : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

说明:

  1. 备份目录:如果备份目录已存在,任务将不会改变状态(幂等性)。
  2. 备份文件:每次执行备份任务时,都会生成一个新的备份文件。因此,changed 状态可能会一直为 true,除非备份文件未发生变化。

执行前的环境状态:

数据库 testdb 包含一个表 example,其中有一条记录。

$ ssh devops@demo.example.com
Last login: Mon Jun 13 11:29:28 2022 from 192.168.178.26
[devops@demo ~]$ sudo su
[root@demo devops]# su - postgres
Last login: Fri Jun 10 16:50:48 UTC 2022 on pts/0
[postgres@demo ~]$ psql testdb
psql (10.21)
Type "help" for help.
testdb=# \dt
           List of relations
 Schema |  Name   | Type  |  Owner   
--------+---------+-------+----------
 public | example | table | postgres
(1 row)
testdb=# select * from example;
      message     
-----------------
 Ansible managed
(1 row)
testdb=# \q
[postgres@demo ~]$

执行后的环境状态:

备份文件已生成在 /backups 文件夹中。

$ ssh devops@demo.example.com
Last login: Mon Jun 13 11:37:13 2022 from 192.168.178.26
[devops@demo ~]$ sudo su
[root@demo devops]# ls -al /backups/
total 4
drwxrwxrwx.  2 postgres root      23 Jun 13 11:36 .
dr-xr-xr-x. 18 root     root     239 Jun 13 11:36 ..
-rw-r--r--.  1 postgres postgres 583 Jun 13 11:37 testdb.gz
[root@demo devops]# zcat /backups/testdb.gz 
--
-- PostgreSQL database dump
--
-- Dumped from database version 10.21
-- Dumped by pg_dump version 10.21
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: 
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: 
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: example; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.example (
    message character varying(255) NOT NULL
);
ALTER TABLE public.example OWNER TO postgres;
--
-- Data for Name: example; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.example (message) FROM stdin;
Ansible managed
\.
--
-- PostgreSQL database dump complete
--

通过上述操作,我们成功地使用 Ansible 将 PostgreSQL 数据库 testdb 备份为压缩文件 /backups/testdb.gz。