100 lines
2.5 KiB
Python
100 lines
2.5 KiB
Python
# Copyright: (c) 2025, Luca Bilke <luca@bil.ke>
|
|
# MIT License (see LICENSE)
|
|
|
|
from __future__ import annotations
|
|
|
|
import shlex
|
|
from typing import TYPE_CHECKING, Any
|
|
|
|
if TYPE_CHECKING:
|
|
from ansible_collections.snailed.ez_docker.plugins.module_utils.models import State
|
|
|
|
EXTRA_ARGS = {
|
|
"backup": {"type": "bool", "default": True},
|
|
"database": {"type": "str", "required": True},
|
|
"username": {"type": "str", "required": True},
|
|
"password": {"type": "str", "required": True},
|
|
}
|
|
|
|
DOCUMENTATION = """
|
|
postgres:
|
|
description:
|
|
- Configuration for postgres service.
|
|
type: list
|
|
elements: dict
|
|
suboptions:
|
|
backup:
|
|
description:
|
|
- If true, add labels for the docker volume backupper.
|
|
type: bool
|
|
default: true
|
|
database:
|
|
description:
|
|
- Name of database.
|
|
type: str
|
|
required: true
|
|
username:
|
|
description:
|
|
- Username for database.
|
|
type: str
|
|
required: true
|
|
password:
|
|
description:
|
|
- Password for database.
|
|
type: str
|
|
required: true
|
|
"""
|
|
|
|
|
|
def helper(state: State, params: dict[str, Any]) -> dict[str, Any]:
|
|
project_name: str = state.params["name"]
|
|
backup: bool = params["backup"]
|
|
database: str = params["database"]
|
|
username: str = params["username"]
|
|
password: str = params["password"]
|
|
service_name: str = params["name"]
|
|
|
|
volumes = [
|
|
{
|
|
"source": service_name,
|
|
"target": "/var/lib/postgresql/data",
|
|
"type": "volume",
|
|
},
|
|
]
|
|
|
|
environment = {
|
|
"POSTGRES_DB": database,
|
|
"POSTGRES_USER": username,
|
|
"POSTGRES_PASSWORD": password,
|
|
}
|
|
|
|
labels: dict[str, str] = {}
|
|
|
|
if backup:
|
|
labels.update(
|
|
{
|
|
"docker-volume-backup.archive-pre": (
|
|
"/bin/sh -c '"
|
|
f"PGPASSWORD={shlex.quote(password)} "
|
|
"pg_dumpall "
|
|
f"-U {shlex.quote(username)} "
|
|
f"-f /backup/{shlex.quote(project_name)}.sql"
|
|
"'"
|
|
),
|
|
},
|
|
)
|
|
|
|
volumes.append(
|
|
{
|
|
"type": "volume",
|
|
"source": f"{service_name}_backup",
|
|
"target": "/backup",
|
|
},
|
|
)
|
|
|
|
return {
|
|
"environment": environment,
|
|
"volumes": volumes,
|
|
"labels": labels,
|
|
"networks": {"internal": {}},
|
|
}
|