refactor(remnawave): синхронизировать панель из desired.yml и шаблонов команд
ansible-deploy / plan (push) Successful in 1s
ansible-lint / lint (push) Successful in 2s
ansible-deploy / deploy (core-mon, ) (push) Successful in 37s
ansible-deploy / deploy (core-net, ) (push) Failing after 52s
ansible-deploy / deploy (core-secrets, ) (push) Successful in 24s
ansible-deploy / deploy (ger-nod-02, ) (push) Successful in 1m20s
ansible-deploy / deploy (opnsense, ) (push) Successful in 13s
ansible-deploy / deploy (rus-central, ) (push) Successful in 1m6s

Повторный прогон без смены compose не тянет образы, ноды и сквады добавляются данными, а не новым плейбуком на каждый VPS.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
karpenokandCursor committed 2026-11-18 17:18:49 +07:00
1 parent 89f928c64a
commit 99ee815213
22 files changed
+1151 -672

No files matched your search

@@ -4,25 +4,10 @@
# Секреты setup-ключей сохраняются в Infisical (/services/netbird) автоматически
# и не попадают в Git или логи CI.
# Управляемые группы пиров
# Группы exit-<hostname> для нод из desired.yml добавляет sync_access.py.
client_groups:
- exit-clients
- remnawave
- exit-ger-nod-02
# Выходные шлюзы (Exit Nodes)
exit_nodes:
- network_id: exit-ger-nod-02
description: "Exit Node DE (0.0.0.0/0 via ger-nod-02)"
peer: ger-nod-02
peer_group: exit-ger-nod-02
client_groups:
- exit-clients
metric: 9999
masquerade: true
keep_route: false
skip_auto_apply: false
enabled: true
# DNS для клиентских групп
dns_nameservers:
@@ -58,10 +43,6 @@ peers:
groups:
- remnawave
state: present
- name: "ger-nod-02"
groups:
- exit-ger-nod-02
state: present
# Zero-Trust политики доступа (заменяют дефолтную политику Default All <-> All).
# Инициировать соединения в сторону внешних нод могут только панель (core-net) и клиенты (exit-clients).
@@ -83,8 +64,7 @@ policies:
- "9101"
sources:
- remnawave
destinations:
- exit-ger-nod-02
destinations: "@remnawave_exit_groups"
- name: "exit-clients-to-exit-nodes"
description: "One-way traffic from Exit Node clients to Exit Nodes"
@@ -98,8 +78,7 @@ policies:
bidirectional: false
sources:
- exit-clients
destinations:
- exit-ger-nod-02
destinations: "@remnawave_exit_groups"
- name: "exit-clients-udp"
description: "Allow outbound UDP from exit-clients via exit node"
enabled: true
@@ -108,8 +87,7 @@ policies:
bidirectional: false
sources:
- exit-clients
destinations:
- exit-ger-nod-02
destinations: "@remnawave_exit_groups"
- name: "exit-clients-icmp"
description: "Allow ICMP for exit-clients via exit node"
enabled: true
@@ -118,5 +96,4 @@ policies:
bidirectional: true
sources:
- exit-clients
destinations:
- exit-ger-nod-02
destinations: "@remnawave_exit_groups"
@@ -73,10 +73,59 @@ def group_peer_ids(grp: dict[str, Any]) -> list[str]:
return [p["id"] for p in (grp.get("peers") or []) if p.get("id")]
def expand_remnawave(cfg: dict[str, Any]) -> None:
"""Группы, exit-маршруты и пиры нод берутся из desired.yml, не копируются руками."""
if "remnawave_nodes" not in cfg:
return
nodes = cfg.pop("remnawave_nodes") or []
groups: list[str] = []
for node in nodes:
host = str(node.get("netbird_hostname") or "").strip()
if not host:
continue
group = f"exit-{host}"
groups.append(group)
client_groups = cfg.setdefault("client_groups", [])
if group not in client_groups:
client_groups.append(group)
exits = cfg.setdefault("exit_nodes", [])
if not any(item.get("network_id") == group for item in exits):
code = str(node.get("country_code") or "").strip()
exits.append(
{
"network_id": group,
"description": f"Exit Node {code} via {host}".strip(),
"peer": host,
"peer_group": group,
"client_groups": ["exit-clients"],
"metric": 9999,
"masquerade": True,
"keep_route": False,
"skip_auto_apply": False,
"enabled": True,
}
)
peers = cfg.setdefault("peers", [])
if not any(item.get("name") == host for item in peers):
peers.append({"name": host, "groups": [group], "state": "present"})
cfg["_remnawave_exit_groups"] = groups
for policy in cfg.get("policies") or []:
for rule in policy.get("rules") or []:
dest = rule.get("destinations")
if dest == "@remnawave_exit_groups":
rule["destinations"] = list(groups)
elif isinstance(dest, list) and "@remnawave_exit_groups" in dest:
expanded: list[str] = []
for item in dest:
expanded.extend(groups if item == "@remnawave_exit_groups" else [item])
rule["destinations"] = expanded
def sync(cfg: dict[str, Any], api: NetBirdAPI) -> dict[str, Any]:
changes: list[str] = []
warnings: list[str] = []
updated_secrets: dict[str, str] = {}
expand_remnawave(cfg)
peers_raw = api.get("/peers") or []
groups_raw = api.get("/groups") or []
@@ -217,6 +266,22 @@ def sync(cfg: dict[str, Any], api: NetBirdAPI) -> dict[str, Any]:
api.put(f"/routes/{existing['id']}", desired)
changes.append(f"route.update:{net_id}")
keep_exit_groups = cfg.get("_remnawave_exit_groups")
if keep_exit_groups is not None:
keep = set(keep_exit_groups)
for route in routes_raw:
net_id = str(route.get("network_id") or "")
if route.get("network") == "0.0.0.0/0" and net_id.startswith("exit-") and net_id not in keep and route.get("id"):
api.delete(f"/routes/{route['id']}")
changes.append(f"route.delete:{net_id}")
for gname, grp in list(groups_by_name.items()):
if not gname.startswith("exit-") or gname == "exit-clients" or gname in keep:
continue
current_ids = group_peer_ids(grp)
if current_ids:
set_group_peers(grp, [])
changes.append(f"group.clear:{gname}")
# 4. DNS Nameservers
ns_raw = api.get("/dns/nameservers") or []
for item in cfg.get("dns_nameservers") or []:
@@ -2,6 +2,11 @@
- name: Загрузить декларативную конфигурацию доступа NetBird
ansible.builtin.set_fact:
netbird_access_cfg: "{{ lookup('file', role_path ~ '/files/access.yml') | from_yaml }}"
netbird_remnawave_nodes: "{{ (lookup('file', playbook_dir ~ '/../roles/core-net/remnawave/files/desired.yml') | from_yaml).nodes | default([]) }}"
- name: Передать ноды Remnawave в синхронизацию доступа
ansible.builtin.set_fact:
netbird_access_cfg: "{{ netbird_access_cfg | combine({'remnawave_nodes': netbird_remnawave_nodes}) }}"
- name: Положить скрипт синхронизации доступа NetBird
ansible.builtin.copy: