diff --git a/loki-ingress-argocd-setup/00-START-HERE.txt b/loki-ingress-argocd-setup/00-START-HERE.txt new file mode 100644 index 0000000..a905cd1 --- /dev/null +++ b/loki-ingress-argocd-setup/00-START-HERE.txt @@ -0,0 +1,148 @@ +╔═══════════════════════════════════════════════════════════════════════════╗ +║ ║ +║ 🚀 LOKI INGRESS для ArgoCD - НАЧНИ ОТСЮДА 🚀 ║ +║ ║ +╚═══════════════════════════════════════════════════════════════════════════╝ + +📚 ДОКУМЕНТАЦИЯ (читай в этом порядке): +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +1. INDEX.md → Общий обзор и навигация +2. README.md → Описание файлов и быстрый старт +3. CHEATSHEET.md → Шпаргалка с командами +4. ARGOCD_LOKI_INGRESS_SETUP.md → Полная пошаговая инструкция (MAIN!) +5. ARCHITECTURE.md → Схемы и диаграммы + + +📦 YAML ФАЙЛЫ ДЛЯ РАЗВЕРТЫВАНИЯ: +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Для директории apps/loki/: + ✓ secret-basic-auth.yaml → Basic Auth credentials + ✓ middleware-auth.yaml → Traefik middleware + ✓ ingress-loki.yaml → Ingress с HTTPS + +Для директории apps/monitoring/: + ✓ grafana-datasource-loki.yaml → Grafana datasource config + + +🤖 АВТОМАТИЗАЦИЯ: +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ✓ deploy-loki-ingress.sh → Скрипт автоматического развертывания + + +🚀 БЫСТРЫЙ СТАРТ: +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +ВАРИАНТ 1: Автоматический (рекомендуется) +────────────────────────────────────────── + +1. Клонируй git репозиторий: + $ git clone http://gitea-http.gitea.svc.cluster.local:3000/admin/k3s-gitops.git + $ cd k3s-gitops + +2. Скопируй YAML файлы: + $ cp secret-basic-auth.yaml apps/loki/ + $ cp middleware-auth.yaml apps/loki/ + $ cp ingress-loki.yaml apps/loki/ + +3. Запусти скрипт развертывания: + $ chmod +x deploy-loki-ingress.sh + $ ./deploy-loki-ingress.sh + +4. Настрой DNS для loki.thedevops.dev → 5.182.17.194 + + +ВАРИАНТ 2: Ручной +────────────────── + +См. подробную инструкцию в ARGOCD_LOKI_INGRESS_SETUP.md + + +✅ ПРОВЕРКА ПОСЛЕ УСТАНОВКИ: +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +1. Проверь статус ресурсов: + $ kubectl get ingress,certificate,secret -n loki + +2. Тестовый запрос: + $ curl -u admin:lokipass123 https://loki.thedevops.dev/ready + Ожидается: "ready" + +3. Открой в браузере: + URL: https://loki.thedevops.dev + Username: admin + Password: lokipass123 + + +🔐 БЕЗОПАСНОСТЬ (ВАЖНО!): +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +⚠️ ОБЯЗАТЕЛЬНО измени пароль по умолчанию! + +Генерация нового пароля: + $ htpasswd -nb admin your-secure-password + +Затем обнови значение в secret-basic-auth.yaml + + +📋 ЧЕК-ЛИСТ: +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +[ ] Git репозиторий клонирован +[ ] YAML файлы скопированы в apps/loki/ +[ ] Git commit и push выполнены +[ ] ArgoCD синхронизирован +[ ] DNS настроен для loki.thedevops.dev +[ ] Ingress получил IP адрес +[ ] Certificate создан (Ready: True) +[ ] Curl тест пройден +[ ] Браузер тест пройден +[ ] Пароль изменен +[ ] Loki добавлен в Grafana +[ ] Логи видны в Grafana Explore + + +🆘 НУЖНА ПОМОЩЬ? +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +1. Быстрые команды → CHEATSHEET.md +2. Troubleshooting → ARGOCD_LOKI_INGRESS_SETUP.md (раздел Troubleshooting) +3. Логи: + $ kubectl logs -n loki loki-0 + $ kubectl logs -n cert-manager deployment/cert-manager + $ kubectl get events -n loki --sort-by='.lastTimestamp' + + +🎯 ИТОГОВЫЙ РЕЗУЛЬТАТ: +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +После успешного развертывания ты получишь: + +✓ Безопасный HTTPS доступ к Loki +✓ Автоматическое управление через ArgoCD +✓ Интеграция с Grafana для просмотра логов +✓ Production-ready конфигурация +✓ Централизованное хранение логов кластера + +Доступ: + URL: https://loki.thedevops.dev + Username: admin + Password: lokipass123 (ИЗМЕНИ!) + + +📞 ТВОЯ ИНФРАСТРУКТУРА: +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +ArgoCD: https://argocd.thedevops.dev +Grafana: https://grafana.thedevops.dev +Gitea: http://gitea-http.gitea.svc.cluster.local:3000 +Loki: https://loki.thedevops.dev (после развертывания) + + +🎉 Happy Logging! 🚀📊 + +╔═══════════════════════════════════════════════════════════════════════════╗ +║ Vladimiras, начни с файла INDEX.md для полной навигации по документации ║ +╚═══════════════════════════════════════════════════════════════════════════╝ diff --git a/loki-ingress-argocd-setup/ARCHITECTURE.md b/loki-ingress-argocd-setup/ARCHITECTURE.md new file mode 100644 index 0000000..0773b15 --- /dev/null +++ b/loki-ingress-argocd-setup/ARCHITECTURE.md @@ -0,0 +1,321 @@ +# Loki Architecture Diagram + +## Архитектура решения + +```mermaid +graph TB + subgraph "External Access" + Browser[🌐 Browser] + DNS[🔍 DNS: loki.thedevops.dev] + end + + subgraph "Traefik Ingress Controller" + Traefik[⚡ Traefik
Port 80/443] + LE[🔐 Let's Encrypt
TLS Certificate] + end + + subgraph "Loki Namespace" + Ingress[📥 Ingress
loki.thedevops.dev] + Middleware[🔒 Basic Auth
Middleware] + Secret[🗝️ Secret
loki-basic-auth] + Service[🔌 Service
loki:3100] + StatefulSet[💾 StatefulSet
loki-0] + PVC[📀 PVC
loki-data] + Promtail[📡 DaemonSet
Promtail] + end + + subgraph "Monitoring Namespace" + Grafana[📊 Grafana] + Prometheus[📈 Prometheus] + end + + subgraph "ArgoCD" + ArgoCD[🔄 ArgoCD
Auto-Sync] + GitRepo[📚 Gitea
k3s-gitops] + end + + subgraph "Storage" + Longhorn[💿 Longhorn
Distributed Storage] + end + + Browser -->|HTTPS| DNS + DNS -->|Resolve| Traefik + Traefik -->|TLS Termination| LE + Traefik -->|Route| Ingress + Ingress -->|Apply| Middleware + Middleware -->|Validate| Secret + Middleware -->|Forward| Service + Service -->|Load Balance| StatefulSet + StatefulSet -->|Store Logs| PVC + PVC -->|Backend| Longhorn + + Promtail -.->|Push Logs| Service + Grafana -.->|Query LogQL| Service + Prometheus -.->|Scrape Metrics| StatefulSet + + GitRepo -->|Watch| ArgoCD + ArgoCD -->|Deploy| Ingress + ArgoCD -->|Deploy| Middleware + ArgoCD -->|Deploy| Secret + ArgoCD -->|Deploy| StatefulSet + + style Browser fill:#e1f5ff + style DNS fill:#e1f5ff + style Traefik fill:#ffe1e1 + style LE fill:#ffe1e1 + style Ingress fill:#fff4e1 + style Middleware fill:#fff4e1 + style Secret fill:#fff4e1 + style Service fill:#e1ffe1 + style StatefulSet fill:#e1ffe1 + style PVC fill:#f0e1ff + style Promtail fill:#e1ffe1 + style Grafana fill:#ffe1f5 + style Prometheus fill:#ffe1f5 + style ArgoCD fill:#e1f0ff + style GitRepo fill:#e1f0ff + style Longhorn fill:#f0e1ff +``` + +## Data Flow - Логи + +```mermaid +sequenceDiagram + participant Apps as Kubernetes Pods + participant Promtail as Promtail DaemonSet + participant Loki as Loki StatefulSet + participant Storage as Longhorn PVC + participant Grafana as Grafana + + Apps->>Promtail: Write logs to stdout/stderr + Note over Promtail: Parse & Label logs + Promtail->>Loki: HTTP POST /loki/api/v1/push + Note over Loki: Index labels
Compress chunks + Loki->>Storage: Write compressed chunks + + Grafana->>Loki: LogQL Query + Loki->>Storage: Read chunks + Loki->>Grafana: Return log lines + Note over Grafana: Display in UI +``` + +## Access Flow - External User + +```mermaid +sequenceDiagram + participant User as Browser + participant DNS as DNS Server + participant Traefik as Traefik + participant Ingress as Ingress + participant Middleware as Middleware + participant Secret as Secret + participant Loki as Loki Service + + User->>DNS: Resolve loki.thedevops.dev + DNS->>User: Return IPs + User->>Traefik: HTTPS Request + Note over Traefik: TLS Termination
(Let's Encrypt) + Traefik->>Ingress: Route to loki namespace + Ingress->>Middleware: Apply loki-auth + Middleware->>Secret: Get credentials + Middleware->>Middleware: Validate Basic Auth + alt Valid Credentials + Middleware->>Loki: Forward request + Loki->>Middleware: Response + Middleware->>Traefik: Response + Traefik->>User: HTTPS Response + else Invalid Credentials + Middleware->>User: 401 Unauthorized + end +``` + +## ArgoCD GitOps Flow + +```mermaid +graph LR + subgraph "Developer" + Dev[👨‍💻 Developer] + Local[💻 Local Git] + end + + subgraph "Gitea" + Repo[📚 k3s-gitops
Repository] + end + + subgraph "ArgoCD" + Sync[🔄 ArgoCD
Controller] + App[📦 Application
loki] + end + + subgraph "Kubernetes" + Resources[☸️ K8s Resources
Ingress, Secret, etc] + end + + Dev -->|1. Edit YAML| Local + Local -->|2. Git Push| Repo + Repo -->|3. Webhook/Poll| Sync + Sync -->|4. Detect Changes| App + App -->|5. kubectl apply| Resources + Resources -.->|6. Status| App + App -.->|7. Sync Status| Dev + + style Dev fill:#e1f5ff + style Local fill:#e1f5ff + style Repo fill:#e1f0ff + style Sync fill:#e1ffe1 + style App fill:#e1ffe1 + style Resources fill:#ffe1e1 +``` + +## Component Relationships + +```mermaid +graph TB + subgraph "Core Components" + Loki[Loki StatefulSet
Port 3100] + Promtail[Promtail DaemonSet
Port 3101] + end + + subgraph "Access Control" + Ingress[Ingress] + Middleware[Middleware] + Secret[Secret] + end + + subgraph "Monitoring" + ServiceMonitor[ServiceMonitor] + Prometheus[Prometheus] + Grafana[Grafana] + end + + subgraph "Storage" + PVC[PersistentVolumeClaim
loki-data] + Longhorn[Longhorn] + end + + subgraph "GitOps" + Git[Git Repository] + ArgoCD[ArgoCD] + end + + Ingress --> Middleware + Middleware --> Secret + Middleware --> Loki + Promtail --> Loki + Loki --> PVC + PVC --> Longhorn + ServiceMonitor --> Loki + ServiceMonitor --> Prometheus + Grafana --> Loki + Git --> ArgoCD + ArgoCD --> Ingress + ArgoCD --> Middleware + ArgoCD --> Secret + ArgoCD --> Loki + ArgoCD --> Promtail + + style Loki fill:#4CAF50 + style Promtail fill:#8BC34A + style Ingress fill:#FFC107 + style Middleware fill:#FF9800 + style Secret fill:#FF5722 + style Grafana fill:#E91E63 + style Prometheus fill:#9C27B0 + style ArgoCD fill:#2196F3 + style Longhorn fill:#00BCD4 +``` + +## Deployment States + +```mermaid +stateDiagram-v2 + [*] --> GitPush: Developer commits + GitPush --> ArgoCD_Detect: ArgoCD polls repo + ArgoCD_Detect --> Syncing: Changes detected + Syncing --> Deploying: Apply manifests + + state Deploying { + [*] --> CreateSecret + CreateSecret --> CreateMiddleware + CreateMiddleware --> CreateIngress + CreateIngress --> RequestCert + RequestCert --> ValidateCert + ValidateCert --> [*] + } + + Deploying --> Healthy: All resources ready + Healthy --> [*]: Deployment complete + + Deploying --> Failed: Error occurred + Failed --> Syncing: Retry + + Healthy --> GitPush: New changes +``` + +## Network Topology + +```mermaid +graph TB + subgraph "Internet" + Client[Client Browser] + end + + subgraph "Public IPs" + IP1[5.182.17.194] + IP2[62.169.30.194] + IP3[62.169.30.206] + end + + subgraph "k3s Cluster" + subgraph "kube-system" + Traefik[Traefik LoadBalancer
80/443] + end + + subgraph "loki namespace" + Ingress[Ingress
loki.thedevops.dev] + Service[ClusterIP Service
10.43.x.x:3100] + Pod[Loki Pod
10.42.x.x:3100] + end + + subgraph "cert-manager" + CertManager[Cert Manager] + Certificate[Certificate
loki-tls] + end + end + + Client -->|DNS| IP1 + Client -->|DNS| IP2 + Client -->|DNS| IP3 + IP1 --> Traefik + IP2 --> Traefik + IP3 --> Traefik + Traefik -->|Route by Host| Ingress + Ingress -->|ClusterIP| Service + Service -->|Pod IP| Pod + CertManager -.->|Provision| Certificate + Certificate -.->|Use| Ingress + + style Client fill:#e1f5ff + style IP1 fill:#ffe1e1 + style IP2 fill:#ffe1e1 + style IP3 fill:#ffe1e1 + style Traefik fill:#fff4e1 + style Ingress fill:#e1ffe1 + style Service fill:#e1f0ff + style Pod fill:#f0e1ff +``` + +--- + +## Legend + +- 🌐 External Access Point +- ⚡ Load Balancer / Proxy +- 📥 Ingress / API Gateway +- 🔒 Authentication / Security +- 💾 Stateful Storage +- 📡 Log Collection +- 📊 Visualization +- 🔄 Automation / GitOps +- 💿 Persistent Storage +- ☸️ Kubernetes Resources diff --git a/loki-ingress-argocd-setup/ARCHIVE_INFO.txt b/loki-ingress-argocd-setup/ARCHIVE_INFO.txt new file mode 100644 index 0000000..4887280 --- /dev/null +++ b/loki-ingress-argocd-setup/ARCHIVE_INFO.txt @@ -0,0 +1,115 @@ +╔══════════════════════════════════════════════════════════════════════════╗ +║ ║ +║ 📦 LOKI INGRESS ArgoCD SETUP - ARCHIVE INFO 📦 ║ +║ ║ +╚══════════════════════════════════════════════════════════════════════════╝ + +📁 Archive Name: loki-ingress-argocd-setup.zip +📊 Archive Size: 24 KB +📝 Total Files: 14 files (62 KB uncompressed) +📅 Created: 2026-01-05 + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +📋 СОДЕРЖИМОЕ АРХИВА: + +┌─ DOCUMENTATION (5 files) +│ +├── 00-START-HERE.txt 7.8 KB → Начни отсюда! +├── INDEX.md 6.3 KB → Навигация +├── README.md 5.3 KB → Описание файлов +├── CHEATSHEET.md 4.1 KB → Команды и шпаргалка +└── ARGOCD_LOKI_INGRESS_SETUP.md 18.5 KB → Полная инструкция ⭐ + +┌─ DIAGRAMS & ARCHITECTURE (1 file) +│ +└── ARCHITECTURE.md 8.0 KB → Mermaid диаграммы + +┌─ YAML MANIFESTS (6 files) +│ +├── secret-basic-auth.yaml 421 B → Basic Auth +├── middleware-auth.yaml 298 B → Traefik middleware +├── ingress-loki.yaml 1.1 KB → Main Ingress ⭐ +├── loki-ingress.yaml 1.7 KB → Alternative version +├── loki-nodeport.yaml 447 B → NodePort alternative +└── grafana-datasource-loki.yaml 1.2 KB → Grafana datasource + +┌─ AUTOMATION (1 file) +│ +└── deploy-loki-ingress.sh 5.1 KB → Auto-deploy script ⭐ + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +🎯 ЧТО ВНУТРИ: + +✓ Полная документация на русском языке +✓ Пошаговые инструкции (12 шагов) +✓ Готовые YAML манифесты для ArgoCD +✓ Bash скрипт для автоматического развертывания +✓ Troubleshooting guide +✓ Mermaid диаграммы архитектуры +✓ Шпаргалка с командами +✓ Интеграция с Grafana + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +📖 КАК ИСПОЛЬЗОВАТЬ: + +1. Распакуй архив: + $ unzip loki-ingress-argocd-setup.zip + +2. Начни с одного из файлов: + - 00-START-HERE.txt → Краткий обзор + - INDEX.md → Полная навигация + +3. Следуй инструкциям в: + - ARGOCD_LOKI_INGRESS_SETUP.md + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +🚀 БЫСТРЫЙ СТАРТ: + +После распаковки: + +$ cd k3s-gitops +$ cp secret-basic-auth.yaml apps/loki/ +$ cp middleware-auth.yaml apps/loki/ +$ cp ingress-loki.yaml apps/loki/ +$ chmod +x deploy-loki-ingress.sh +$ ./deploy-loki-ingress.sh + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +🎯 РЕЗУЛЬТАТ: + +После развертывания: + URL: https://loki.thedevops.dev + Username: admin + Password: lokipass123 (ИЗМЕНИ!) + +Features: + ✓ HTTPS с Let's Encrypt + ✓ Basic Authentication + ✓ ArgoCD GitOps управление + ✓ Grafana интеграция + ✓ Production-ready + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +📞 SUPPORT: + +Для помощи см.: + - CHEATSHEET.md → Быстрые команды + - ARGOCD_LOKI_INGRESS_SETUP.md → Troubleshooting раздел + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Created for: Vladimiras Levinas +Purpose: Loki Ingress deployment via ArgoCD GitOps +Date: 2026-01-05 + +Happy Logging! 🚀📊 + +╔══════════════════════════════════════════════════════════════════════════╗ +║ Начни с файла 00-START-HERE.txt ║ +╚══════════════════════════════════════════════════════════════════════════╝ diff --git a/loki-ingress-argocd-setup/ARGOCD_LOKI_INGRESS_SETUP.md b/loki-ingress-argocd-setup/ARGOCD_LOKI_INGRESS_SETUP.md new file mode 100644 index 0000000..9c52f3b --- /dev/null +++ b/loki-ingress-argocd-setup/ARGOCD_LOKI_INGRESS_SETUP.md @@ -0,0 +1,712 @@ +# ArgoCD GitOps Setup для Loki Ingress + +## Текущая конфигурация + +- **ArgoCD Application:** `loki` +- **Git Repository:** `http://gitea-http.gitea.svc.cluster.local:3000/admin/k3s-gitops` +- **Path:** `apps/loki` +- **Auto-sync:** Включен (prune: true, selfHeal: true) +- **Target Namespace:** `loki` + +--- + +## Шаг 1: Подключись к Git репозиторию + +### Вариант A: Через SSH (рекомендуется) + +```bash +# Клонируй репозиторий +git clone git@gitea-http.gitea.svc.cluster.local:admin/k3s-gitops.git +cd k3s-gitops + +# Или если используешь внешний доступ +git clone git@gitea.thedevops.dev:admin/k3s-gitops.git +cd k3s-gitops +``` + +### Вариант B: Через HTTP + +```bash +git clone http://gitea-http.gitea.svc.cluster.local:3000/admin/k3s-gitops.git +cd k3s-gitops + +# Введи credentials для Gitea +``` + +--- + +## Шаг 2: Проверь структуру директорий + +```bash +# Перейди в директорию приложения Loki +cd apps/loki + +# Посмотри текущую структуру +tree . + +# Должна быть примерно такая структура: +# apps/loki/ +# ├── namespace.yaml +# ├── configmap-loki.yaml +# ├── configmap-promtail.yaml +# ├── statefulset.yaml +# ├── daemonset-promtail.yaml +# ├── service.yaml +# ├── ingress-promtail.yaml (уже существует) +# ├── rbac.yaml +# └── servicemonitor.yaml +``` + +--- + +## Шаг 3: Создай файлы для Loki Ingress + +### 3.1 Secret для Basic Auth + +Создай файл: `apps/loki/secret-basic-auth.yaml` + +```yaml +--- +# Basic Auth Secret для защиты Loki +apiVersion: v1 +kind: Secret +metadata: + name: loki-basic-auth + namespace: loki + labels: + app.kubernetes.io/name: loki + argocd.argoproj.io/instance: loki +type: Opaque +stringData: + # Username: admin + # Password: lokipass123 + # Сгенерировано с помощью: htpasswd -nb admin lokipass123 + users: | + admin:$apr1$8jGXMp0X$xR7yGcZqz.pPJY4IaGQ0n0 +``` + +**Как создать свой пароль:** + +```bash +# Установи htpasswd (если нужно) +sudo apt-get install apache2-utils + +# Создай новый пароль +htpasswd -nb admin your-secure-password + +# Результат замени в stringData.users выше +``` + +### 3.2 Traefik Middleware + +Создай файл: `apps/loki/middleware-auth.yaml` + +```yaml +--- +# Traefik Middleware для Basic Auth +apiVersion: traefik.containo.us/v1alpha1 +kind: Middleware +metadata: + name: loki-auth + namespace: loki + labels: + app.kubernetes.io/name: loki + argocd.argoproj.io/instance: loki +spec: + basicAuth: + secret: loki-basic-auth + removeHeader: true +``` + +### 3.3 Loki Ingress + +Создай файл: `apps/loki/ingress-loki.yaml` + +```yaml +--- +# Ingress для Loki с HTTPS и аутентификацией +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: loki + namespace: loki + annotations: + # Использовать Traefik ingress controller + kubernetes.io/ingress.class: traefik + + # Let's Encrypt сертификат + cert-manager.io/cluster-issuer: letsencrypt-http + cert-manager.io/acme-challenge-type: http01 + + # Применить Basic Auth middleware + traefik.ingress.kubernetes.io/router.middlewares: loki-loki-auth@kubernetescrd + + # Entry points (http и https) + traefik.ingress.kubernetes.io/router.entrypoints: web,websecure + labels: + app.kubernetes.io/name: loki + argocd.argoproj.io/instance: loki +spec: + ingressClassName: traefik + rules: + - host: loki.thedevops.dev + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: loki + port: + number: 3100 + tls: + - hosts: + - loki.thedevops.dev + secretName: loki-tls +``` + +--- + +## Шаг 4: Проверь файлы перед коммитом + +```bash +# Находясь в директории k3s-gitops/apps/loki/ + +# Проверь что файлы созданы +ls -la + +# Должны появиться: +# - secret-basic-auth.yaml +# - middleware-auth.yaml +# - ingress-loki.yaml + +# Валидируй YAML синтаксис +kubectl apply --dry-run=client -f secret-basic-auth.yaml +kubectl apply --dry-run=client -f middleware-auth.yaml +kubectl apply --dry-run=client -f ingress-loki.yaml +``` + +--- + +## Шаг 5: Git Commit и Push + +```bash +# Из директории k3s-gitops/ + +# Добавь файлы в git +git add apps/loki/secret-basic-auth.yaml +git add apps/loki/middleware-auth.yaml +git add apps/loki/ingress-loki.yaml + +# Проверь статус +git status + +# Создай коммит +git commit -m "feat(loki): Add Ingress with HTTPS and Basic Auth for loki.thedevops.dev" + +# Push в репозиторий +git push origin main +# (или master - в зависимости от твоей ветки) +``` + +--- + +## Шаг 6: ArgoCD Auto-Sync + +Поскольку у тебя включен auto-sync, ArgoCD автоматически: +1. Обнаружит изменения в git (в течение 3 минут) +2. Применит новые манифесты +3. Создаст Secret, Middleware и Ingress + +### Ручная синхронизация (если не хочешь ждать) + +#### Через ArgoCD CLI: + +```bash +# Синхронизируй приложение +argocd app sync loki + +# Посмотри статус +argocd app get loki + +# Посмотри логи синхронизации +argocd app logs loki --follow +``` + +#### Через ArgoCD UI: + +1. Открой: `https://argocd.thedevops.dev` (или твой ArgoCD URL) +2. Найди приложение `loki` +3. Нажми кнопку **"SYNC"** +4. Нажми **"SYNCHRONIZE"** + +#### Через kubectl: + +```bash +# Триггер синхронизации через kubectl +kubectl patch application loki -n argocd \ + --type merge \ + --patch '{"operation": {"initiatedBy": {"username": "manual"}}}' +``` + +--- + +## Шаг 7: Проверка развертывания + +### 7.1 Проверь ресурсы в кластере + +```bash +# Проверь что все ресурсы созданы +kubectl get all,ingress,secret,middleware -n loki + +# Проверь конкретно Ingress +kubectl get ingress loki -n loki -o wide + +# Должен показать: +# NAME CLASS HOSTS ADDRESS PORTS AGE +# loki traefik loki.thedevops.dev 5.182.17.194,62.169.30.194,... 80, 443 1m + +# Проверь Middleware +kubectl get middleware -n loki + +# Проверь Secret +kubectl get secret loki-basic-auth -n loki +``` + +### 7.2 Проверь сертификат + +```bash +# Посмотри статус сертификата +kubectl get certificate -n loki + +# Должен появиться: +# NAME READY SECRET AGE +# loki-tls True loki-tls 2m + +# Если сертификат не готов, посмотри детали +kubectl describe certificate loki-tls -n loki + +# Проверь логи cert-manager +kubectl logs -n cert-manager deployment/cert-manager --tail=50 +``` + +### 7.3 Проверь ArgoCD статус + +```bash +# Посмотри статус приложения +argocd app get loki + +# Должно показать: +# Health Status: Healthy +# Sync Status: Synced + +# Посмотри ресурсы приложения +argocd app resources loki +``` + +--- + +## Шаг 8: Настрой DNS + +### 8.1 Проверь IP адреса Ingress + +```bash +kubectl get ingress loki -n loki -o jsonpath='{.status.loadBalancer.ingress[*].ip}' + +# Получишь IP адреса: 5.182.17.194 62.169.30.194 62.169.30.206 +``` + +### 8.2 Добавь DNS запись + +В DNS провайдере (Cloudflare, Route53, и т.д.) создай A-record: + +``` +Type: A +Name: loki.thedevops.dev +Value: 5.182.17.194 (или любой из твоих IP) +TTL: 300 +``` + +**Или для всех IP (если нужен load balancing):** + +``` +Type: A, Name: loki.thedevops.dev, Value: 5.182.17.194 +Type: A, Name: loki.thedevops.dev, Value: 62.169.30.194 +Type: A, Name: loki.thedevops.dev, Value: 62.169.30.206 +``` + +### 8.3 Проверь DNS резолюцию + +```bash +# Проверь что DNS работает +nslookup loki.thedevops.dev + +# Или +dig loki.thedevops.dev + +# Должен показать твои IP адреса +``` + +--- + +## Шаг 9: Тестирование доступа + +### 9.1 Тестовые запросы + +```bash +# Проверка health endpoint (требует Basic Auth) +curl -u admin:lokipass123 https://loki.thedevops.dev/ready + +# Должен вернуть: ready + +# Проверка метрик +curl -u admin:lokipass123 https://loki.thedevops.dev/metrics + +# Проверка labels +curl -u admin:lokipass123 https://loki.thedevops.dev/loki/api/v1/labels + +# Тестовый LogQL запрос +curl -u admin:lokipass123 -G -s "https://loki.thedevops.dev/loki/api/v1/query" \ + --data-urlencode 'query={namespace="loki"}' | jq +``` + +### 9.2 Проверка через браузер + +1. Открой: `https://loki.thedevops.dev` +2. Должен появиться Basic Auth prompt +3. Введи: + - **Username:** `admin` + - **Password:** `lokipass123` +4. Должна открыться страница Loki (скорее всего 404 на корневом пути - это нормально) +5. Попробуй endpoints: + - `https://loki.thedevops.dev/ready` + - `https://loki.thedevops.dev/metrics` + +### 9.3 Проверка HTTPS сертификата + +```bash +# Проверь SSL сертификат +openssl s_client -connect loki.thedevops.dev:443 -servername loki.thedevops.dev + +# Или через curl +curl -vI https://loki.thedevops.dev 2>&1 | grep -i "SSL\|certificate" +``` + +--- + +## Шаг 10: Интеграция с Grafana + +### 10.1 Добавь Loki DataSource в Grafana + +Создай файл: `apps/monitoring/grafana-datasource-loki.yaml` + +```yaml +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: grafana-datasource-loki + namespace: monitoring + labels: + grafana_datasource: "1" +data: + loki.yaml: | + apiVersion: 1 + + datasources: + # Внутренний доступ (из Grafana pod в кластере) - РЕКОМЕНДУЕТСЯ + - name: Loki + type: loki + access: proxy + url: http://loki.loki.svc.cluster.local:3100 + isDefault: false + editable: true + jsonData: + maxLines: 5000 + timeout: 60 + derivedFields: + - datasourceUid: prometheus + matcherRegex: "traceID=(\\w+)" + name: TraceID + url: '$${__value.raw}' + + # Внешний доступ (через домен, требует Basic Auth) + - name: Loki External + type: loki + access: proxy + url: https://loki.thedevops.dev + isDefault: false + editable: true + basicAuth: true + basicAuthUser: admin + secureJsonData: + basicAuthPassword: lokipass123 + jsonData: + maxLines: 5000 + timeout: 60 + tlsSkipVerify: false +``` + +### 10.2 Примени конфигурацию + +```bash +cd k3s-gitops/ + +# Добавь файл +git add apps/monitoring/grafana-datasource-loki.yaml + +# Commit & Push +git commit -m "feat(grafana): Add Loki datasource configuration" +git push origin main + +# Если у Grafana отдельное ArgoCD приложение, синхронизируй его +argocd app sync k8s-monitoring +# (или как называется твое Grafana приложение) +``` + +### 10.3 Перезапусти Grafana (опционально) + +```bash +# Если datasource не появился автоматически +kubectl rollout restart deployment k8s-monitoring-grafana -n monitoring +``` + +### 10.4 Проверь в Grafana UI + +1. Открой Grafana: `https://grafana.thedevops.dev` +2. Перейди в: **Configuration → Data Sources** +3. Должны появиться: + - `Loki` (внутренний) + - `Loki External` (внешний) +4. Нажми **Test** на каждом +5. Должно показать: **"Data source is working"** + +--- + +## Шаг 11: Тестирование логов в Grafana + +### 11.1 Через Explore + +1. В Grafana перейди: **Explore** (иконка компаса) +2. Выбери Data Source: **Loki** +3. Попробуй запросы: + +```logql +# Все логи из namespace loki +{namespace="loki"} + +# Логи Loki pod'ов +{namespace="loki", app="loki"} + +# Ошибки из всех namespaces +{} |= "error" + +# Rate запросов за последние 5 минут +rate({namespace="loki"}[5m]) +``` + +### 11.2 Создай Dashboard + +1. **Dashboards → Import** +2. Вставь ID: **13639** (Loki Dashboard) +3. Выбери Loki datasource +4. **Import** + +--- + +## Шаг 12: Мониторинг и алерты + +### 12.1 Проверь ServiceMonitor + +```bash +# ServiceMonitor уже должен существовать +kubectl get servicemonitor loki -n loki -o yaml +``` + +### 12.2 Prometheus метрики + +```bash +# Проверь что Prometheus собирает метрики Loki +kubectl port-forward -n monitoring svc/k8s-monitoring-kube-promet-prometheus 9090:9090 + +# В браузере открой: http://localhost:9090 +# Попробуй запрос: loki_ingester_memory_chunks +``` + +--- + +## Troubleshooting + +### Проблема: Ingress не получает IP + +```bash +# Проверь Traefik +kubectl get svc -n kube-system traefik + +# Проверь логи Traefik +kubectl logs -n kube-system deployment/traefik --tail=50 +``` + +### Проблема: 401 Unauthorized + +```bash +# Проверь что Secret создан +kubectl get secret loki-basic-auth -n loki + +# Проверь содержимое +kubectl get secret loki-basic-auth -n loki -o jsonpath='{.data.users}' | base64 -d + +# Проверь что Middleware применен +kubectl get middleware loki-auth -n loki -o yaml +``` + +### Проблема: Сертификат не создается + +```bash +# Проверь CertificateRequest +kubectl get certificaterequest -n loki + +# Проверь Challenge +kubectl get challenge -n loki + +# Проверь Order +kubectl get order -n loki + +# Логи cert-manager +kubectl logs -n cert-manager deployment/cert-manager -f + +# Проверь что домен резолвится +nslookup loki.thedevops.dev +``` + +### Проблема: ArgoCD не синхронизирует + +```bash +# Проверь статус приложения +argocd app get loki + +# Проверь логи ArgoCD +kubectl logs -n argocd deployment/argocd-application-controller -f + +# Вручную триггер sync +argocd app sync loki --force +``` + +### Проблема: Loki недоступен из Grafana + +```bash +# Проверь что Service работает +kubectl get svc loki -n loki + +# Проверь endpoints +kubectl get endpoints loki -n loki + +# Тест внутри кластера +kubectl run -it --rm debug --image=curlimages/curl --restart=Never -- \ + curl -s http://loki.loki.svc.cluster.local:3100/ready +``` + +--- + +## Полезные команды + +```bash +# Просмотр всех ресурсов Loki +kubectl get all,ingress,secret,middleware,certificate -n loki + +# Логи Loki pod +kubectl logs -n loki loki-0 -f + +# Логи Promtail +kubectl logs -n loki daemonset/promtail -f + +# ArgoCD приложение +argocd app get loki +argocd app sync loki +argocd app diff loki + +# Удалить и пересоздать Ingress (если нужно) +kubectl delete ingress loki -n loki +argocd app sync loki + +# Принудительный sync всего приложения +argocd app sync loki --prune --force +``` + +--- + +## Итоговая структура Git репозитория + +``` +k3s-gitops/ +└── apps/ + └── loki/ + ├── namespace.yaml + ├── configmap-loki.yaml + ├── configmap-promtail.yaml + ├── secret-basic-auth.yaml # НОВЫЙ + ├── middleware-auth.yaml # НОВЫЙ + ├── ingress-loki.yaml # НОВЫЙ + ├── ingress-promtail.yaml # СУЩЕСТВУЮЩИЙ + ├── service.yaml + ├── statefulset.yaml + ├── daemonset-promtail.yaml + ├── rbac.yaml + └── servicemonitor.yaml +``` + +--- + +## Безопасность и Best Practices + +1. **Пароли:** + - Используй strong passwords + - Рассмотри интеграцию с Vault для хранения паролей + - Регулярно меняй пароли + +2. **HTTPS:** + - Всегда используй HTTPS для production + - Let's Encrypt сертификаты автоматически обновляются + +3. **Rate Limiting:** + - Добавь Traefik middleware для rate limiting если нужно + +4. **Network Policies:** + - Ограничь доступ к Loki только от Promtail и Grafana + +5. **Backup:** + - Настрой backup для PVC (`loki-data`) + - Используй Longhorn snapshots + +--- + +## Следующие шаги + +1. ✅ Добавить Ingress для Loki +2. ✅ Настроить HTTPS с Let's Encrypt +3. ✅ Добавить Basic Authentication +4. ✅ Интегрировать с Grafana +5. 🔲 Настроить alerting rules в Loki +6. 🔲 Добавить Grafana dashboards +7. 🔲 Настроить retention policies +8. 🔲 Интегрировать с Tempo (distributed tracing) +9. 🔲 Добавить Network Policies +10. 🔲 Настроить backup для Loki data + +--- + +## Ресурсы + +- [Loki Documentation](https://grafana.com/docs/loki/latest/) +- [Traefik Middleware](https://doc.traefik.io/traefik/middlewares/overview/) +- [ArgoCD Documentation](https://argo-cd.readthedocs.io/) +- [Cert-Manager Documentation](https://cert-manager.io/docs/) + +--- + +## Поддержка + +Если возникли проблемы: +1. Проверь логи компонентов +2. Проверь ArgoCD sync status +3. Проверь Kubernetes events: `kubectl get events -n loki --sort-by='.lastTimestamp'` diff --git a/loki-ingress-argocd-setup/CHEATSHEET.md b/loki-ingress-argocd-setup/CHEATSHEET.md new file mode 100644 index 0000000..9945ce0 --- /dev/null +++ b/loki-ingress-argocd-setup/CHEATSHEET.md @@ -0,0 +1,180 @@ +# Loki Ingress - Шпаргалка + +## Быстрый старт + +```bash +# 1. Клонируй репозиторий +git clone http://gitea-http.gitea.svc.cluster.local:3000/admin/k3s-gitops.git +cd k3s-gitops + +# 2. Скопируй файлы в apps/loki/ +cp secret-basic-auth.yaml apps/loki/ +cp middleware-auth.yaml apps/loki/ +cp ingress-loki.yaml apps/loki/ + +# 3. Commit и Push +git add apps/loki/*.yaml +git commit -m "feat(loki): Add Ingress with HTTPS and Basic Auth" +git push origin main + +# 4. Синхронизация ArgoCD (или жди 3 минуты) +argocd app sync loki +``` + +## Проверка статуса + +```bash +# Ingress +kubectl get ingress loki -n loki -o wide + +# Certificate +kubectl get certificate loki-tls -n loki + +# Все ресурсы +kubectl get all,ingress,secret,middleware,certificate -n loki +``` + +## Тестирование + +```bash +# Health check +curl -u admin:lokipass123 https://loki.thedevops.dev/ready + +# Metrics +curl -u admin:lokipass123 https://loki.thedevops.dev/metrics + +# Labels +curl -u admin:lokipass123 https://loki.thedevops.dev/loki/api/v1/labels +``` + +## Credentials по умолчанию + +- **URL:** https://loki.thedevops.dev +- **Username:** admin +- **Password:** lokipass123 + +## Изменить пароль + +```bash +# Генерация нового пароля +htpasswd -nb admin your-new-password + +# Обновить secret-basic-auth.yaml +# Замени строку в stringData.users +``` + +## DNS настройка + +``` +Type: A +Name: loki.thedevops.dev +Value: 5.182.17.194 +TTL: 300 +``` + +## Troubleshooting + +### Ingress нет IP +```bash +kubectl get svc -n kube-system traefik +kubectl logs -n kube-system deployment/traefik --tail=50 +``` + +### Сертификат не создается +```bash +kubectl describe certificate loki-tls -n loki +kubectl logs -n cert-manager deployment/cert-manager --tail=50 +kubectl get challenge -n loki +``` + +### 401 Unauthorized +```bash +kubectl get secret loki-basic-auth -n loki +kubectl get middleware loki-auth -n loki -o yaml +``` + +### ArgoCD не синхронизирует +```bash +argocd app get loki +argocd app sync loki --force +kubectl logs -n argocd deployment/argocd-application-controller --tail=50 +``` + +## Полезные команды + +```bash +# Логи Loki +kubectl logs -n loki loki-0 -f + +# Логи cert-manager +kubectl logs -n cert-manager deployment/cert-manager -f + +# События +kubectl get events -n loki --sort-by='.lastTimestamp' + +# ArgoCD sync +argocd app sync loki +argocd app get loki +argocd app diff loki + +# Принудительная пересинхронизация +argocd app sync loki --prune --force +``` + +## Grafana интеграция + +1. Скопируй `grafana-datasource-loki.yaml` в `apps/monitoring/` +2. Commit & Push +3. Sync ArgoCD приложение monitoring +4. Перезапусти Grafana (если нужно): + ```bash + kubectl rollout restart deployment k8s-monitoring-grafana -n monitoring + ``` + +## Endpoints + +- `/ready` - health check +- `/metrics` - Prometheus metrics +- `/loki/api/v1/query` - LogQL queries +- `/loki/api/v1/labels` - available labels +- `/loki/api/v1/label//values` - label values + +## LogQL примеры в Grafana + +```logql +# Все логи из loki namespace +{namespace="loki"} + +# Логи с ошибками +{namespace="loki"} |= "error" + +# Rate за 5 минут +rate({namespace="loki"}[5m]) + +# Логи конкретного pod +{namespace="loki", pod="loki-0"} +``` + +## Безопасность + +1. ✅ HTTPS включен (Let's Encrypt) +2. ✅ Basic Auth включен +3. 🔲 TODO: Изменить пароль по умолчанию +4. 🔲 TODO: Добавить Network Policy +5. 🔲 TODO: Настроить Rate Limiting + +## Структура файлов + +``` +apps/loki/ +├── secret-basic-auth.yaml ← Новый +├── middleware-auth.yaml ← Новый +├── ingress-loki.yaml ← Новый +├── namespace.yaml +├── configmap-loki.yaml +├── configmap-promtail.yaml +├── service.yaml +├── statefulset.yaml +├── daemonset-promtail.yaml +└── ... +```