ez_docker/plugins/module_utils/service/mariadb.py
2024-12-11 18:42:59 +01:00

90 lines
2.4 KiB
Python

# Copyright: (c) 2024, Luca Bilke <luca@bil.ke>
# MIT License (see LICENSE)
from __future__ import annotations
import shlex
from typing import TYPE_CHECKING
from ansible_collections.snailed.ez_compose.plugins.module_utils.service import common as service
if TYPE_CHECKING:
from ansible_collections.snailed.ez_compose.plugins.module_utils.common import State
def helper(state: State) -> State:
backup = state.module.params.get("backup", True)
database = state.module.params["database"]
username = state.module.params["username"]
password = state.module.params["password"]
root_password = state.module.params["root_password"]
service_name = state.module.params["name"]
project_name = state.module.params["project_name"]
volumes = [
{
"source": service_name,
"target": "/var/lib/mysql",
"type": "volume",
},
]
environment = {
"MARIADB_DATABASE": database,
"MARIADB_USER": username,
"MARIADB_PASSWORD": password,
}
labels: dict[str, str] = {}
if root_password:
environment.update(
{
"MARIADB_ROOT_PASSWORD": root_password,
},
)
if backup:
labels.update(
{
"docker-volume-backup.archive-pre": (
"/bin/sh -c '"
"mysqldump --all-databases "
f"-u {shlex.quote(username)} "
f"-p {shlex.quote(password)} "
f">/backup/{shlex.quote(project_name)}.sql"
"'"
),
},
)
# mysqldump -psecret --all-databases > /tmp/dumps/dump.sql
volumes.append(
{
"type": "volume",
"source": f"{service_name}_backup",
"target": "/backup",
},
)
update = {
"environment": environment,
"volumes": volumes,
"labels": labels,
}
return service.update(state, update)
def main():
extra_args = {
"archive": {"type": "bool"},
"database": {"type": "str", "required": True},
"username": {"type": "str", "required": True},
"password": {"type": "str", "required": True},
"root_password": {"type": "str"},
}
service.run(extra_args, helper)
if __name__ == "__main__":
main()