ci: add GitLab build and k3s deploy pipeline

This commit is contained in:
nyan404 committed 2026-08-16 17:15:41 +03:00
1 parent c15fc81178
commit 057e5c81bd
8 files changed
+140 -11

No files matched your search

+1
View File
@@ -9,6 +9,7 @@ env/
.env .env
.env.* .env.*
!.env.example !.env.example
.gitlab.variables.env
data/*.sqlite3 data/*.sqlite3
data/*.db data/*.db
+43 -7
View File
@@ -1,8 +1,10 @@
stages: stages:
- build - build
- deploy
variables: variables:
DOCKER_IMAGE: $DOCKER_REGISTRY/belki:latest DOCKER_IMAGE_REPOSITORY: $DOCKER_REGISTRY/cwshed-clone/belki
KUBE_NAMESPACE: belki
DOCKER_HOST: tcp://docker:2375 DOCKER_HOST: tcp://docker:2375
build: build:
stage: build stage: build
@@ -18,10 +20,44 @@ build:
# Docker Registry # Docker Registry
- echo "$DOCKER_PASSWORD" | docker login $DOCKER_REGISTRY -u "$DOCKER_USERNAME" --password-stdin - echo "$DOCKER_PASSWORD" | docker login $DOCKER_REGISTRY -u "$DOCKER_USERNAME" --password-stdin
# Docker build over dind - export IMAGE_TAG="$CI_COMMIT_SHORT_SHA"
- docker build -t $DOCKER_IMAGE . - docker build --pull -t "$DOCKER_IMAGE_REPOSITORY:$IMAGE_TAG" -t "$DOCKER_IMAGE_REPOSITORY:latest" .
- docker push "$DOCKER_IMAGE_REPOSITORY:$IMAGE_TAG"
- docker push "$DOCKER_IMAGE_REPOSITORY:latest"
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
# Push the resulting image deploy:
- docker push $DOCKER_IMAGE stage: deploy
only: image: bitnami/kubectl:1.34
- main needs: [build]
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
before_script:
- test -n "$KUBE_CONFIG_B64"
- test -n "$VK_GROUP_TOKEN"
- test -n "$VK_GROUP_ID"
- test -n "$BELKI_DATABASE_URL"
- test -n "$POSTGRES_PASSWORD"
- test -n "$BELKI_ADMIN_PASSWORD"
- mkdir -p "$CI_PROJECT_DIR/.kube"
- printf '%s' "$KUBE_CONFIG_B64" | base64 -d > "$CI_PROJECT_DIR/.kube/config"
- export KUBECONFIG="$CI_PROJECT_DIR/.kube/config"
- kubectl version --client
- kubectl -n "$KUBE_NAMESPACE" get serviceaccount gitlab-deploy
script:
- kubectl -n "$KUBE_NAMESPACE" create secret generic belki-runtime
--from-literal=VK_GROUP_TOKEN="$VK_GROUP_TOKEN"
--from-literal=VK_GROUP_ID="$VK_GROUP_ID"
--from-literal=VK_API_VERSION="${VK_API_VERSION:-5.199}"
--from-literal=BELKI_DATABASE_URL="$BELKI_DATABASE_URL"
--from-literal=POSTGRES_PASSWORD="$POSTGRES_PASSWORD"
--from-literal=BELKI_ADMIN_PASSWORD="$BELKI_ADMIN_PASSWORD"
--dry-run=client -o yaml | kubectl apply -f -
- sed "s#reg.nyan404.ru/cwshed-clone/belki:6b74dfa#$DOCKER_IMAGE_REPOSITORY:$CI_COMMIT_SHORT_SHA#g" deploy/k8s/production.yaml | kubectl apply -f -
- kubectl -n "$KUBE_NAMESPACE" rollout status deployment/belki-postgres --timeout=180s
- kubectl -n "$KUBE_NAMESPACE" rollout status deployment/belki-web --timeout=180s
- kubectl -n "$KUBE_NAMESPACE" rollout status deployment/belki-bot --timeout=180s
- kubectl -n "$KUBE_NAMESPACE" get pods,svc
after_script:
- rm -rf "$CI_PROJECT_DIR/.kube"
+3 -2
View File
@@ -7,15 +7,16 @@
## Working Rules ## Working Rules
- Keep the calculation domain independent from HTTP, VK, and Kubernetes. - Keep the calculation domain independent from HTTP, VK, and Kubernetes.
- Keep VK tokens and group IDs out of the repository; use environment variables or Kubernetes Secrets. - Keep VK tokens and group IDs out of the repository; use environment variables or Kubernetes Secrets.
- Do not apply `deploy/k8s/` until the bot commands, report wording, registry image name, service exposure, and Secret handoff are explicitly confirmed. - Production manifests are already applied in namespace `belki`; CI deploys them from `main` using the namespace-scoped RBAC in [`deploy/k8s/rbac.yaml`](./deploy/k8s/rbac.yaml).
- Prefer `docker:dind` for CI unless the target runner is explicitly pinned and known to expose `/var/run/docker.sock`. - Prefer `docker:dind` for CI unless the target runner is explicitly pinned and known to expose `/var/run/docker.sock`.
## Validation ## Validation
- For CI-only changes, prefer a targeted YAML parse and a diff review. - For CI-only changes, prefer a targeted YAML parse and a diff review.
- For image/runtime changes, check the `Dockerfile`, Python entrypoint, static asset serving, and CI job together. - For image/runtime changes, check the `Dockerfile`, Python entrypoint, static asset serving, and CI job together.
- For k3s changes, validate YAML and current cluster inventory first; deployment is currently deferred. - For k3s changes, validate YAML and current cluster inventory first; keep `KUBE_CONFIG_B64` masked/protected in GitLab.
- Do not add unnecessary local build artifacts or temporary files to the repository. - Do not add unnecessary local build artifacts or temporary files to the repository.
## Notes ## Notes
- `docker:dind` requires a privileged Docker executor and `DOCKER_HOST=tcp://docker:2375` with `DOCKER_TLS_CERTDIR=""`. - `docker:dind` requires a privileged Docker executor and `DOCKER_HOST=tcp://docker:2375` with `DOCKER_TLS_CERTDIR=""`.
- The `dind` daemon can take time to initialize; this repo waits for `docker info` before building. - The `dind` daemon can take time to initialize; this repo waits for `docker info` before building.
- Never commit `.env` or `.gitlab.variables.env`; the latter contains the GitLab Variable handoff and a namespace-scoped kubeconfig.
+1
View File
@@ -20,3 +20,4 @@
- The admin history is served at `/admin`; `/api/admin/calculations` requires `BELKI_ADMIN_PASSWORD` via `X-Admin-Password` and supports sorting by kitten ID/name. The password is configured out-of-band and is not stored in browser localStorage. - The admin history is served at `/admin`; `/api/admin/calculations` requires `BELKI_ADMIN_PASSWORD` via `X-Admin-Password` and supports sorting by kitten ID/name. The password is configured out-of-band and is not stored in browser localStorage.
- The new domain uses 5 minutes = 1 adult point and 5 minutes = 2 kitten points; a non-self-sufficient main kitten gives the adult a 1.5x multiplier and each additional non-self-sufficient kitten adds 0.5x, matching the inspected Google Sheet formulas. - The new domain uses 5 minutes = 1 adult point and 5 minutes = 2 kitten points; a non-self-sufficient main kitten gives the adult a 1.5x multiplier and each additional non-self-sufficient kitten adds 0.5x, matching the inspected Google Sheet formulas.
- 2026-08-16 production deployment: namespace `belki` is live in k3s. Web and bot use `reg.nyan404.ru/cwshed-clone/belki:6b74dfa`; PostgreSQL uses the amd64 mirror `reg.nyan404.ru/library/postgres:16-alpine-amd64` on Longhorn. The web LoadBalancer is MetalLB `10.12.0.212`; route `cat.nyan404.ru/belki` through the external Nginx to that IP. Runtime credentials remain only in the cluster Secret `belki-runtime`. - 2026-08-16 production deployment: namespace `belki` is live in k3s. Web and bot use `reg.nyan404.ru/cwshed-clone/belki:6b74dfa`; PostgreSQL uses the amd64 mirror `reg.nyan404.ru/library/postgres:16-alpine-amd64` on Longhorn. The web LoadBalancer is MetalLB `10.12.0.212`; route `cat.nyan404.ru/belki` through the external Nginx to that IP. Runtime credentials remain only in the cluster Secret `belki-runtime`.
- GitLab CI/CD now builds SHA/latest tags and deploys `deploy/k8s/production.yaml` from `main`. The ignored `.gitlab.variables.env` is a local handoff for GitLab Variables; CI uses namespace-scoped ServiceAccount `belki/gitlab-deploy`, not cluster-admin credentials.
+43
View File
@@ -0,0 +1,43 @@
apiVersion: v1
kind: ServiceAccount
metadata:
name: gitlab-deploy
namespace: belki
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: gitlab-deploy
namespace: belki
rules:
- apiGroups: [""]
resources:
- configmaps
- events
- persistentvolumeclaims
- pods
- pods/log
- secrets
- services
verbs: [get, list, watch, create, update, patch]
- apiGroups: ["apps"]
resources:
- deployments
- deployments/status
- replicasets
- replicasets/status
verbs: [get, list, watch, create, update, patch]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: gitlab-deploy
namespace: belki
subjects:
- kind: ServiceAccount
name: gitlab-deploy
namespace: belki
roleRef:
kind: Role
name: gitlab-deploy
apiGroup: rbac.authorization.k8s.io
+2 -1
View File
@@ -1,7 +1,7 @@
apiVersion: v1 apiVersion: v1
kind: Secret kind: Secret
metadata: metadata:
name: belki-vk name: belki-runtime
namespace: belki namespace: belki
type: Opaque type: Opaque
stringData: stringData:
@@ -9,4 +9,5 @@ stringData:
VK_GROUP_ID: replace-out-of-band VK_GROUP_ID: replace-out-of-band
VK_API_VERSION: "5.199" VK_API_VERSION: "5.199"
BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki
POSTGRES_PASSWORD: replace-out-of-band
BELKI_ADMIN_PASSWORD: replace-out-of-band BELKI_ADMIN_PASSWORD: replace-out-of-band
+44
View File
@@ -0,0 +1,44 @@
# GitLab CI/CD для «Беличьей норы»
`.gitlab-ci.yml` выполняет два шага на `main`:
1. Собирает образ и публикует его в `reg.nyan404.ru/cwshed-clone/belki` с тегами короткого SHA и `latest`.
2. Подключается к k3s namespace `belki`, обновляет runtime Secret, применяет `deploy/k8s/production.yaml` и ждёт готовности web, bot и PostgreSQL.
## Переменные GitLab
Файл `.gitlab.variables.env` рядом с локальным `.env` содержит подготовленные значения для текущего окружения. Он игнорируется Git и имеет права `0600`; его нельзя коммитить или пересылать в открытом виде.
Добавьте в GitLab → Settings → CI/CD → Variables:
| Переменная | Назначение | Защита |
| --- | --- | --- |
| `DOCKER_REGISTRY` | `reg.nyan404.ru` | masked, protected |
| `DOCKER_USERNAME` | пользователь registry | masked, protected |
| `DOCKER_PASSWORD` | пароль registry | masked, protected |
| `DOCKER_IMAGE_REPOSITORY` | `reg.nyan404.ru/cwshed-clone/belki` | protected |
| `KUBE_NAMESPACE` | `belki` | protected |
| `KUBE_CONFIG_B64` | base64 kubeconfig для ServiceAccount `gitlab-deploy` | masked, protected |
| `VK_GROUP_TOKEN` | токен VK-группы | masked, protected |
| `VK_GROUP_ID` | ID VK-группы | protected |
| `VK_API_VERSION` | обычно `5.199` | protected |
| `BELKI_DATABASE_URL` | DSN PostgreSQL внутри k3s | masked, protected |
| `POSTGRES_PASSWORD` | пароль PostgreSQL | masked, protected |
| `BELKI_ADMIN_PASSWORD` | пароль `/admin` | masked, protected |
`KUBE_CONFIG_B64` уже ограничен namespace `belki`: CI использует отдельные `ServiceAccount`, `Role` и `RoleBinding` из [`deploy/k8s/rbac.yaml`](../deploy/k8s/rbac.yaml), а не кластерный admin-доступ.
При смене токена VK или паролей достаточно обновить соответствующие GitLab Variables: deploy-job применит `belki-runtime` заново. Для изменения PostgreSQL-пароля существующей базы потребуется отдельная процедура, поскольку пароль уже хранится внутри кластера.
## Ручная проверка
Для проверки без CI используйте тот же kubeconfig и манифест:
```sh
export KUBECONFIG=/path/to/kubeconfig
kubectl -n belki apply -f deploy/k8s/rbac.yaml
kubectl -n belki apply -f deploy/k8s/production.yaml
kubectl -n belki rollout status deployment/belki-web --timeout=180s
```
MetalLB адрес web-сервиса — `10.12.0.212`; внешний Nginx проксирует на него путь `cat.nyan404.ru/belki`.
+3 -1
View File
@@ -5,7 +5,8 @@
- [`Dockerfile`](./Dockerfile): Python 3.12 runtime image for the calculator web service and shared static assets. - [`Dockerfile`](./Dockerfile): Python 3.12 runtime image for the calculator web service and shared static assets.
- [`app/`](./app): calculation domain, report templates, JSON API, HTTP server, and VK Bots Long Poll adapter. - [`app/`](./app): calculation domain, report templates, JSON API, HTTP server, and VK Bots Long Poll adapter.
- [`web/`](./web): calculator frontend plus legacy CatWar userscript assets. - [`web/`](./web): calculator frontend plus legacy CatWar userscript assets.
- [`deploy/k8s/`](./deploy/k8s): namespace and production web/bot/PostgreSQL manifests. - [`deploy/k8s/`](./deploy/k8s): namespace, production web/bot/PostgreSQL manifests, and namespace-scoped CI deploy RBAC.
- [`docs/GITLAB_CI_CD.md`](./docs/GITLAB_CI_CD.md): GitLab variables and CI/CD handoff.
- [`tests/`](./tests): standard-library unit tests for calculation, reports, API, and VK parsing. - [`tests/`](./tests): standard-library unit tests for calculation, reports, API, and VK parsing.
- [`docs/staging/`](./docs/staging): working specification and implementation plan for the Belki calculator. - [`docs/staging/`](./docs/staging): working specification and implementation plan for the Belki calculator.
- [`AGENTS.md`](./AGENTS.md): repo-specific instructions for future coding agents. - [`AGENTS.md`](./AGENTS.md): repo-specific instructions for future coding agents.
@@ -39,3 +40,4 @@
- 2026-08-16: made bulk entry conversational and separator-free; added API/web inspection and clarification flow. - 2026-08-16: made bulk entry conversational and separator-free; added API/web inspection and clarification flow.
- 2026-08-16: rewrote VK help, welcome, and web hints as a concise neutral FAQ; command behavior is unchanged. - 2026-08-16: rewrote VK help, welcome, and web hints as a concise neutral FAQ; command behavior is unchanged.
- 2026-08-16: added the calculator/VK links to the CatWar home page and deployed the calculator stack to k3s; MetalLB assigned `10.12.0.212`. - 2026-08-16: added the calculator/VK links to the CatWar home page and deployed the calculator stack to k3s; MetalLB assigned `10.12.0.212`.
- 2026-08-16: added GitLab build/deploy stages, namespace-scoped `gitlab-deploy` RBAC, and the ignored local variables handoff `.gitlab.variables.env`.