ez_docker/plugins/module_utils/service/docker_volume_backupper.py
2025-01-20 18:13:02 +01:00

88 lines
2.5 KiB
Python

# Copyright: (c) 2025, Luca Bilke <luca@bil.ke>
# MIT License (see LICENSE)
from __future__ import annotations
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from ansible_collections.snailed.ez_docker.plugins.module_utils.models import State
EXTRA_ARGS = {
"archive": {"type": "path"},
"backup_volumes": {"type": "list", "elements": "str", "required": True},
"docker_socket_proxy": {"type": "str"},
}
DOCUMENTATION = """
docker_volume_backupper:
description:
- Configuration for docker_volume_backupper service.
type: list
elements: dict
suboptions:
archive:
description:
- Directory to store backups in.
type: path
backup_volumes:
description:
- List of volume names of volumes to backup.
type: list
elements: str
required: true
docker_socket_proxy:
description:
- Hostname of a docker socket proxy to use.
type: str
"""
def helper(state: State, params: dict[str, Any]) -> dict[str, Any]:
project_name: str = state.params["name"]
archive: str | None = params.get("archive")
backup_volumes: list[str] | None = params["backup_volumes"]
socket_proxy: str | None = params.get("docker_socket_proxy")
volumes: list[dict[str, Any]] = [
{
"type": "volume",
"source": volume,
"target": f"/backup/{volume}",
"read_only": True,
}
for volume in (backup_volumes or [])
]
environment = {
"BACKUP_FILENAME": f"{project_name}-%Y-%m-%dT%H-%M-%S.{'{{ .Extension }}'}",
"BACKUP_LATEST_SYMLINK": f"{project_name}-latest",
"BACKUP_PRUNING_PREFIX": f"{project_name}-",
"BACKUP_STOP_DURING_BACKUP_LABEL": project_name,
}
if socket_proxy:
environment["DOCKER_HOST"] = f"tcp://{socket_proxy}:2375"
else:
volumes.append(
{
"type": "bind",
"source": "/var/run/docker.sock",
"target": "/var/run/docker.sock",
"read_only": False,
},
)
if archive:
environment["BACKUP_ARCHIVE"] = "/archive"
volumes.append(
{
"type": "bind",
"source": f"{archive}/{project_name}",
"target": "/archive",
"bind": {"create_host_path": True},
},
)
return {"environment": environment, "volumes": volumes, "networks": {"internal": {}}}