diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index 665ace7..d1a81fc 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -6,7 +6,7 @@ | Машина | Плейбук | Роли | Каталоги | |---|---|---|---| -| `core-net` | `playbooks/core-net.yml` | `roles/core-net/traefik`, `roles/core-net/authentik` | `/opt/traefik`, `/opt/authentik` | +| `core-net` | `playbooks/core-net.yml` | `roles/core-net/traefik`; `roles/core-net/authentik` *(опц., по умолчанию выкл.)* | `/opt/traefik`; `/opt/authentik` *(если включён)* | | `core-secrets` | `playbooks/core-secrets.yml` | `roles/core-secrets/infisical`, `roles/core-secrets/vaultwarden` | `/opt/infisical`, `/opt/vaultwarden` | | `core-mon` | `playbooks/core-mon.yml` | `roles/core-mon/monitoring` | `/opt/monitoring` | | `rus-central` | `playbooks/rus-central.yml` | `roles/rus-central/netbird` | `/opt/netbird` | @@ -32,7 +32,7 @@ Terraform в этом репозитории описывает только у |---|---|---|---|---| | **CT 109** | `pve` | `192.168.1.217` | `gitea` | Gitea (`:3000`), Postgres (`:5432`), Gitea Actions Runner (`dind`) | | **CT 901** | `netcore` | `192.168.1.102` | `core-secrets` | Infisical (`:8080`), Postgres, Redis, Vaultwarden (`:8000`) | -| **CT 902** | `netcore` | `192.168.1.104` | `core-net` | Traefik (`:80`, `:443`), Authentik (`127.0.0.1:9000`) | +| **CT 902** | `netcore` | `192.168.1.104` | `core-net` | Traefik (`:80`, `:443`); Authentik (`127.0.0.1:9000`) — опционально, по умолчанию выкл. | | **CT 903** | `netcore` | `192.168.1.108` | `core-mon` | Prometheus (`:9090`), Alertmanager (`:9093`), Grafana (`:3000`), Ntfy (`:80`) | ### 1.3. Внешние узлы @@ -62,7 +62,7 @@ API Endpoint (внутренний LAN): `http://192.168.1.102:8080/api` - `POSTGRES_PASSWORD`: пароль БД Infisical. - `ENCRYPTION_KEY`: 32-байтный hex-ключ шифрования хранилища. - `AUTH_SECRET`: base64 секрет сессий/JWT Infisical. -- `/services/authentik` *(опционально, стек отключен)*: +- `/services/authentik` *(нужен только если включите Authentik)*: - `AUTHENTIK_SECRET_KEY`: случайный ключ шифрования сессий Authentik. - `AUTHENTIK_POSTGRES_PASSWORD`: пароль БД PostgreSQL Authentik. - `/services/netbird`: @@ -113,13 +113,22 @@ API Endpoint (внутренний LAN): `http://192.168.1.102:8080/api` Дальше стек ведёт пайплайн **`ansible-core-secrets`**: Infisical в `/opt/infisical`, Vaultwarden в `/opt/vaultwarden`. -### Шаг 4. Traefik и Authentik (CT 902) +### Шаг 4. Traefik (CT 902) 1. Запустить пайплайн **`ansible-core-net`** в Gitea Actions. Первый прогон на новом CT должен быть полным: ручной запуск выполняет `site.yml --limit core-net` и ставит Docker ролью `host`. -2. Раннер подключается напрямую к `http://192.168.1.102:8080/api`, забирает SSH-ключ раннера и секреты Authentik из `/services/authentik`. Если секретов Authentik ещё нет, раннер генерирует их и сохраняет в Infisical. -3. Плейбук поднимает на CT 902 Traefik и Authentik. Authentik слушает только `127.0.0.1:9000`; снаружи его публикует Traefik как `https://auth.gunihome.ru`. Blueprint создаёт группы `admins` и `family`, пользователей `karpenok` и `ksynia` и закрывает панель Traefik группой `admins`. Пароли blueprint не задаёт. -4. Проверить `https://auth.gunihome.ru`, `https://proxy.gunihome.ru`, `gitea.gunihome.ru` и `infisical.gunihome.ru`. Панель открывается учёткой из группы `admins`. Первый запуск Authentik создаёт `akadmin`; одноразовый пароль пишется в лог контейнера `authentik-server`. `akadmin` в группу `admins` не входит. +2. Раннер подключается к `http://192.168.1.102:8080/api`, забирает SSH-ключ раннера и `ADMIN_*` из Infisical. Панель Traefik (`proxy.gunihome.ru`) закрывается BasicAuth из `/USER/ADMIN`. +3. Плейбук поднимает Traefik на CT 902. Роль Authentik в плейбуке есть, но **по умолчанию выключена** (`authentik_enabled=false` в defaults и в CI): compose не стартует, стек на cold bootstrap не нужен. +4. Проверить `https://proxy.gunihome.ru`, `https://gitea.gunihome.ru` и `https://infisical.gunihome.ru`. -Правка только роли `traefik` или только роли `authentik` ставит эту роль, без повторной подготовки машины. +Правка только роли `traefik` ставит эту роль, без повторной подготовки машины. + +#### Authentik (опционально, не часть cold bootstrap) +Стек оставляем в репозитории на будущее: SSO/forwardAuth для выбранных приложений, не для всего edge сразу. + +Чтобы включить: +1. Положить секреты в Infisical `/services/authentik` (`AUTHENTIK_SECRET_KEY`, `AUTHENTIK_POSTGRES_PASSWORD`). +2. Убрать принудительный `-e authentik_enabled=false` из `ansible/ci/deploy-machine.sh` (или передать `authentik_enabled=true` при ручном прогоне) и выставить `authentik_enabled: true`. +3. Прогнать `ansible-core-net` (или `--tags authentik`): стек слушает `127.0.0.1:9000`, снаружи — `https://auth.gunihome.ru`. Blueprints заводят группы `admins`/`family` и пользователей `karpenok`/`ksynia`; пароли blueprint не задаёт. Первый запуск создаёт `akadmin` (пароль в логе `authentik-server`). +4. На нужных роутерах Traefik повесить middleware `authentik` (forwardAuth из `roles/core-net/traefik/files/dynamic/authentik.yml`) — точечно, не на все сервисы. ### Шаг 5. NetBird (rus-central) и связка с OPNsense 1. Запустить пайплайн **`ansible-rus-central`** в Gitea Actions. Ручной запуск сверяет машину целиком. Push в `roles/rus-central/netbird` ставит только NetBird. diff --git a/ansible/playbooks/rus-central.yml b/ansible/playbooks/rus-central.yml index 5fccc49..b94ea15 100644 --- a/ansible/playbooks/rus-central.yml +++ b/ansible/playbooks/rus-central.yml @@ -3,5 +3,7 @@ hosts: rus-central gather_facts: false roles: + - role: host + tags: [host] - role: rus-central/netbird tags: [netbird] diff --git a/ansible/roles/core-mon/monitoring/files/dashboards/node-exporter-full.json b/ansible/roles/core-mon/monitoring/files/dashboards/node-exporter-full.json index 1d91938..80c15d9 100644 --- a/ansible/roles/core-mon/monitoring/files/dashboards/node-exporter-full.json +++ b/ansible/roles/core-mon/monitoring/files/dashboards/node-exporter-full.json @@ -15505,13 +15505,13 @@ "type": "prometheus", "uid": "prometheus" }, - "definition": "label_values(node_uname_info{job=\"$job\"}, nodename)", + "definition": "label_values(node_uname_info{job=\"$job\"}, host)", "includeAll": false, - "label": "Nodename", + "label": "Host", "name": "nodename", "options": [], "query": { - "query": "label_values(node_uname_info{job=\"$job\"}, nodename)", + "query": "label_values(node_uname_info{job=\"$job\"}, host)", "refId": "Prometheus-nodename-Variable-Query" }, "refresh": 1, @@ -15525,13 +15525,13 @@ "type": "prometheus", "uid": "prometheus" }, - "definition": "label_values(node_uname_info{job=\"$job\", nodename=\"$nodename\"}, instance)", + "definition": "label_values(node_uname_info{job=\"$job\", host=\"$nodename\"}, instance)", "includeAll": false, "label": "Instance", "name": "node", "options": [], "query": { - "query": "label_values(node_uname_info{job=\"$job\", nodename=\"$nodename\"}, instance)", + "query": "label_values(node_uname_info{job=\"$job\", host=\"$nodename\"}, instance)", "refId": "Prometheus-node-Variable-Query" }, "refresh": 1, diff --git a/ansible/roles/core-mon/monitoring/tasks/main.yml b/ansible/roles/core-mon/monitoring/tasks/main.yml index 613f1fc..ca58ec4 100644 --- a/ansible/roles/core-mon/monitoring/tasks/main.yml +++ b/ansible/roles/core-mon/monitoring/tasks/main.yml @@ -18,6 +18,7 @@ - { path: "{{ monitoring_dir }}/grafana/provisioning/datasources", owner: "root", group: "root", mode: "0755" } - { path: "{{ monitoring_dir }}/grafana/provisioning/dashboards", owner: "root", group: "root", mode: "0755" } - { path: "{{ monitoring_dir }}/ntfy_data", owner: "root", group: "root", mode: "0777" } + - { path: "{{ monitoring_dir }}/alertmanager-ntfy", owner: "root", group: "root", mode: "0755" } - name: Установить конфигурацию Prometheus ansible.builtin.template: @@ -43,6 +44,14 @@ group: root mode: "0644" +- name: Установить конфигурацию alertmanager-ntfy + ansible.builtin.template: + src: alertmanager-ntfy.yml.j2 + dest: "{{ monitoring_dir }}/alertmanager-ntfy/config.yml" + owner: root + group: root + mode: "0644" + - name: Установить источник данных Prometheus в Grafana ansible.builtin.template: src: grafana-datasources.yml.j2 diff --git a/ansible/roles/core-mon/monitoring/templates/alertmanager-ntfy.yml.j2 b/ansible/roles/core-mon/monitoring/templates/alertmanager-ntfy.yml.j2 new file mode 100644 index 0000000..5ce056d --- /dev/null +++ b/ansible/roles/core-mon/monitoring/templates/alertmanager-ntfy.yml.j2 @@ -0,0 +1,34 @@ +http: + addr: :8000 + +ntfy: + baseurl: http://ntfy:80 + auth: + basic: + username: "{{ ntfy_admin_user }}" + password: "{{ ntfy_admin_password }}" + notification: + topic: "{{ ntfy_default_topic }}" + priority: | + status == "firing" ? (labels.severity == "critical" ? "urgent" : "high") : "default" + tags: + - tag: white_check_mark + condition: status == "resolved" + - tag: rotating_light + condition: status == "firing" && labels.severity == "critical" + - tag: warning + condition: status == "firing" && labels.severity != "critical" + templates: + title: | + {{ if eq .Status "resolved" }}✅ [Восстановлено] {{ index .Labels "alertname" }}: {{ if index .Labels "host" }}{{ index .Labels "host" }}{{ else }}{{ index .Labels "instance" }}{{ end }}{{ else }}🚨 [СБОЙ] {{ index .Annotations "summary" }}{{ end }} + description: | + {{ if eq .Status "resolved" }}Работа сервиса полностью восстановлена.{{ else }}{{ index .Annotations "description" }}{{ end }} + + Хост: {{ if index .Labels "host" }}{{ index .Labels "host" }}{{ else }}{{ index .Labels "instance" }}{{ end }} + Критичность: {{ index .Labels "severity" }} + headers: + X-Click: | + https://graf.gunihome.ru + X-Actions: | + view, 📊 Открыть Grafana, https://graf.gunihome.ru, clear=true + async: false diff --git a/ansible/roles/core-mon/monitoring/templates/alertmanager.yml.j2 b/ansible/roles/core-mon/monitoring/templates/alertmanager.yml.j2 index 29a9f91..2959853 100644 --- a/ansible/roles/core-mon/monitoring/templates/alertmanager.yml.j2 +++ b/ansible/roles/core-mon/monitoring/templates/alertmanager.yml.j2 @@ -11,10 +11,6 @@ route: receivers: - name: 'ntfy' webhook_configs: - - url: "http://ntfy:80/{{ ntfy_default_topic }}" + - url: "http://alertmanager-ntfy:8000/hook" send_resolved: true - http_config: - basic_auth: - username: "{{ ntfy_admin_user }}" - password: "{{ ntfy_admin_password }}" diff --git a/ansible/roles/core-mon/monitoring/templates/compose.yaml.j2 b/ansible/roles/core-mon/monitoring/templates/compose.yaml.j2 index 19316a1..a1559ad 100644 --- a/ansible/roles/core-mon/monitoring/templates/compose.yaml.j2 +++ b/ansible/roles/core-mon/monitoring/templates/compose.yaml.j2 @@ -51,6 +51,17 @@ services: ports: - "80:80" + alertmanager-ntfy: + image: ghcr.io/alexbakker/alertmanager-ntfy:latest + container_name: monitoring-alertmanager-ntfy + restart: unless-stopped + command: + - "--configs=/etc/alertmanager-ntfy/config.yml" + volumes: + - ./alertmanager-ntfy/config.yml:/etc/alertmanager-ntfy/config.yml:ro + depends_on: + - ntfy + grafana: image: grafana/grafana:11.5.2 container_name: monitoring-grafana diff --git a/ansible/roles/host/tasks/main.yml b/ansible/roles/host/tasks/main.yml index 8fe1625..a13c914 100644 --- a/ansible/roles/host/tasks/main.yml +++ b/ansible/roles/host/tasks/main.yml @@ -6,6 +6,19 @@ - name: Собрать факты ansible.builtin.setup: +- name: Установить hostname хоста + ansible.builtin.hostname: + name: "{{ inventory_hostname }}" + failed_when: false + +- name: Обеспечить запись inventory_hostname в /etc/hosts + ansible.builtin.lineinfile: + path: /etc/hosts + line: "127.0.1.1 {{ inventory_hostname }}" + regexp: '^127\.0\.1\.1\s+' + state: present + failed_when: false + - name: Создать каталог .ssh ansible.builtin.file: path: /root/.ssh