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 2025.7 or higher
  • A Kubernetes cluster for testing (minikube, kind, or cloud-based)
  • Git

Development Environment Setup

1. Clone the Repository

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

The easiest way to get started is using the provided devcontainer which provides a complete Home Assistant development environment.

Prerequisites

Quick Start

  1. Open the project in VS Code:
code .
  1. Start the devcontainer:
  2. Press F1 and select "Dev Containers: Reopen in Container"
  3. Or click the green "Reopen in Container" button when prompted

  4. Wait for setup to complete (first run takes a few minutes)

  5. Home Assistant will start automatically after setup

  6. Access Home Assistant at http://localhost:8123

  7. Wait about a minute for Home Assistant to fully start up

What's Included

The devcontainer automatically provides:

  • ✅ Complete Home Assistant installation
  • ✅ Your integration automatically mounted and available
  • ✅ All development dependencies (ruff, pytest, mypy)
  • ✅ Debug logging pre-configured
  • ✅ VS Code extensions for Python development
  • ✅ Quick test scripts and development helpers

Development Workflow

  1. Edit your integration code directly in VS Code
  2. Restart Home Assistant to apply changes:
  3. Use the restart script: /config/restart_ha.sh
  4. Or in HA: Settings → System → Restart
  5. Check logs:
  6. Settings → System → Logs in HA UI
  7. Or view log file: tail -f /config/logs/home-assistant.log

Testing Your Integration

Configure the integration by editing .devcontainer/configuration.yaml:

kubernetes:
  host: "https://your-cluster-endpoint"
  token: "your-service-account-token"
  verify_ssl: false  # for development clusters

Or use the Home Assistant UI: Settings → Integrations → Add Integration

Debugging

Enable Python debugging:

  1. Uncomment in .devcontainer/configuration.yaml:
debugpy:
  start: true
  wait: false
  port: 5678
  1. Restart Home Assistant
  2. In VS Code: Run and Debug → "Python: Remote Attach" → localhost:5678

Code quality tools (run automatically on save):

  • ruff check custom_components/ - linting
  • ruff format custom_components/ - formatting
  • pytest tests/ - run tests

3. Manual Setup (Alternative)

If you prefer to set up manually:

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -e ".[dev]"

# 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 (polling + Watch API)
│       ├── sensor.py                # Sensor platform
│       ├── binary_sensor.py         # Binary sensor platform
│       ├── switch.py                # Switch platform (workload control)
│       ├── 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
│       ├── frontend/
│       │   └── kubernetes-panel.js  # Built panel JS bundle (committed)
│       └── translations/
│           └── en.json              # English translations
├── 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/
│       │   ├── k8s-overview.ts      # Overview tab
│       │   ├── k8s-nodes-table.ts   # Nodes tab
│       │   ├── k8s-pods-table.ts    # Pods tab
│       │   ├── k8s-workloads.ts     # Workloads tab
│       │   └── k8s-settings.ts      # Settings tab
│       └── utils/
│           └── load-ha-elements.ts  # HA element lazy loader
├── tests/
│   ├── conftest.py
│   ├── test_init.py
│   ├── test_websocket_api.py
│   └── ...
├── docs/
├── pyproject.toml
└── README.md

Frontend Development

The sidebar panel is built with Lit 3 (TypeScript) and bundled with Vite into a single ES module. Minification is disabled because esbuild's variable mangling breaks Lit's tagged template literals.

Setup

cd frontend
npm install

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

Testing

Running Tests

# Run all tests
pytest

# Run tests with verbose output
pytest -v

# Run specific test file
pytest tests/test_kubernetes_integration.py

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

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
curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.20.0/kind-linux-amd64
chmod +x ./kind
sudo mv ./kind /usr/local/bin/kind

# 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:

pip install pre-commit
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 SettingsDevices & ServicesAdd 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

General 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

Devcontainer Issues

  1. Integration not loading:
  2. Check /config/custom_components/kubernetes/ exists in the container
  3. Verify manifest.json is valid
  4. Check Home Assistant logs: ha logs --filter kubernetes

  5. Permission issues:

  6. Ensure Docker has permission to mount volumes
  7. On Linux, you may need to adjust file ownership

  8. Port conflicts:

  9. If port 8123 is in use, update forwardPorts in .devcontainer/devcontainer.json

  10. Container won't start:

  11. Try rebuilding: F1 → "Dev Containers: Rebuild Container"
  12. Check Docker is running and has sufficient resources

Useful devcontainer commands:

# Start Home Assistant
/config/start_ha.sh &

# Restart Home Assistant
/config/restart_ha.sh

# Check setup
/config/check_setup.sh

# Test integration
python /config/test_integration.py

# View logs
tail -f /config/logs/home-assistant.log

# Check running processes
ps aux | grep hass

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