diff --git a/tailscalesd/main.py b/tailscalesd/main.py index 334e81e..cac012b 100644 --- a/tailscalesd/main.py +++ b/tailscalesd/main.py @@ -12,6 +12,8 @@ from fastapi import FastAPI from pydantic import Field, SecretStr from pydantic_settings import BaseSettings, SettingsConfigDict +MATRIX_TAG = "tag:matrix" + env_path = os.getenv("TAILSCALESD_ENV_FILE") debug = os.getenv("TAILSCALESD_DEBUG", False) log = logging.getLogger("tailscalesd") @@ -70,8 +72,8 @@ def group_by_type(input_list): return result -def tailscale_labels(tailnet, device) -> Dict[str, str]: - return { +def tailscale_labels(tailnet, device, tag) -> Dict[str, str]: + labels = { "__meta_tailscale_device_client_version": device["clientVersion"], "__meta_tailscale_device_hostname": device["hostname"], "__meta_tailscale_device_authorized": str(device["authorized"]).lower(), @@ -80,6 +82,9 @@ def tailscale_labels(tailnet, device) -> Dict[str, str]: "__meta_tailscale_device_os": device["os"], "__meta_tailscale_tailnet": tailnet, } + if tag: + labels["__meta_tailscale_device_tag"] = tag + return labels async def matrix_node_sd(device) -> Dict: @@ -107,7 +112,7 @@ def matrix_workers_to_sd(tailnet, device, workers) -> List: target_groups.append( { "targets": [f"{ipv4}:{port}"], - "labels": tailscale_labels(tailnet, device) + "labels": tailscale_labels(tailnet, device, None) | { "__meta_matrix_worker_type": worker_type, "__meta_matrix_worker_name": worker_name, @@ -120,7 +125,7 @@ def matrix_workers_to_sd(tailnet, device, workers) -> List: async def matrix_sd(tailnet, devices) -> List: sd = [] for device in devices: - if "tag:matrix" not in device["tags"]: + if MATRIX_TAG not in device["tags"]: continue try: workers = await matrix_node_sd(device) @@ -140,9 +145,14 @@ def plain_devices_sd(tailnet, devices) -> List: sd = [] for device in devices: targets = ipv4_only(device["addresses"]) - labels = tailscale_labels(tailnet, device) - sd.append({"labels": labels, "targets": targets}) - + tags = device["tags"] + if tags: + for tag in tags: + labels = tailscale_labels(tailnet, device, tag) + sd.append({"labels": labels, "targets": targets}) + else: + labels = tailscale_labels(tailnet, device, None) + sd.append({"labels": labels, "targets": targets}) return sd diff --git a/tests/test_main.py b/tests/test_main.py index dfb5a37..d25097a 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -41,11 +41,11 @@ def test_matrix_workers_to_sd_valid_input(): "addresses": ["10.0.0.1", "192.168.1.1"], "hostname": "test-host", "clientVersion": "1", - "tags": ["tag:matrix"], "id": "id", "name": "name", "os": "linux", "authorized": True, + "tags": ["tag:test"], "tailnet": "testnet", } workers = {