GuideManifests

Guide

Manifests

What every manifest class shares, whatever its kind - identity, the render lifecycle, metadata, configuration data, switching off and the way out to the raw object.

A manifest is one class that produces one Kubernetes resource. This page covers what all manifests share; the kinds are in Containers, Networking, Workloads and the manifest types reference.

A manifest class

You extend one of the base classes (AbstractContainerDeployment, AbstractService, AbstractConfigMap and the rest) and implement one method that every manifest needs, the static shortName(). Everything else overrides a default; a minimal Deployment is shortName() and image().

Each manifest has three derived names, read-only properties: computedShortName (the short name), computedFullName (the resource name, <app>-<short name>) and fileName (api.deployment, the name k8s:dump:* writes). The static apiVersion() and kind() come from the base class.

Manifest classes are not final

Every manifest is wrapped in a proxy when it enters the build, and the proxy is a generated subclass. That is what makes the event system possible, and why a final manifest fails the render with "Class … cannot be proxied because it is final". The same holds for sidecar and init container classes. Apps and event subscribers are not proxied and may be final.

Choosing a base class

You needExtend
A workload with one main containerAbstractContainerDeployment, AbstractContainerStatefulSet, AbstractContainerJob, AbstractContainerCronJob
A pod with several containers of equal weightAbstractDeployment and the other kinds without Container, with container classes
A Service, ConfigMap, Secret, Ingress, ServiceAccount, Role, HPA, PVC, PriorityClass, StorageClassthe Abstract<Kind> of that kind
Gateway API resourcesAbstractGateway, AbstractHTTPRoute, AbstractGRPCRoute, …
An instance of a custom resource (ExternalSecret, Certificate)AbstractSelfMakingManifest, see Custom resources
A CustomResourceDefinitionAbstractCustomResourceDefinition

Prefer the class of the kind whenever there is one: the configurators, the generated events and the built-in subscribers hang off it. AbstractSelfMakingManifest is for kinds Kubernetes does not know.

The render lifecycle

What happens when an App renders; it helps the first time you write a subscriber:

  1. Discovery. At container compile time, compiler passes collect the manifest services and attach each to its App.
  2. Registration and proxying. Each manifest enters the manifest registry wrapped in a proxy. From then on every public method call on it dispatches an event before and after.
  3. Making. A resource maker for the manifest's kind builds the Kubernetes object: it calls your configurator methods (ports(), env(), resources() …), then your configure<Kind>().
  4. Events. As the parts come together, events fire: container generated, pod spec generated, then the kind's own (klass8s.manifest_generated.deployment and its siblings), then the generic klass8s.manifest_generated. Built-in subscribers add labels, selectors and annotations here.
  5. Whole build. When every App is built, klass8s.manifests.processed fires once; the config checksums are written then.
  6. Output. The objects serialize to YAML, to standard output (k8s:render:*) or to one file per resource (k8s:dump:*).

The same code, configuration and APP_ENV always produce the same bytes.

Metadata

Labels and annotations of one manifest go in metadata():

src/K8S/Shop/Manifest/ApiDeployment.phnsrc/K8S/Shop/Manifest/ApiDeployment.php
metadata(MetadataConfigurator $meta): void {
    $meta->labels()->add('team', 'payments');
    $meta->annotations()->add('prometheus.io/scrape', 'true');
}
public function metadata(MetadataConfigurator $meta): void
{
    $meta->labels()->add('team', 'payments');
    $meta->annotations()->add('prometheus.io/scrape', 'true');
}

On a workload they are written on the resource and on its pod template. For metadata on every resource of every App, write a subscriber.

Configuration data: $this->config

Every manifest carries $this->config, the keys its App's entry in config/packages/klass8s.yaml gives it under manifests.<short name>:

config/packages/klass8s.yaml
klass8s:
    apps:
        shop:
            manifests:
                api:
                    rate_limit: 200        # read by ApiDeployment as $this->config
                legacy-worker:
                    virtual: true          # stays referenceable, is not rendered
                trust-bundle:
                    virtual: true          # written by another system; read by ApiDeployment
        reports:
            enabled: false                 # not registered, not rendered
src/K8S/Shop/Manifest/ApiDeployment.phnsrc/K8S/Shop/Manifest/ApiDeployment.php
env(EnvConfigurator $env): void {
    // apps[shop].manifests.api.rate_limit in config/packages/klass8s.yaml
    $limit = $this->config['rate_limit'] ?? 100;
    $env->var('RATE_LIMIT', is_int($limit) ? (string) $limit : '100');
}
public function env(EnvConfigurator $env): void
{
    // apps[shop].manifests.api.rate_limit in config/packages/klass8s.yaml
    $limit = $this->config['rate_limit'] ?? 100;
    $env->var('RATE_LIMIT', is_int($limit) ? (string) $limit : '100');
}

The array holds whatever the YAML holds, so code that wants an integer checks for one. Symfony merges configuration per environment, so config/packages/prod/klass8s.yaml can give production another value with no code involved:

config/packages/prod/klass8s.yaml
klass8s:
    apps:
        shop:
            manifests:
                api:
                    rate_limit: 1000       # prod only

That is the data side of environments; environment-specific methods are the logic side.

Turning manifests off

src/K8S/Shop/Manifest/MailSinkDeployment.phnsrc/K8S/Shop/Manifest/MailSinkDeployment.php
namespace App\K8S\Shop\Manifest;

use Klass8s\Bundle\EnvManagement\Attribute\EnabledForEnvs;
use Klass8s\Bundle\EnvManagement\Env;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Deployment\AbstractContainerDeployment;

// A development affordance: rendered in dev and test, absent from every other environment.
#[EnabledForEnvs(Env::DEV, Env::TEST)]
class MailSinkDeployment extends AbstractContainerDeployment
{
    static shortName(): string => 'mail-sink';

    image(): Image => Image::fromName('axllent/mailpit')->setTag('v1.21');
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use Klass8s\Bundle\EnvManagement\Attribute\EnabledForEnvs;
use Klass8s\Bundle\EnvManagement\Env;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Deployment\AbstractContainerDeployment;

// A development affordance: rendered in dev and test, absent from every other environment.
#[EnabledForEnvs(Env::DEV, Env::TEST)]
class MailSinkDeployment extends AbstractContainerDeployment
{
    public static function shortName(): string
    {
        return 'mail-sink';
    }

    public function image(): Image
    {
        return Image::fromName('axllent/mailpit')->setTag('v1.21');
    }
}
ScopeMechanism
A manifest exists in some environments only#[EnabledForEnvs(…)] on the class
A class shared by several Apps renders for some of them#[EnabledForApps('shop', 'billing')]
A manifest depends on a container parameter#[EnabledForConfigurationParameter('…')]: rendered when the parameter is true
A service exists in some environments onlySymfony's #[When(env: 'dev')], on an App or any other class
A whole App is offenabled: false on its entry in config/packages/klass8s.yaml
Something else creates the resource in this clustervirtual: true on the manifest's entry: it stays referenceable and is not rendered
The decision needs the generated objecta subscriber sets preventProcessing on klass8s.manifest_generated

The rendering of these manifests in production:

RenderedAPP_ENV=prod bin/console k8s:render:apps shop
# File: /shop/api.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    prometheus.io/scrape: 'true'
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: api
    team: payments
  name: shop-api
spec:
  minReadySeconds: 10
  replicas: 1
  revisionHistoryLimit: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: shop
      app.kubernetes.io/component: api
  template:
    metadata:
      annotations:
        prometheus.io/scrape: 'true'
        klass8s.dev/env-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
        klass8s.dev/volume-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
      labels:
        app.kubernetes.io/name: shop
        app.kubernetes.io/component: api
        team: payments
    spec:
      containers:
        -
          env:
            - { name: RATE_LIMIT, value: '1000' }
          image: 'acme/shop-api:1.0.0'
          imagePullPolicy: IfNotPresent
          name: app
          volumeMounts:
            - { mountPath: /etc/ssl/trust, name: trust, readOnly: true }
      enableServiceLinks: false
      volumes:
        -
          configMap:
            name: shop-trust-bundle
          name: trust
---
# File: /shop/api.service.yaml
apiVersion: v1
kind: Service
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:
  ports:
    -
      name: http
      port: 80
      targetPort: 8080
  selector:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: api
  trafficDistribution: PreferClose

MailSinkDeployment is in the dev output and absent here; LegacyWorkerDeployment, virtual in the configuration above, is absent from both. Use the environment gates sparingly: an environment that differs in what exists stops proving the others.

A virtual manifest is still a class the others can name. Here the cluster's certificate tooling writes a ConfigMap, and a class gives it a name:

src/K8S/Shop/Manifest/TrustBundleConfigMap.phnsrc/K8S/Shop/Manifest/TrustBundleConfigMap.php
namespace App\K8S\Shop\Manifest;

use Klass8s\Core\ConfigMap\AbstractConfigMap;

// virtual: true in config/packages/klass8s.yaml: the cluster's certificate tooling writes the
// ConfigMap shop-trust-bundle; this class gives it a name the other classes can refer to.
class TrustBundleConfigMap extends AbstractConfigMap
{
    const string KEY = 'ca.crt';

    static shortName(): string => 'trust-bundle';
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use Klass8s\Core\ConfigMap\AbstractConfigMap;

// virtual: true in config/packages/klass8s.yaml: the cluster's certificate tooling writes the
// ConfigMap shop-trust-bundle; this class gives it a name the other classes can refer to.
class TrustBundleConfigMap extends AbstractConfigMap
{
    public const string KEY = 'ca.crt';

    public static function shortName(): string
    {
        return 'trust-bundle';
    }
}
src/K8S/Shop/Manifest/ApiDeployment.phnsrc/K8S/Shop/Manifest/ApiDeployment.php
// A virtual ConfigMap, read by class: the name resolves, and the checksum leaves it out.
volumes(VolumesConfigurator $volumes): void => $volumes->fromConfigMapClass('trust', TrustBundleConfigMap::class);

volumeMounts(VolumeMountsConfigurator $mounts): void => $mounts->add('trust', '/etc/ssl/trust')->setReadOnly(true);
// A virtual ConfigMap, read by class: the name resolves, and the checksum leaves it out.
public function volumes(VolumesConfigurator $volumes): void
{
    $volumes->fromConfigMapClass('trust', TrustBundleConfigMap::class);
}

public function volumeMounts(VolumeMountsConfigurator $mounts): void
{
    $mounts->add('trust', '/etc/ssl/trust')->setReadOnly(true);
}
Renderedbin/console k8s:render:apps shop
# File: /shop/api.deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    prometheus.io/scrape: 'true'
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: api
    team: payments
  name: shop-api
spec:
  minReadySeconds: 10
  replicas: 1
  revisionHistoryLimit: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: shop
      app.kubernetes.io/component: api
  template:
    metadata:
      annotations:
        prometheus.io/scrape: 'true'
        klass8s.dev/env-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
        klass8s.dev/volume-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
      labels:
        app.kubernetes.io/name: shop
        app.kubernetes.io/component: api
        team: payments
    spec:
      containers:
        -
          env:
            - { name: RATE_LIMIT, value: '200' }
          image: 'acme/shop-api:1.0.0'
          imagePullPolicy: IfNotPresent
          name: app
          volumeMounts:
            - { mountPath: /etc/ssl/trust, name: trust, readOnly: true }
      enableServiceLinks: false
      volumes:
        -
          configMap:
            name: shop-trust-bundle
          name: trust

The volume names shop-trust-bundle, resolved from the class, and the render holds no ConfigMap of that name. The workload treats the source as external: Klass8s has none of its bytes, so the checksum leaves it out, here the checksum of nothing. A change to that ConfigMap restarts no pod; a workload that must follow it says so on its own.

The way out: configure<Kind>()

The configurators cover the common fields. For any other, every base class ends with a configure<Kind>() method that receives the generated object from klass8s/k8schema, the whole Kubernetes API, typed:

src/K8S/Shop/Manifest/ApiDeployment.phnsrc/K8S/Shop/Manifest/ApiDeployment.php
// Runs after every configurator: the generated object, typed, for any field they lack.
configureDeployment(Deployment $deployment): void {
    $deployment->spec()->setMinReadySeconds(10);
    $deployment->spec()->template()->spec()->setEnableServiceLinks(false);
}
// Runs after every configurator: the generated object, typed, for any field they lack.
public function configureDeployment(Deployment $deployment): void
{
    $deployment->spec()->setMinReadySeconds(10);
    $deployment->spec()->template()->spec()->setEnableServiceLinks(false);
}

It runs after the configurator methods, so it can change what they produced. When the same change appears in a third manifest, make it a subscriber.

Sharing a name on purpose

Resources of different kinds may share a short name. A Service with the short name of a Deployment gets the same resource name, and Klass8s sets its selector to that Deployment's pod labels:

src/K8S/Shop/Manifest/ApiService.phnsrc/K8S/Shop/Manifest/ApiService.php
namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Service\AbstractService;
use Klass8s\Core\Service\Configurator\ServicePortsConfigurator;

class ApiService extends AbstractService
{
    // the Deployment's short name: the same resource name, and a selector for its pods
    static shortName(): string => ApiDeployment::shortName();

    ports(ServicePortsConfigurator $ports): void => $ports->add(80, 8080)->setName('http');
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use Klass8s\Core\Service\AbstractService;
use Klass8s\Core\Service\Configurator\ServicePortsConfigurator;

class ApiService extends AbstractService
{
    // the Deployment's short name: the same resource name, and a selector for its pods
    public static function shortName(): string
    {
        return ApiDeployment::shortName();
    }

    public function ports(ServicePortsConfigurator $ports): void
    {
        $ports->add(80, 8080)->setName('http');
    }
}

Two manifests of the same kind with the same short name in one App fail the container's compilation.

Next

  • Containers: the workload side of manifests.
  • Events: what the proxies make possible.