Skip to content

Development Guide

This document provides detailed instructions for developing and contributing to the Home Assistant Kubernetes integration.

Prerequisites

  • Python 3.13 or higher
  • Home Assistant 2026.4 or higher
  • A Kubernetes cluster for testing (minikube, kind, or cloud-based)
  • Git
  • Helm — only needed when changing RBAC. Use the version pinned in .github/workflows/helm.yaml (azure/setup-helm); see RBAC and the Helm Chart

Development Environment Setup

1. Clone the Repository

git clone https://github.com/tibuntu/homeassistant-kubernetes.git
cd homeassistant-kubernetes

2. Set Up a Virtual Environment

CI installs the exact versions pinned in uv.lock. The quickest way to get the same environment is uv (Python 3.14.2+, the minimum of the pinned Home Assistant):

# Create .venv and install the locked dev dependencies
uv sync --extra dev
source .venv/bin/activate

Without uv, a plain virtual environment works too, but it resolves the unpinned transitive dependencies afresh:

python3 -m venv venv
source venv/bin/activate
pip install -e ".[dev]"

After changing dependencies in pyproject.toml, run uv lock and commit the updated uv.lock — CI's uv sync --locked fails when the two disagree. Renovate refreshes the lock file's transitive dependencies weekly (lock file maintenance, Sundays).

Then link the integration into a Home Assistant config directory:

# Create Home Assistant config directory
mkdir -p config/custom_components
ln -sf "$(pwd)/custom_components/kubernetes" "config/custom_components/kubernetes"

Project Structure

homeassistant-kubernetes/
├── custom_components/
│   └── kubernetes/
│       ├── __init__.py              # Main integration file (panel registration, WS setup)
│       ├── manifest.json            # Integration metadata
│       ├── config_flow.py           # Configuration flow
│       ├── const.py                 # Constants and configuration keys
│       ├── coordinator.py           # Data coordinator + entry runtime-data types
│       ├── sensor.py                # Sensor platform
│       ├── binary_sensor.py         # Binary sensor platform
│       ├── switch.py                # Switch platform (workload control)
│       ├── number.py                # Number platform (replica count)
│       ├── services.py              # HA services (scale, start, stop)
│       ├── device.py                # Device registry management
│       ├── kubernetes_client.py     # Kubernetes API client
│       ├── websocket_api.py         # WebSocket API for the sidebar panel
│       ├── icons.json               # Entity icons (icon translations)
│       ├── frontend/
│       │   └── kubernetes-panel.js  # Built panel JS bundle (committed)
│       └── translations/
│           └── en.json              # Entity names, exceptions, config flow strings
├── frontend/                        # Panel source (Lit + TypeScript + Vite)
│   ├── package.json
│   ├── tsconfig.json
│   ├── vite.config.ts
│   ├── eslint.config.js
│   ├── .prettierrc
│   └── src/
│       ├── kubernetes-panel.ts      # Root panel element with tab navigation
│       ├── views/
│       │   ├── base-view.ts         # K8sDataView: shared load/poll/subscribe lifecycle
│       │   ├── k8s-overview.ts      # Overview tab
│       │   ├── k8s-nodes-table.ts   # Nodes tab
│       │   ├── k8s-workloads.ts     # Workloads tab
│       │   ├── k8s-pods-table.ts    # Pods tab
│       │   ├── k8s-network.ts       # Network tab
│       │   └── k8s-settings.ts      # Settings tab
│       ├── styles/
│       │   ├── shared.ts            # Loading/error/empty state + filter styles
│       │   └── actions.ts           # Round action-button + action-error banner styles
│       └── utils/
│           ├── load-ha-elements.ts  # HA element lazy loader
│           └── format.ts            # Pure formatting helpers (age, relative time, errors)
├── chart/                            # Helm chart for the ServiceAccount + RBAC
│   ├── Chart.yaml
│   ├── values.yaml
│   └── templates/
├── manifests/                        # Generated from chart/ — do not edit by hand
│   ├── full/
│   └── minimal/
├── scripts/
│   └── render-manifests.sh           # chart/ → manifests/
├── tests/
│   ├── conftest.py
│   ├── test_init.py
│   ├── test_websocket_api.py
│   └── ...
├── docs/
├── pyproject.toml
└── README.md

RBAC and the Helm Chart

chart/ is the single source of truth for the integration's RBAC. The plain manifests in manifests/{full,minimal}/ are rendered from it and committed so the kubectl apply -f <raw URL> install path keeps working without Helm.

When a new feature needs a new verb or resource:

  1. Add the rule to chart/templates/clusterrole.yaml — inside the mode: full branch, the minimal branch, or both.
  2. Re-render the plain manifests:
scripts/render-manifests.sh
  1. Commit both chart/ and the regenerated manifests/.
  2. Update the permission matrix in docs/RBAC.md.

Adding a new value? Add it to chart/values.schema.json too — Helm validates values against that schema on every install/upgrade/lint/template, which is why mode is an enum there rather than a template-level fail (a fail inside if rbac.create would be skipped when rbac.create=false).

.github/workflows/helm.yaml lints both modes and fails if manifests/ does not match a fresh render — the same drift guard used for the committed frontend bundle. It compares with git status --porcelain rather than git diff, so a new template rendering a new (untracked) manifest is caught too. Never edit files under manifests/ directly; the next render will overwrite them.

The workflow pins the Helm version (azure/setup-helm) so the rendered output is byte-stable; use the same version locally if the drift check disagrees with you.

The chart version is bumped by release-please alongside the integration version, and the release workflow pushes it to oci://ghcr.io/tibuntu/charts on every release.

Releases

Releases are cut by release-please from conventional-commit subjects on main: fix: bumps the patch version, feat: the minor version; refactor:, test:, build:, docs: and chore: do not trigger a release or appear in the changelog. When a release contains more than its fix: commits express — a large refactor, a behaviour change shipped under fix: — force the version with a Release-As footer:

git commit -m "chore: release 1.12.0" -m "Release-As: 1.12.0"

The commit must not be empty: pull requests are rebase-merged, and a rebase silently drops empty commits, so the footer never reaches main (this happened with #404). Attach the footer to a small real change instead — a documentation note, for example.

Every release carries a kubernetes.zip asset, built from custom_components/kubernetes/ by the release-asset job in .github/workflows/release.yaml. hacs.json sets zip_release, so HACS installs from that asset and shows its download count. If the job fails, attach it by hand:

git archive --format=zip -o kubernetes.zip vX.Y.Z:custom_components/kubernetes ':!kubernetes'
gh release upload vX.Y.Z kubernetes.zip --clobber

For minor releases the generated changelog section is rewritten as end-user prose on the release-please--branches--main branch before the release PR is merged (intro paragraph, ### New features / ### Fixes & improvements, an > **Upgrading** note for behaviour changes), and the release PR body is replaced with the same text.

Frontend Development

The sidebar panel is built with Lit 3 (TypeScript) and bundled with Vite (rolldown) into a single ES module. The bundle is minified via build.rolldownOptions.output.minify (compress + mangle + codegen.removeWhitespace) — property/class names used by Lit's tagged template literals and the custom-element contract are not mangled, so this is safe. The committed custom_components/kubernetes/frontend/kubernetes-panel.js (~116 KB) is diffed byte-for-byte against a fresh build in CI (see below), so always rebuild after editing .ts source.

Setup

cd frontend
npm ci

Build

npm run build    # One-time build → custom_components/kubernetes/frontend/kubernetes-panel.js
npm run dev      # Watch mode for development

The built kubernetes-panel.js is committed to the repository so HACS users get a working panel without needing Node.js.

Lint & Format

npm run lint          # ESLint check
npm run lint:fix      # ESLint auto-fix
npm run format:check  # Prettier check
npm run format        # Prettier auto-fix
npm run typecheck     # tsc --noEmit

npm run typecheck is enforced by CI (.github/workflows/frontend.yaml) and by the frontend-typecheck pre-commit hook. ESLint, Prettier and tsc cover frontend/e2e/ as well as frontend/src/.

Panel Tests (Playwright)

frontend/e2e/ holds browser tests for the sidebar panel. They need neither Home Assistant nor a cluster: e2e/harness.html mounts the real <kubernetes-panel> against a fake hass object (e2e/harness.ts) whose callWS answers from the canned responses in e2e/fixtures.ts, and whose callService only records the call. Every WebSocket message and service call is kept on window.__k8s so a spec can assert the exact payload a view sent. ?fail=<ws type> in the harness URL makes that call reject until the spec clears window.__k8s.fail, and window.__k8s.push() fires a kubernetes/subscribe_updates push. The harness has no Home Assistant router: it derives the panel's route from the page path and follows location-changed/popstate, so deep links like /e2e/harness.html/pods?phase=problems work in specs.

npx playwright install --with-deps chromium   # once; downloads the browser
npm run test:e2e                              # starts Vite's dev server itself
npx playwright test --ui                      # interactive runner

playwright.config.ts runs Chromium only and keeps a trace for failed tests under frontend/test-results/; CI uploads that directory as the playwright-traces artifact when the job fails. Fixture shapes mirror what websocket_api.py sends — update fixtures.ts when a command's payload changes. When you change how a view is operated (a dialog, a filter, a navigation), add or adjust a flow in e2e/panel.spec.ts; keep the specs to user-visible behaviour rather than per-component unit tests.

Testing

Running Tests

# Run all tests
pytest

# Run tests with verbose output
pytest -v

# Run specific test file
pytest tests/test_switch.py

# Run tests with coverage
pytest --cov=custom_components/kubernetes

Kubernetes API Compatibility Tests

CI runs the tests/k8s_compat/ suite against real kind clusters (Kubernetes N, N-1, N-2 — see .github/workflows/k8s-compat.yaml). These tests exercise every KubernetesClient method against a live API server with the chart's actual RBAC deployed. They are marked k8s_compat and auto-skip locally when K8S_SERVER/K8S_TOKEN are not set.

The latest supported Kubernetes version is pinned as K8S_LATEST in the workflow and tracked by Renovate (kubernetes/kubernetes github-releases). When a new release is tagged, Renovate opens a PR that bumps the pin and auto-updates the supported-version range in README.md and docs/SETUP.md via scripts/update-k8s-support-range.sh.

Python Requirements

manifest.json lists no requirements: the client talks to the API server with aiohttp, which Home Assistant ships. Keep it that way — Home Assistant installs manifest requirements under its own package_constraints.txt, and a pinned package that conflicts with those pins makes the integration uninstallable (v1.13.1 shipped kubernetes==37.0.0, which needed a newer pydantic than Home Assistant allowed).

Setting Up a Test Kubernetes Cluster

Using minikube

# Install minikube
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube

# Start minikube
minikube start

# Create test resources
kubectl create namespace test-namespace
kubectl run nginx --image=nginx -n test-namespace
kubectl expose pod nginx --port=80 -n test-namespace

Using kind

# Install kind: https://kind.sigs.k8s.io/docs/user/quick-start/#installation

# Create cluster
kind create cluster

# Create test resources
kubectl create namespace test-namespace
kubectl run nginx --image=nginx -n test-namespace

Creating Test ServiceAccount

# serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: homeassistant-test
  namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: homeassistant-test
subjects:
- kind: ServiceAccount
  name: homeassistant-test
  namespace: default
roleRef:
  kind: ClusterRole
  name: view
  apiGroup: rbac.authorization.k8s.io

Apply the configuration:

kubectl apply -f serviceaccount.yaml

Get the token:

kubectl get secret $(kubectl get serviceaccount homeassistant-test -o jsonpath='{.secrets[0].name}') -o jsonpath='{.data.token}' | base64 --decode

Code Quality

Code Formatting

# Lint and auto-fix
ruff check --fix .

# Format code
ruff format .

Type Checking

# Run mypy type checking
mypy custom_components/kubernetes/

Pre-commit Hooks

Install pre-commit hooks (the Python hooks run on python3.15, set by default_language_version in .pre-commit-config.yaml). The YAML and frontend hooks call the tools in frontend/node_modules, so install those first:

pip install pre-commit
(cd frontend && npm ci)
pre-commit install

Integration Testing

Manual Testing

  1. Start Home Assistant with your development configuration:
hass --config config
  1. Open Home Assistant in your browser (usually http://localhost:8123)

  2. Go to Settings → Devices & Services → Add Integration

  3. Search for "Kubernetes" and add it

  4. Configure the integration with your test cluster details

  5. Verify that sensors are created and updating

Automated Testing

Create integration tests in tests/ directory:

import pytest
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component

from custom_components.kubernetes.const import DOMAIN


async def test_load_unload_config_entry(hass: HomeAssistant) -> None:
    """Test loading and unloading the config entry."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONF_CLUSTER_NAME: "test-cluster",
            CONF_HOST: "test-cluster.example.com",
            # ... other config
        },
    )
    config_entry.add_to_hass(hass)

    assert await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()

    assert await hass.config_entries.async_unload(config_entry.entry_id)
    await hass.async_block_till_done()

Debugging

Enable Debug Logging

Add to your configuration.yaml:

logger:
  default: info
  logs:
    custom_components.kubernetes: debug

Common Issues

  1. Connection refused: Check if the Kubernetes API server is accessible
  2. Authentication failed: Verify the API token is correct
  3. SSL certificate errors: Check CA certificate configuration
  4. Permission denied: Ensure the ServiceAccount has proper RBAC permissions

Contributing

Pull Request Process

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass: pytest
  6. Format your code: ruff check --fix . && ruff format .
  7. Commit your changes: git commit -m 'Add amazing feature'
  8. Push to the branch: git push origin feature/amazing-feature
  9. Open a Pull Request

Code Review Checklist

  • Code follows Home Assistant integration patterns
  • All tests pass
  • Code is properly formatted
  • Type hints are included
  • Documentation is updated
  • No sensitive information is exposed

Resources