Guide
Dynamic manifests
Files as content, generated content with Twig, resources that exist under conditions, and manifests a rule spawns for every resource that matches.
One class, one resource, one static short name covers almost everything. This page is about what bends that model: file-shaped content, generated content, resources that exist only under conditions, and resources spawned by a rule.
Files as content
A ConfigMap or Secret that carries a file (an nginx.conf, a Fluent Bit pipeline, a development certificate) keeps it as a file, in the Resources/ directory beside the App class, read with $this->app->readFile() once the app is narrowed to ReadsResourceFiles (Apps says why). The file stays reviewable, and the class only wires it in.
Generated content: Twig
When the file needs values (a port from a manifest's constant, a hostname from a binding), use a template engine. Klass8s ships none: manifests are services, so Symfony's arrives through the constructor like any other dependency.
composer require symfony/twig-bundlenamespace App\K8S\Shop\Manifest;
use K8Schema\Collection\StringMap;
use Klass8s\App\ReadsResourceFiles;
use Klass8s\Core\ConfigMap\AbstractConfigMap;
use Twig\Environment;
class NginxConfigMap extends AbstractConfigMap
{
// Twig, from TwigBundle, like any other service
__construct(private Environment $twig, private string $publicHostname) {}
static shortName(): string => 'nginx';
data(StringMap $data): void {
assert($this->app instanceof ReadsResourceFiles);
// the template stays a file beside the App: Resources/configs/nginx.conf.twig
$template = $this->twig->createTemplate($this->app->readFile('configs/nginx.conf.twig'));
$data->add('nginx.conf', $template->render([
'server_name' => $this->publicHostname,
'upstream_port' => ApiDeployment::PORT,
]));
}
}<?php
declare(strict_types=1);
namespace App\K8S\Shop\Manifest;
use K8Schema\Collection\StringMap;
use Klass8s\App\ReadsResourceFiles;
use Klass8s\Core\ConfigMap\AbstractConfigMap;
use Twig\Environment;
class NginxConfigMap extends AbstractConfigMap
{
// Twig, from TwigBundle, like any other service
public function __construct(private Environment $twig, private string $publicHostname) {}
public static function shortName(): string
{
return 'nginx';
}
public function data(StringMap $data): void
{
assert($this->app instanceof ReadsResourceFiles);
// the template stays a file beside the App: Resources/configs/nginx.conf.twig
$template = $this->twig->createTemplate($this->app->readFile('configs/nginx.conf.twig'));
$data->add('nginx.conf', $template->render([
'server_name' => $this->publicHostname,
'upstream_port' => ApiDeployment::PORT,
]));
}
}# File: /shop/nginx.config-map.yaml
apiVersion: v1
kind: ConfigMap
data:
nginx.conf: |
server {
listen 8080;
server_name shop.example.com;
location / {
proxy_pass http://127.0.0.1:9000;
}
}
metadata:
annotations:
klass8s.dev/app: shop
klass8s.dev/deploy-priority: '0'
labels:
app.kubernetes.io/name: shop
app.kubernetes.io/component: nginx
name: shop-nginxcreateTemplate() keeps the template beside the App; with TwigBundle's usual templates/ directory, $this->twig->render('nginx.conf.twig', […]) works as well. None of this is a framework feature, which is the point: a constructor is enough.
Resources that exist under conditions
Covered elsewhere, collected here:
#[EnabledForEnvs('dev', 'test')]: per environment (Environments).#[EnabledForApps('shop', 'billing')]: a class shared by several Apps renders for those named.#[EnabledForConfigurationParameter('…')]: a container parameter decides, the closest thing to a feature switch.- A subscriber to
ManifestGeneratedEventsetspreventProcessing, when the decision needs the generated resource ("leave out workloads whose final replica count is zero").
Manifests spawned by a rule
Some resources are not written but derived: every Deployment that serves metrics gets a ServiceMonitor; every Deployment marked #[Autoscale] gets a KEDA ScaledObject (Klass8s's own use of this pattern). One class describes the companion resource; a subscriber creates an instance per parent.
The class is a template manifest: ManifestTemplateInterface and ManifestTemplateTrait make its short name a property of the instance rather than a static fact.
namespace App\K8S\Shop\Template;
use App\Attribute\ExposesMetrics;
use Klass8s\Core\Deployment\DeploymentInterface;
use Klass8s\Core\LabelSelector\SelectorConfigurator;
use Klass8s\Manifest\ManifestTemplateInterface;
use Klass8s\Manifest\ManifestTemplateTrait;
use Klass8s\Monitoring\Prometheus\Configurator\EndpointsConfigurator;
use Klass8s\Monitoring\Prometheus\ServiceMonitor\AbstractServiceMonitor;
/** A ServiceMonitor for one workload: one instance per workload that exposes metrics. */
class WorkloadServiceMonitor extends AbstractServiceMonitor implements ManifestTemplateInterface
{
use ManifestTemplateTrait;
__construct(private DeploymentInterface $workload, private ExposesMetrics $metrics) {
$this->dynamicShortName = $workload->computedShortName;
}
selector(SelectorConfigurator $selector): void
=> $selector->addLabel('app.kubernetes.io/component', $this->workload->computedShortName);
endpoints(EndpointsConfigurator $endpoints): void
=> $endpoints->add()->port($this->metrics->port)->path($this->metrics->path)->interval('30s');
}<?php
declare(strict_types=1);
namespace App\K8S\Shop\Template;
use App\Attribute\ExposesMetrics;
use Klass8s\Core\Deployment\DeploymentInterface;
use Klass8s\Core\LabelSelector\SelectorConfigurator;
use Klass8s\Manifest\ManifestTemplateInterface;
use Klass8s\Manifest\ManifestTemplateTrait;
use Klass8s\Monitoring\Prometheus\Configurator\EndpointsConfigurator;
use Klass8s\Monitoring\Prometheus\ServiceMonitor\AbstractServiceMonitor;
/** A ServiceMonitor for one workload: one instance per workload that exposes metrics. */
class WorkloadServiceMonitor extends AbstractServiceMonitor implements ManifestTemplateInterface
{
use ManifestTemplateTrait;
public function __construct(private DeploymentInterface $workload, private ExposesMetrics $metrics)
{
$this->dynamicShortName = $workload->computedShortName;
}
public function selector(SelectorConfigurator $selector): void
{
$selector->addLabel('app.kubernetes.io/component', $this->workload->computedShortName);
}
public function endpoints(EndpointsConfigurator $endpoints): void
{
$endpoints->add()->port($this->metrics->port)->path($this->metrics->path)->interval('30s');
}
}$dynamicShortName can be set once (a second assignment throws), and the static shortName() throws: the class alone no longer identifies a resource. Templates are not services: keep them out of service discovery (here, the App's Template/ directory is excluded in config/services.yaml) and construct them in a subscriber.
The subscriber collects the parents while they are generated and spawns the companions when the build is complete, through ManifestSpawner, the supported way to add an instance to the build:
namespace App\EventSubscriber;
use App\Attribute\ExposesMetrics;
use App\K8S\Shop\Template\WorkloadServiceMonitor;
use Klass8s\App\AppInterface;
use Klass8s\Core\Deployment\DeploymentInterface;
use Klass8s\Event\DeploymentGeneratedEvent;
use Klass8s\Event\ManifestsProcessedEvent;
use Klass8s\Manifest\ManifestSpawner;
use LogicException;
use ReflectionClass;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/** Every Deployment marked #[ExposesMetrics] gets a ServiceMonitor, spawned into its App's output. */
final class ServiceMonitorSubscriber implements EventSubscriberInterface
{
private list<(DeploymentInterface, AppInterface, ExposesMetrics)> $targets = [];
__construct(private ManifestSpawner $spawner) {}
static getSubscribedEvents(): map<string, string|(string, int)> => [
DeploymentGeneratedEvent::NAME => 'collect',
// above -1024, so that the late subscribers see the spawned resources
ManifestsProcessedEvent::NAME => ['spawn', 512],
];
collect(DeploymentGeneratedEvent $event): void {
$manifest = $event->manifest();
// the attribute is on the class you wrote, which className() names, not on its proxy
$class = $manifest::className();
if (!class_exists($class)) {
return;
}
$attributes = new ReflectionClass($class)->getAttributes(ExposesMetrics::class);
if ([] !== $attributes) {
$this->targets[] = [$manifest, $event->app(), $attributes[0]->newInstance()];
}
}
spawn(ManifestsProcessedEvent $event): void throws LogicException {
foreach ($this->targets as [$workload, $app, $metrics]) {
$monitor = new WorkloadServiceMonitor($workload, $metrics);
$monitor->setApp($app);
$output = $event->outputDir->directory($app->alias()) ?? throw new LogicException("No output for {$app->alias()}");
$this->spawner->spawn($monitor, $output);
}
}
}<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Attribute\ExposesMetrics;
use App\K8S\Shop\Template\WorkloadServiceMonitor;
use Klass8s\App\AppInterface;
use Klass8s\Core\Deployment\DeploymentInterface;
use Klass8s\Event\DeploymentGeneratedEvent;
use Klass8s\Event\ManifestsProcessedEvent;
use Klass8s\Manifest\ManifestSpawner;
use LogicException;
use ReflectionClass;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/** Every Deployment marked #[ExposesMetrics] gets a ServiceMonitor, spawned into its App's output. */
final class ServiceMonitorSubscriber implements EventSubscriberInterface
{
/**
* @var list<array{DeploymentInterface, AppInterface, ExposesMetrics}>
*/
private array $targets = [];
public function __construct(private ManifestSpawner $spawner) {}
/**
* @return array<string, string|array{string, int}>
*/
public static function getSubscribedEvents(): array
{
return [
DeploymentGeneratedEvent::NAME => 'collect',
// above -1024, so that the late subscribers see the spawned resources
ManifestsProcessedEvent::NAME => ['spawn', 512],
];
}
public function collect(DeploymentGeneratedEvent $event): void
{
$manifest = $event->manifest();
// the attribute is on the class you wrote, which className() names, not on its proxy
$class = $manifest::className();
if (!class_exists($class)) {
return;
}
$attributes = new ReflectionClass($class)->getAttributes(ExposesMetrics::class);
if ([] !== $attributes) {
$this->targets[] = [$manifest, $event->app(), $attributes[0]->newInstance()];
}
}
/**
* @throws LogicException
*/
public function spawn(ManifestsProcessedEvent $event): void
{
foreach ($this->targets as [$workload, $app, $metrics]) {
$monitor = new WorkloadServiceMonitor($workload, $metrics);
$monitor->setApp($app);
$output = $event->outputDir->directory($app->alias()) ?? throw new LogicException("No output for {$app->alias()}");
$this->spawner->spawn($monitor, $output);
}
}
}namespace App\K8S\Shop\Manifest;
use App\Attribute\ExposesMetrics;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Container\Ports\PortsConfigurator;
use Klass8s\Core\Deployment\AbstractContainerDeployment;
#[ExposesMetrics(port: 'metrics')]
class ApiDeployment extends AbstractContainerDeployment
{
const int PORT = 9000;
static shortName(): string => 'api';
image(): Image => Image::fromName('acme/shop-api')->setTag('1.4.0');
ports(PortsConfigurator $ports): void {
$ports->add(self::PORT)->setName('http');
$ports->add(9090)->setName('metrics');
}
}<?php
declare(strict_types=1);
namespace App\K8S\Shop\Manifest;
use App\Attribute\ExposesMetrics;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Container\Ports\PortsConfigurator;
use Klass8s\Core\Deployment\AbstractContainerDeployment;
#[ExposesMetrics(port: 'metrics')]
class ApiDeployment extends AbstractContainerDeployment
{
public const int PORT = 9000;
public static function shortName(): string
{
return 'api';
}
public function image(): Image
{
return Image::fromName('acme/shop-api')->setTag('1.4.0');
}
public function ports(PortsConfigurator $ports): void
{
$ports->add(self::PORT)->setName('http');
$ports->add(9090)->setName('metrics');
}
}# File: /shop/api.service-monitor.yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
annotations:
klass8s.dev/app: shop
klass8s.dev/deploy-priority: '0'
labels:
app.kubernetes.io/name: shop
app.kubernetes.io/component: api
name: shop-api
spec:
selector:
matchLabels:
app.kubernetes.io/component: api
namespaceSelector: {}
endpoints:
-
port: metrics
path: /metrics
interval: 30sspawn() puts the instance through what a discovered manifest goes through: it is proxied (default labels, environment methods, method events), configured from its App's configuration, made by its kind's maker (which dispatches the kind's event), passed through ManifestGeneratedEvent (annotations, namespace removal, the veto) and added to the given output directory. Calling a maker yourself would skip everything after the kind's event.
Why it fits:
ManifestsProcessedEventis the right moment. Every parent exists and nothing is written yet; the output holds objects until it renders, so late additions and late changes both reach the YAML. Spawn above -1024 so that the late subscribers (checksums, resource tracking) see what you add.- Names derive from the parent, so companions follow the
<app>-<name>convention. - Output lands per App:
$event->outputDir->directory($app->alias())is the App's own part of the output.
A template may also implement FullNameAwareInterface when its instances need names of their own. A template cannot be the target of a class reference (resourceNameFromManifestClass(WorkloadServiceMonitor::class) would be ambiguous); whatever needs an instance's name takes it from the instance.
Check the alternatives first: three fixed queues are better served by three small subclasses of one abstract worker, with static names and class references. Spawned templates earn their place when the set is derived: one companion per matching parent, however many there are.
Choosing
| What varies | Use |
|---|---|
| a file's content | $this->app->readFile(), the app narrowed to ReadsResourceFiles |
| a file's content, with values | a Twig template |
| whether the resource exists | the #[EnabledFor…] attributes, or preventProcessing |
| a value inside the resource | configuration, environment methods |
| how many resources there are | subclasses for a small fixed set; spawned templates for a derived one |