add device tags

This commit is contained in:
Abel Luck 2023-11-06 11:15:33 +01:00
parent 2fcd13a16b
commit f5a2ecd6fd
2 changed files with 18 additions and 8 deletions

View file

@ -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)
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

View file

@ -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 = {