Kubernetes manifests, written as classes
Klass8s is a library and Symfony bundle that renders typed classes into plain Kubernetes YAML. You state each fact once; names, labels, selectors, references and config checksums are derived. Write the classes in Phaenon or in PHP.
namespace App\K8S\Checkout\Manifest;
use Klass8s\Core\Container\Env\EnvConfigurator;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Container\Ports\PortsConfigurator;
use Klass8s\Core\Container\Resources\ContainerResourcesInterface;
use Klass8s\Core\Container\Resources\CPU;
use Klass8s\Core\Container\Resources\Memory;
use Klass8s\Core\Deployment\AbstractContainerDeployment;
class ApiDeployment extends AbstractContainerDeployment
{
const int PORT = 8080;
static shortName(): string => 'api';
image(): Image => Image::fromName('acme/checkout-api')->setTag('1.42.0');
replicas(): int => 2;
replicasProd(): int => 6;
ports(PortsConfigurator $ports): void => $ports->add(self::PORT)->setName('http');
env(EnvConfigurator $env): void {
$env->addConfigMapClass(ApiConfigMap::class)
->varFromSecretClass('PAYMENTS_TOKEN', PaymentsSecret::class, PaymentsSecret::KEY_TOKEN);
}
resources(ContainerResourcesInterface $resources): void {
$resources->requestCPU(CPU::millicores(250))->requestMemory(Memory::mebibytes(256));
}
}<?php
declare(strict_types=1);
namespace App\K8S\Checkout\Manifest;
use Klass8s\Core\Container\Env\EnvConfigurator;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Container\Ports\PortsConfigurator;
use Klass8s\Core\Container\Resources\ContainerResourcesInterface;
use Klass8s\Core\Container\Resources\CPU;
use Klass8s\Core\Container\Resources\Memory;
use Klass8s\Core\Deployment\AbstractContainerDeployment;
class ApiDeployment extends AbstractContainerDeployment
{
public const int PORT = 8080;
public static function shortName(): string
{
return 'api';
}
public function image(): Image
{
return Image::fromName('acme/checkout-api')->setTag('1.42.0');
}
public function replicas(): int
{
return 2;
}
public function replicasProd(): int
{
return 6;
}
public function ports(PortsConfigurator $ports): void
{
$ports->add(self::PORT)->setName('http');
}
public function env(EnvConfigurator $env): void
{
$env->addConfigMapClass(ApiConfigMap::class)
->varFromSecretClass('PAYMENTS_TOKEN', PaymentsSecret::class, PaymentsSecret::KEY_TOKEN);
}
public function resources(ContainerResourcesInterface $resources): void
{
$resources->requestCPU(CPU::millicores(250))->requestMemory(Memory::mebibytes(256));
}
}# File: /checkout/api.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
klass8s.dev/app: checkout
klass8s.dev/deploy-priority: '0'
labels:
app.kubernetes.io/name: checkout
app.kubernetes.io/component: api
name: checkout-api
spec:
replicas: 2
revisionHistoryLimit: 1
selector:
matchLabels:
app.kubernetes.io/name: checkout
app.kubernetes.io/component: api
template:
metadata:
annotations:
klass8s.dev/env-sources-checksum: f06e7058bfb51fd08dda20d7e1cd3254
klass8s.dev/volume-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
labels:
app.kubernetes.io/name: checkout
app.kubernetes.io/component: api
spec:
containers:
-
env:
- { name: PAYMENTS_TOKEN, valueFrom: { secretKeyRef: { key: token, name: checkout-payments, optional: false } } }
envFrom:
- { configMapRef: { name: checkout-api, optional: false } }
image: 'acme/checkout-api:1.42.0'
imagePullPolicy: IfNotPresent
name: app
ports:
- { containerPort: 8080, name: http }
resources:
requests: { cpu: 250m, memory: 256Mi }Marked lines are derived by Klass8s. The class states none of them.
References are classes, not strings
A Service names the Deployment it fronts, an env block names its ConfigMap, a binding names its Role: each by class. Klass8s resolves the resource names when it renders and fails the render when a reference points at nothing.
How manifests reference each othernamespace App\K8S\Checkout\Manifest;
use Klass8s\Core\Service\AbstractService;
use Klass8s\Core\Service\Configurator\ServicePortsConfigurator;
class ApiService extends AbstractService
{
static shortName(): string => ApiDeployment::shortName();
ports(ServicePortsConfigurator $ports): void => $ports->add(80, ApiDeployment::PORT)->setName('http');
}<?php
declare(strict_types=1);
namespace App\K8S\Checkout\Manifest;
use Klass8s\Core\Service\AbstractService;
use Klass8s\Core\Service\Configurator\ServicePortsConfigurator;
class ApiService extends AbstractService
{
public static function shortName(): string
{
return ApiDeployment::shortName();
}
public function ports(ServicePortsConfigurator $ports): void
{
$ports->add(80, ApiDeployment::PORT)->setName('http');
}
}# File: /checkout/api.service.yaml
apiVersion: v1
kind: Service
metadata:
annotations:
klass8s.dev/app: checkout
klass8s.dev/deploy-priority: '0'
labels:
app.kubernetes.io/name: checkout
app.kubernetes.io/component: api
name: checkout-api
spec:
ports:
-
name: http
port: 80
targetPort: 8080
selector:
app.kubernetes.io/name: checkout
app.kubernetes.io/component: api
trafficDistribution: PreferCloseEnvironments are methods
replicasProd() next to replicas(): what production changes stands in the class it changes, not in an overlay directory or a values file per environment.
replicas(): int => 2;
replicasProd(): int => 6;public function replicas(): int
{
return 2;
}
public function replicasProd(): int
{
return 6;
}A rule for every pod, written once
Every manifest method call and every generated resource dispatches an event. One subscriber can require memory limits in production, attach a sidecar, or answer for every workload that left a field empty.
The event systemnamespace App\EventSubscriber;
use Klass8s\Bundle\EnvManagement\Env;
use Klass8s\Event\ContainerGeneratedEvent;
use LogicException;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/** A production container without a memory limit fails the render. */
final class RequireMemoryLimitsInProd implements EventSubscriberInterface
{
__construct(#[Autowire('%kernel.environment%')] private string $environment) {}
static getSubscribedEvents(): map<string, string> => [ContainerGeneratedEvent::NAME => 'onContainer'];
onContainer(ContainerGeneratedEvent $event): void throws LogicException {
if (Env::PRODUCTION !== $this->environment) {
return;
}
$limits = $event->container->getResources()?->limits();
if (null === $limits || !$limits->has('memory')) {
throw new LogicException(sprintf('Container "%s" has no memory limit, which production requires.', $event->container->getName()));
}
}
}<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use Klass8s\Bundle\EnvManagement\Env;
use Klass8s\Event\ContainerGeneratedEvent;
use LogicException;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/** A production container without a memory limit fails the render. */
final class RequireMemoryLimitsInProd implements EventSubscriberInterface
{
public function __construct(#[Autowire('%kernel.environment%')] private string $environment) {}
/**
* @return array<string, string>
*/
public static function getSubscribedEvents(): array
{
return [ContainerGeneratedEvent::NAME => 'onContainer'];
}
/**
* @throws LogicException
*/
public function onContainer(ContainerGeneratedEvent $event): void
{
if (Env::PRODUCTION !== $this->environment) {
return;
}
$limits = $event->container->getResources()?->limits();
if (null === $limits || !$limits->has('memory')) {
throw new LogicException(sprintf('Container "%s" has no memory limit, which production requires.', $event->container->getName()));
}
}
}Plain YAML out
Rendering prints ordinary multi-document YAML. Nothing of Klass8s runs in the cluster, no custom resource is needed to apply it, and the same code, configuration and environment always give the same bytes, so a diff of the output is a review of the change.
Rendering and deploying# what would change
bin/console k8s:render:apps | kubectl diff -f -
# apply it
bin/console k8s:render:apps | kubectl apply -f -
# or write one file per resource, to commit for a GitOps controller
bin/console k8s:dump:appsPhaenon or PHP
Every example on this site is written twice. Phaenon is a typed dialect of PHP that compiles to the PHP you would write by hand; a Klass8s project can be written in either, or in both. The tabs on any example switch every example, and the choice is kept.
Phaenon and PHP- Runs where you render
- PHP 8.5 and Symfony 8 components at render time; nothing afterwards.
- Kubernetes' own schema
- Every built-in kind is a class generated from the Kubernetes OpenAPI specification, versioned with Kubernetes.
- Tested like code
- Render an app in PHPUnit and assert on the YAML, with every subscriber and environment rule applied.
- Installs with Composer
klass8s/klass8s, a bundle beside the rest of your Symfony configuration.