SiamCafe.net Blog
Technology

Tailscale Mesh Feature Flag Management

tailscale mesh feature flag management
Tailscale Mesh Feature Flag Management | SiamCafe Blog
2026-01-03· อ. บอม — SiamCafe.net· 8,964 คำ

Tailscale Mesh VPN

Tailscale Mesh VPN สร้างบน WireGuard เชื่อมต่ออุปกรณ์ Peer-to-Peer ไม่ผ่าน Central Server ติดตั้งง่าย ไม่เปิด Port SSO Login ACL ควบคุมการเข้าถึง

Feature Flag เปิดปิด Feature ใน Production ไม่ต้อง Deploy ใหม่ Canary Release A/B Testing Kill Switch

Tailscale Setup และ ACL

# === Tailscale Setup และ Configuration ===

# 1. ติดตั้ง Tailscale
# Linux
# curl -fsSL https://tailscale.com/install.sh | sh
# sudo tailscale up

# macOS
# brew install tailscale
# sudo tailscale up

# Windows
# Download from tailscale.com/download
# tailscale up

# Docker
# docker run -d --name=tailscale \
#   --cap-add=NET_ADMIN \
#   --cap-add=SYS_MODULE \
#   -v /dev/net/tun:/dev/net/tun \
#   -v tailscale-state:/var/lib/tailscale \
#   -e TS_AUTHKEY=tskey-auth-xxxxx \
#   tailscale/tailscale

# 2. Tailscale ACL (tailscale policy file)
# {
#   "groups": {
#     "group:devops": ["user1@company.com", "user2@company.com"],
#     "group:developers": ["dev1@company.com", "dev2@company.com"],
#     "group:qa": ["qa1@company.com"]
#   },
#   "tagOwners": {
#     "tag:production": ["group:devops"],
#     "tag:staging": ["group:devops", "group:developers"],
#     "tag:feature-flags": ["group:devops"]
#   },
#   "acls": [
#     {
#       "action": "accept",
#       "src": ["group:devops"],
#       "dst": ["tag:production:*"]
#     },
#     {
#       "action": "accept",
#       "src": ["group:developers"],
#       "dst": ["tag:staging:*"]
#     },
#     {
#       "action": "accept",
#       "src": ["group:devops"],
#       "dst": ["tag:feature-flags:4242"]
#     },
#     {
#       "action": "accept",
#       "src": ["tag:production"],
#       "dst": ["tag:feature-flags:4242"]
#     }
#   ]
# }

# 3. Tailscale Commands
commands = {
    "tailscale up": "เชื่อมต่อ VPN",
    "tailscale down": "ตัดการเชื่อมต่อ",
    "tailscale status": "ดูสถานะอุปกรณ์ทั้งหมด",
    "tailscale ip": "ดู IP ของตัวเอง",
    "tailscale ping ": "Ping อุปกรณ์อื่น",
    "tailscale netcheck": "ตรวจสอบ Network",
    "tailscale cert ": "ขอ HTTPS Certificate",
    "tailscale serve": "เปิด Service ให้เข้าถึงผ่าน Tailscale",
    "tailscale funnel": "เปิด Service ให้เข้าถึงจาก Internet",
}

print("Tailscale Commands:")
for cmd, desc in commands.items():
    print(f"  {cmd}")
    print(f"    -> {desc}")

Feature Flag Implementation

# feature_flags.py — Feature Flag Management System
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Any
from datetime import datetime
import json
import hashlib

@dataclass
class FeatureFlag:
    key: str
    name: str
    description: str
    enabled: bool = False
    percentage: int = 100  # Rollout percentage
    targets: List[str] = field(default_factory=list)  # Specific user IDs
    environments: Dict[str, bool] = field(default_factory=dict)
    created_at: str = ""
    updated_at: str = ""

    def __post_init__(self):
        if not self.created_at:
            self.created_at = datetime.now().isoformat()
        self.updated_at = datetime.now().isoformat()

class FeatureFlagService:
    """Feature Flag Service"""

    def __init__(self):
        self.flags: Dict[str, FeatureFlag] = {}

    def create_flag(self, flag: FeatureFlag):
        self.flags[flag.key] = flag

    def is_enabled(self, key: str, user_id: str = "",
                   environment: str = "production") -> bool:
        """ตรวจสอบว่า Feature Flag เปิดอยู่หรือไม่"""
        flag = self.flags.get(key)
        if not flag:
            return False

        # ตรวจ Environment
        if environment in flag.environments:
            if not flag.environments[environment]:
                return False

        # ตรวจ Global enabled
        if not flag.enabled:
            return False

        # ตรวจ Specific targets
        if flag.targets and user_id in flag.targets:
            return True

        # ตรวจ Percentage rollout
        if flag.percentage < 100 and user_id:
            hash_val = int(hashlib.md5(
                f"{key}:{user_id}".encode()).hexdigest(), 16)
            return (hash_val % 100) < flag.percentage

        return flag.enabled

    def get_all_flags(self, user_id: str = "",
                      environment: str = "production") -> Dict[str, bool]:
        """ดึง Flag ทั้งหมดสำหรับ User"""
        result = {}
        for key in self.flags:
            result[key] = self.is_enabled(key, user_id, environment)
        return result

    def summary(self):
        print(f"\nFeature Flags Summary:")
        print(f"  Total: {len(self.flags)}")
        enabled = sum(1 for f in self.flags.values() if f.enabled)
        print(f"  Enabled: {enabled}")
        print(f"  Disabled: {len(self.flags) - enabled}")

        for key, flag in self.flags.items():
            status = "ON" if flag.enabled else "OFF"
            pct = f" ({flag.percentage}%)" if flag.percentage < 100 else ""
            targets = f" targets={len(flag.targets)}" if flag.targets else ""
            print(f"    [{status}] {key}{pct}{targets}")
            print(f"      {flag.description}")

# ตัวอย่าง
service = FeatureFlagService()

flags = [
    FeatureFlag("new-checkout", "New Checkout Flow",
                "Redesigned checkout with fewer steps",
                enabled=True, percentage=25),
    FeatureFlag("dark-mode", "Dark Mode",
                "Dark theme for the application",
                enabled=True, percentage=100),
    FeatureFlag("ai-recommendations", "AI Recommendations",
                "ML-powered product recommendations",
                enabled=True, percentage=10,
                targets=["user-vip-001", "user-vip-002"]),
    FeatureFlag("new-search", "New Search Engine",
                "Elasticsearch-powered search",
                enabled=False,
                environments={"staging": True, "production": False}),
    FeatureFlag("maintenance-mode", "Maintenance Mode",
                "Kill switch for maintenance",
                enabled=False),
]

for flag in flags:
    service.create_flag(flag)

service.summary()

# ทดสอบ
users = ["user-001", "user-002", "user-vip-001", "user-100"]
print(f"\nFlag Evaluation:")
for user in users:
    flags_state = service.get_all_flags(user)
    enabled_flags = [k for k, v in flags_state.items() if v]
    print(f"  {user}: {enabled_flags}")

Tailscale + Feature Flag Architecture

# architecture.py — Tailscale + Feature Flag Architecture
from dataclasses import dataclass
from typing import List, Dict

@dataclass
class ServiceNode:
    name: str
    tailscale_ip: str
    tags: List[str]
    ports: List[int]
    role: str

class MeshArchitecture:
    """Tailscale Mesh + Feature Flag Architecture"""

    def __init__(self):
        self.nodes: List[ServiceNode] = []

    def add_node(self, node: ServiceNode):
        self.nodes.append(node)

    def show_topology(self):
        print(f"\n{'='*55}")
        print(f"Tailscale Mesh Topology")
        print(f"{'='*55}")

        by_role = {}
        for node in self.nodes:
            if node.role not in by_role:
                by_role[node.role] = []
            by_role[node.role].append(node)

        for role, nodes in by_role.items():
            print(f"\n  [{role}]")
            for node in nodes:
                tags = ", ".join(node.tags)
                ports = ", ".join(str(p) for p in node.ports)
                print(f"    {node.name}")
                print(f"      IP: {node.tailscale_ip}")
                print(f"      Tags: {tags}")
                print(f"      Ports: {ports}")

    def deployment_flow(self):
        """Feature Flag Deployment Flow"""
        steps = [
            "1. Developer สร้าง Feature Flag ใน Dashboard",
            "2. Code ตรวจสอบ Flag ก่อนแสดง Feature",
            "3. Deploy Code ไป Production (Feature ยังปิด)",
            "4. เปิด Flag 10% (Canary Release)",
            "5. Monitor Metrics, Errors, Performance",
            "6. ถ้าปกติ เพิ่มเป็น 25% -> 50% -> 100%",
            "7. ถ้ามีปัญหา ปิด Flag ทันที (Kill Switch)",
            "8. เมื่อ 100% แล้ว ลบ Flag และ Cleanup Code",
        ]

        print(f"\n  Feature Flag Deployment Flow:")
        for step in steps:
            print(f"    {step}")

# ตัวอย่าง
arch = MeshArchitecture()

nodes = [
    ServiceNode("feature-flag-server", "100.64.0.1",
                ["tag:feature-flags"], [4242], "Infrastructure"),
    ServiceNode("api-gateway", "100.64.0.10",
                ["tag:production"], [8080], "Edge"),
    ServiceNode("web-app", "100.64.0.20",
                ["tag:production"], [3000], "Frontend"),
    ServiceNode("api-server-1", "100.64.0.30",
                ["tag:production"], [8081], "Backend"),
    ServiceNode("api-server-2", "100.64.0.31",
                ["tag:production"], [8081], "Backend"),
    ServiceNode("staging-server", "100.64.0.50",
                ["tag:staging"], [8080, 3000], "Staging"),
    ServiceNode("dev-laptop-1", "100.64.0.100",
                ["tag:developers"], [0], "Developer"),
]

for node in nodes:
    arch.add_node(node)

arch.show_topology()
arch.deployment_flow()

# Feature Flag Tools
tools = {
    "LaunchDarkly": "Enterprise Feature Flag SaaS ครบครัน",
    "Unleash": "Open Source Feature Flag Server",
    "Flagsmith": "Open Source Feature Flag + Remote Config",
    "ConfigCat": "Feature Flag SaaS ราคาถูก",
    "Split.io": "Feature Flag + Experimentation Platform",
    "Flipt": "Open Source Lightweight Feature Flags",
}

print(f"\n  Feature Flag Tools:")
for tool, desc in tools.items():
    print(f"    {tool}: {desc}")

Best Practices

Tailscale คืออะไร

Mesh VPN สร้างบน WireGuard เชื่อมต่อ Peer-to-Peer ไม่ผ่าน Central Server ติดตั้งง่าย ไม่เปิด Port SSO Login ACL ควบคุมการเข้าถึง

Feature Flag คืออะไร

Toggle เปิดปิด Feature Production ไม่ต้อง Deploy ใหม่ Canary Release A/B Testing Kill Switch ปิดทันทีเมื่อมีปัญหา

Tailscale ACL คืออะไร

Access Control List กำหนดอุปกรณ์เข้าถึงอุปกรณ์ไหน JSON HuJSON กำหนดตาม User Group Tag Port Protocol GitOps Version Control

ใช้ Tailscale กับ Feature Flag ร่วมกันอย่างไร

Tailscale Secure Network เชื่อม Feature Flag Server Private Network ไม่เปิด Public ACL ควบคุม Admin Access Tags แยก Environment

สรุป

Tailscale Mesh VPN WireGuard เชื่อมต่อ Peer-to-Peer ACL ควบคุมการเข้าถึง Feature Flag เปิดปิด Feature Production Canary Release Kill Switch ใช้ร่วมกัน Secure Network Private Access Tags แยก Environment

📖 บทความที่เกี่ยวข้อง

Prometheus Federation Feature Flag Managementอ่านบทความ → Payload CMS Feature Flag Managementอ่านบทความ → Tailscale Mesh Home Lab Setupอ่านบทความ → Linkerd Service Mesh Feature Flag Managementอ่านบทความ → Python Pydantic Feature Flag Managementอ่านบทความ →

📚 ดูบทความทั้งหมด →