79 lines
2.2 KiB
Python
79 lines
2.2 KiB
Python
# Copyright: (c) 2024, Luca Bilke <luca@bil.ke>
|
|
# MIT License (see LICENSE)
|
|
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
from dataclasses import replace
|
|
from typing import TYPE_CHECKING, Any, Callable
|
|
|
|
from ansible_collections.ssnailed.ez_compose.plugins.module_utils.common import (
|
|
recursive_update,
|
|
update_project,
|
|
)
|
|
|
|
if TYPE_CHECKING:
|
|
from ansible_collections.ssnailed.ez_compose.plugins.module_utils.common import (
|
|
State,
|
|
)
|
|
|
|
BASE_ARGS: dict[str, Any] = {
|
|
"name": {"type": "str", "required": True},
|
|
"image": {"type": "str", "required": True},
|
|
"defaults": {"type": "dict"},
|
|
"overwrite": {"type": "dict"},
|
|
}
|
|
|
|
|
|
def apply_base(state: State, params: dict[str, Any]) -> State:
|
|
project_name: str = state.module.params["name"]
|
|
|
|
new: dict[str, Any] = {
|
|
"container_name": f"{project_name}_{params["name"]}",
|
|
"hostname": f"{project_name}_{params["name"]}",
|
|
"image": params["image"],
|
|
"restart": "unless-stopped",
|
|
"environment": {},
|
|
"labels": {},
|
|
"volumes": [],
|
|
"networks": {
|
|
"internal": None,
|
|
},
|
|
}
|
|
|
|
return update(params["name"], state, new)
|
|
|
|
|
|
def set_definition(state: State, params: dict[str, Any], param_name: str) -> State:
|
|
service_name: str = params["name"]
|
|
definition: dict[str, Any] = params.get(param_name, {})
|
|
|
|
project = copy.deepcopy(state.after)
|
|
services: dict[str, Any] = project["services"]
|
|
service: dict[str, Any] = services[service_name]
|
|
|
|
_ = recursive_update(service, definition)
|
|
|
|
services.update({service_name: service})
|
|
|
|
return replace(state, after=project)
|
|
|
|
|
|
def update(service_name: str, state: State, update: dict[str, Any]) -> State:
|
|
project = copy.deepcopy(state.after)
|
|
|
|
_ = recursive_update(project["services"][service_name], update)
|
|
|
|
return replace(state, after=project)
|
|
|
|
|
|
def run_helper(
|
|
state: State,
|
|
params: dict[str, Any],
|
|
helper: Callable[[State, dict[str, Any]], State] = lambda x, _: x,
|
|
) -> State:
|
|
state = apply_base(state, params)
|
|
state = set_definition(state, params, "defaults")
|
|
state = helper(state, params)
|
|
state = set_definition(state, params, "overwrite")
|
|
return update_project(state)
|