From cd34e7413d59bf2f48f585cd58449cc3072864eb Mon Sep 17 00:00:00 2001 From: 0xFEEDC0DE64 Date: Sat, 8 Aug 2026 22:26:36 +0200 Subject: [PATCH] Initial commit of my existing home-assistant config files and CI --- .gitea/workflows/deploy.yml | 97 ++++++++++++++++++++ .gitignore | 14 +++ README.md | 177 +++++++++++++++++++++++++++++++++++- ci-deployer.yaml | 79 ++++++++++++++++ create-ci-kubeconfig.sh | 48 ++++++++++ home-assistant.yaml | 123 +++++++++++++++++++++++++ install.sh | 18 ++++ test.sh | 28 ++++++ 8 files changed, 582 insertions(+), 2 deletions(-) create mode 100644 .gitea/workflows/deploy.yml create mode 100644 .gitignore create mode 100644 ci-deployer.yaml create mode 100755 create-ci-kubeconfig.sh create mode 100644 home-assistant.yaml create mode 100755 install.sh create mode 100755 test.sh diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 0000000..4dddab5 --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,97 @@ +name: Validate and deploy Home Assistant + +on: + push: + pull_request: + +env: + KUBECONFORM_VERSION: v0.7.0 + KUBECTL_VERSION: v1.36.3 + KUBERNETES_API: https://host.containers.internal:6443 + KUBERNETES_TLS_SERVER_NAME: 192.168.0.2 + NAMESPACE: default + +jobs: + validate: + name: Validate manifests + runs-on: ubuntu-latest + steps: + - name: Check out source + uses: actions/checkout@v4 + + - name: Validate scripts and Kubernetes resources + run: | + bash -n install.sh + bash -n create-ci-kubeconfig.sh + bash -n test.sh + docker run --rm --interactive \ + "ghcr.io/yannh/kubeconform:${KUBECONFORM_VERSION}@sha256:85dbef6b4b312b99133decc9c6fc9495e9fc5f92293d4ff3b7e1b30f5611823c" \ + -strict -summary < home-assistant.yaml + docker run --rm --interactive \ + "ghcr.io/yannh/kubeconform:${KUBECONFORM_VERSION}@sha256:85dbef6b4b312b99133decc9c6fc9495e9fc5f92293d4ff3b7e1b30f5611823c" \ + -strict -summary < ci-deployer.yaml + + deploy: + name: Deploy to Kubernetes + if: gitea.ref == 'refs/heads/main' + needs: validate + runs-on: ubuntu-latest + steps: + - name: Check out source + uses: actions/checkout@v4 + + - name: Install kubectl + run: | + curl --fail --silent --show-error --location \ + --output "${RUNNER_TEMP}/kubectl" \ + "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl" + curl --fail --silent --show-error --location \ + --output "${RUNNER_TEMP}/kubectl.sha256" \ + "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl.sha256" + printf '%s %s\n' "$(cat "${RUNNER_TEMP}/kubectl.sha256")" "${RUNNER_TEMP}/kubectl" | sha256sum --check + chmod 0700 "${RUNNER_TEMP}/kubectl" + + - name: Configure Kubernetes access + env: + KUBE_CONFIG_BASE64: ${{ secrets.KUBE_CONFIG_BASE64 }} + run: | + test -n "${KUBE_CONFIG_BASE64}" + printf '%s' "${KUBE_CONFIG_BASE64}" | base64 --decode > "${RUNNER_TEMP}/kubeconfig" + chmod 0600 "${RUNNER_TEMP}/kubeconfig" + export KUBECONFIG="${RUNNER_TEMP}/kubeconfig" + "${RUNNER_TEMP}/kubectl" config set-cluster cluster \ + --server="${KUBERNETES_API}" \ + --tls-server-name="${KUBERNETES_TLS_SERVER_NAME}" + + - name: Apply and verify + run: | + export KUBECONFIG="${RUNNER_TEMP}/kubeconfig" + "${RUNNER_TEMP}/kubectl" apply \ + --dry-run=server \ + --validate=false \ + --filename home-assistant.yaml + "${RUNNER_TEMP}/kubectl" apply \ + --validate=false \ + --filename home-assistant.yaml + + for attempt in {1..120}; do + IFS='|' read -r generation observed desired updated available unavailable <<< "$( + "${RUNNER_TEMP}/kubectl" --namespace "${NAMESPACE}" \ + get deployment/home-assistant \ + --output=jsonpath='{.metadata.generation}|{.status.observedGeneration}|{.spec.replicas}|{.status.updatedReplicas}|{.status.availableReplicas}|{.status.unavailableReplicas}' + )" + + echo "Rollout ${attempt}/120: generation ${observed}/${generation}, replicas ${updated}/${desired} updated, ${available}/${desired} available" + if [[ "${observed}" == "${generation}" \ + && "${updated}" == "${desired}" \ + && "${available}" == "${desired}" \ + && ( -z "${unavailable}" || "${unavailable}" == "0" ) ]]; then + echo "Home Assistant deployment successfully rolled out" + exit 0 + fi + + sleep 5 + done + + echo "Home Assistant rollout did not complete within ten minutes" >&2 + exit 1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9754e14 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +# Generated deployment and CI credentials +kubeconfig +*.kubeconfig +rendered.yaml +.env + +# Home Assistant runtime state and backups must never enter this repository +configuration.yaml +secrets.yaml +.storage/ +home-assistant_v2.db* +*.tar +*.tar.gz +*.zip diff --git a/README.md b/README.md index 6d88198..d21b654 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,176 @@ -# home-assistant-kubernetes +# Home Assistant on Kubernetes -My kubernetes configuration files to run home-assistant in my kubernetes cluster \ No newline at end of file +Production deployment for the brunner.ninja Home Assistant instance. It runs +the official Home Assistant Container image with persistent Ceph storage, +host networking, a MetalLB address, and Traefik ingress. + +This repository installs **Home Assistant Container**, not Home Assistant OS or +Home Assistant Supervised. It therefore does not include the Supervisor, +add-ons, or the Home Assistant OS backup interface. See the official +[Home Assistant installation documentation](https://www.home-assistant.io/installation/) +for the differences between installation types. + +## Architecture + +- `ghcr.io/home-assistant/home-assistant:stable` runs as one privileged replica. +- Host networking supports discovery protocols used by home-automation devices. +- `default/home-assistant-pvc` provides 10 Gi from `rook-ceph-block` at `/config`. +- MetalLB advertises `192.168.0.15`; Home Assistant listens on TCP port 8123. +- Traefik publishes `homeass.brunner.ninja` over its `websecure` entrypoint. +- Traefik's existing default `*.brunner.ninja` certificate supplies TLS. +- The `/auth` route uses `default-authentik@kubernetescrd` so Home Assistant's + authentication callbacks are not intercepted by Authentik. +- The `Recreate` strategy prevents two Home Assistant processes from writing + the same config volume during an update. + +The configuration follows Home Assistant's official +[container installation](https://www.home-assistant.io/installation/linux/), +including `/config` persistence, host networking, and privileged access. + +## Repository contents + +- `home-assistant.yaml`: Deployment, PVC, LoadBalancer Service, and ingresses. +- `install.sh`: server-side dry-run, apply, and rollout verification. +- `test.sh`: local script and offline Kubernetes schema validation. +- `ci-deployer.yaml`: restricted Gitea Actions ServiceAccount, Role, binding, + and revocable token. +- `create-ci-kubeconfig.sh`: one-time CI identity bootstrap. +- `.gitea/workflows/deploy.yml`: validation on every push and pull request; + deployment after successful validation of `main`. + +No Home Assistant configuration, database, backup, Kubernetes Secret, or +kubeconfig belongs in this repository. + +## Prerequisites + +For the manifest as committed: + +- Kubernetes and kubectl. +- StorageClass `rook-ceph-block`. +- MetalLB pool `default` containing the reserved address `192.168.0.15`. +- A cluster policy that permits privileged containers and host networking. +- Traefik ingress class `traefik`, with `*.brunner.ninja` configured as its + default TLS certificate. +- Authentik middleware `default-authentik` in namespace `default`. + +Another cluster operator can reuse the file by changing the namespace, +StorageClass, timezone, load-balancer address, hostname, ingress class, and +optional Authentik middleware directly in `home-assistant.yaml`. + +Host networking means port 8123 must be free on the selected node. A cluster +that does not need local-network discovery can remove `hostNetwork` and the +matching `ClusterFirstWithHostNet` DNS policy. + +## Install or restore manually + +Run with an administrator kubeconfig: + +```sh +./install.sh +``` + +The script first asks the Kubernetes API for a server-side dry-run, applies the +same manifest, and waits up to ten minutes for the Deployment. All resource +names match the long-running installation, so this updates it in place and +continues using the bound `default/home-assistant-pvc`. Applying the manifest +does not recreate or empty that claim. + +Home Assistant is then available at: + +- `https://homeass.brunner.ninja` +- `http://192.168.0.15:8123` + +### Reverse proxy configuration + +Home Assistant must explicitly trust a reverse proxy before accepting its +forwarded client addresses. Configure the actual Traefik source addresses or +pod network in `/config/configuration.yaml`, choosing the narrowest correct +range: + +```yaml +http: + use_x_forwarded_for: true + trusted_proxies: + - 10.42.0.0/16 # example only; replace with the actual Traefik source range +``` + +Do not copy the example network blindly. The details are documented in Home +Assistant's [HTTP integration proxy settings](https://www.home-assistant.io/integrations/http/#reverse-proxies). + +## Back up and restore + +The Git repository reconstructs the Kubernetes objects, but **not Home +Assistant's state**. `/config` contains configuration, users, automations, +integrations, and the default SQLite database. Back up the PVC with Ceph +snapshots or a separate volume-backup system. + +The `rook-ceph-block` StorageClass has a `Delete` reclaim policy on this cluster, +so deleting the claim can also delete its backing volume. Never delete +`home-assistant-pvc` during a normal reinstall. + +Before a consistent filesystem-level restore, stop Home Assistant without +deleting its PVC: + +```sh +kubectl scale deployment/home-assistant --replicas=0 -n default +``` + +Restore `/config`, then run `./install.sh` to recreate or update the Deployment. + +## Validate locally + +```sh +./test.sh +``` + +The test checks all shell scripts and validates `home-assistant.yaml` and +`ci-deployer.yaml` with kubeconform without contacting Kubernetes. It uses a +local kubeconform binary when available, otherwise the pinned +`ghcr.io/yannh/kubeconform:v0.7.0` container through Docker. + +## Automatic deployment with Gitea Actions + +The workflow validates every push and pull request. A successful push to +`main` performs a server-side dry-run, applies `home-assistant.yaml`, and polls +the Deployment for up to ten minutes. + +CI cannot create or delete resources. Its namespace Role can only get, patch, +and update these existing named objects: + +- Deployment `home-assistant`; +- Service `home-assistant`; +- PVC `home-assistant-pvc`; +- Ingresses `home-assistant` and `home-assistant-auth`. + +It has no Kubernetes Secrets API access. First installation and RBAC bootstrap +remain administrator operations. + +### One-time CI setup + +1. Run `./install.sh` with an administrator identity so the workload resources + exist. +2. Run: + + ```sh + ./create-ci-kubeconfig.sh + ``` + +3. Copy only the final base64 line into the Gitea repository Actions secret + named `KUBE_CONFIG_BASE64`. +4. Protect `main`, require the validation job before merging, and review + manifest and workflow changes. +5. Push a harmless README change and confirm the deploy job succeeds. + +The workflow matches the existing brunner.ninja runner: Kubernetes API URL +`https://host.containers.internal:6443`, with TLS server name `192.168.0.2`. +Other clusters must change those workflow variables. + +The generated credential is a random Kubernetes service-account token, not a +human-chosen password. Treat the printed kubeconfig as a password. Revoke it by +deleting `default/home-assistant-deployer-token` and the Gitea Actions secret. +Rerunning the wrapper creates a replacement. + +Kubernetes RBAC cannot constrain individual fields inside an allowed +Deployment patch. A malicious change merged into `main` could alter the pod +specification. Branch protection and review therefore remain part of the +security boundary; admission policy is needed for field-level restrictions. diff --git a/ci-deployer.yaml b/ci-deployer.yaml new file mode 100644 index 0000000..eb4ff34 --- /dev/null +++ b/ci-deployer.yaml @@ -0,0 +1,79 @@ +# Bootstrap this file once with an administrator identity. CI can update only +# the existing Home Assistant resources and cannot call the Secrets API. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: home-assistant-deployer + namespace: default +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: home-assistant-deployer + namespace: default +rules: + - apiGroups: + - "" + resources: + - services + resourceNames: + - home-assistant + verbs: + - get + - patch + - update + - apiGroups: + - "" + resources: + - persistentvolumeclaims + resourceNames: + - home-assistant-pvc + verbs: + - get + - patch + - update + - apiGroups: + - apps + resources: + - deployments + resourceNames: + - home-assistant + verbs: + - get + - patch + - update + - apiGroups: + - networking.k8s.io + resources: + - ingresses + resourceNames: + - home-assistant + - home-assistant-auth + verbs: + - get + - patch + - update +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: home-assistant-deployer + namespace: default +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: home-assistant-deployer +subjects: + - kind: ServiceAccount + name: home-assistant-deployer + namespace: default +--- +apiVersion: v1 +kind: Secret +metadata: + name: home-assistant-deployer-token + namespace: default + annotations: + kubernetes.io/service-account.name: home-assistant-deployer +type: kubernetes.io/service-account-token diff --git a/create-ci-kubeconfig.sh b/create-ci-kubeconfig.sh new file mode 100755 index 0000000..418b8c3 --- /dev/null +++ b/create-ci-kubeconfig.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash + +set -euo pipefail + +project_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +namespace=${NAMESPACE:-default} +service_account=${SERVICE_ACCOUNT:-home-assistant-deployer} +secret=${TOKEN_SECRET:-home-assistant-deployer-token} + +kubectl apply --filename "${project_dir}/ci-deployer.yaml" >&2 + +for attempt in {1..30}; do + if kubectl --namespace "${namespace}" get secret "${secret}" \ + --output=jsonpath='{.data.token}' 2>/dev/null | grep -q .; then + break + fi + if [[ "${attempt}" == 30 ]]; then + echo "Timed out waiting for the service-account token" >&2 + exit 1 + fi + sleep 1 +done + +workdir=$(mktemp --directory) +trap 'rm -rf "${workdir}"' EXIT + +server=$(kubectl config view --minify --output=jsonpath='{.clusters[0].cluster.server}') +kubectl --namespace "${namespace}" get secret "${secret}" \ + --output=jsonpath='{.data.ca\.crt}' | base64 --decode > "${workdir}/ca.crt" +token=$(kubectl --namespace "${namespace}" get secret "${secret}" \ + --output=jsonpath='{.data.token}' | base64 --decode) + +export KUBECONFIG="${workdir}/config" +kubectl config set-cluster cluster \ + --server="${server}" \ + --certificate-authority="${workdir}/ca.crt" \ + --embed-certs=true >/dev/null +kubectl config set-credentials "${service_account}" --token="${token}" >/dev/null +kubectl config set-context home-assistant \ + --cluster=cluster \ + --user="${service_account}" \ + --namespace="${namespace}" >/dev/null +kubectl config use-context home-assistant >/dev/null + +echo "Store the following single line as the Gitea Actions secret KUBE_CONFIG_BASE64." >&2 +echo "Treat it as a password; do not commit it." >&2 +base64 --wrap=0 "${KUBECONFIG}" +printf '\n' diff --git a/home-assistant.yaml b/home-assistant.yaml new file mode 100644 index 0000000..0c770af --- /dev/null +++ b/home-assistant.yaml @@ -0,0 +1,123 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: home-assistant + namespace: default + labels: + app: home-assistant + app.kubernetes.io/name: home-assistant +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app: home-assistant + template: + metadata: + labels: + app: home-assistant + app.kubernetes.io/name: home-assistant + spec: + automountServiceAccountToken: false + hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet + containers: + - name: home-assistant + image: ghcr.io/home-assistant/home-assistant:stable + imagePullPolicy: Always + securityContext: + privileged: true + ports: + - name: http + containerPort: 8123 + protocol: TCP + env: + - name: TZ + value: Europe/Vienna + volumeMounts: + - name: home-assistant-config-volume + mountPath: /config + volumes: + - name: home-assistant-config-volume + persistentVolumeClaim: + claimName: home-assistant-pvc +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: home-assistant-pvc + namespace: default + labels: + app.kubernetes.io/name: home-assistant +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 10Gi + storageClassName: rook-ceph-block +--- +apiVersion: v1 +kind: Service +metadata: + name: home-assistant + namespace: default + labels: + app: home-assistant + app.kubernetes.io/name: home-assistant + annotations: + metallb.io/address-pool: default +spec: + type: LoadBalancer + loadBalancerIP: 192.168.0.15 + selector: + app: home-assistant + ports: + - name: http + protocol: TCP + port: 8123 + targetPort: 8123 +--- +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: home-assistant + namespace: default + annotations: + traefik.ingress.kubernetes.io/router.entrypoints: websecure +spec: + ingressClassName: traefik + rules: + - host: homeass.brunner.ninja + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: home-assistant + port: + name: http +--- +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: home-assistant-auth + namespace: default + annotations: + traefik.ingress.kubernetes.io/router.entrypoints: websecure + traefik.ingress.kubernetes.io/router.middlewares: default-authentik@kubernetescrd +spec: + ingressClassName: traefik + rules: + - host: homeass.brunner.ninja + http: + paths: + - path: /auth + pathType: Prefix + backend: + service: + name: home-assistant + port: + name: http diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..7173896 --- /dev/null +++ b/install.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +set -euo pipefail + +project_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +namespace=default + +if ! command -v kubectl >/dev/null 2>&1; then + echo "Required command not found: kubectl" >&2 + exit 1 +fi + +kubectl apply --dry-run=server --filename "${project_dir}/home-assistant.yaml" +kubectl apply --filename "${project_dir}/home-assistant.yaml" +kubectl --namespace "${namespace}" rollout status deployment/home-assistant --timeout=10m + +echo +echo "Home Assistant is available at https://homeass.brunner.ninja and http://192.168.0.15:8123." diff --git a/test.sh b/test.sh new file mode 100755 index 0000000..a4a6e7e --- /dev/null +++ b/test.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash + +set -euo pipefail + +project_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) + +bash -n "${project_dir}/install.sh" +bash -n "${project_dir}/create-ci-kubeconfig.sh" + +validate_file() { + local manifest=$1 + + if command -v kubeconform >/dev/null 2>&1; then + kubeconform -strict -summary "${manifest}" + elif command -v docker >/dev/null 2>&1; then + docker run --rm --interactive \ + ghcr.io/yannh/kubeconform:v0.7.0@sha256:85dbef6b4b312b99133decc9c6fc9495e9fc5f92293d4ff3b7e1b30f5611823c \ + -strict -summary < "${manifest}" + else + echo "Required command not found: install kubeconform or Docker" >&2 + exit 1 + fi +} + +validate_file "${project_dir}/home-assistant.yaml" +validate_file "${project_dir}/ci-deployer.yaml" + +echo "Home Assistant scripts and Kubernetes resources are valid."