GuideCustom resources

Guide

Custom resources

Instances of operators' kinds as classes with a spec(), and CustomResourceDefinitions with typed names and versions.

Clusters run on operators: External Secrets Operator writes Secrets, database operators run databases, cert-manager issues certificates. Each speaks in kinds Kubernetes does not know, so klass8s/k8schema has no classes for them. Klass8s covers them twice:

  • AbstractSelfMakingManifest declares an instance of any kind: an ExternalSecret, a database Cluster.
  • AbstractCustomResourceDefinition declares a CustomResourceDefinition itself, for a team that ships its own operator.

Instances of any kind

Four methods: the three static identity methods and spec(), which returns what you would write under spec::

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

use Klass8s\Manifest\AbstractSelfMakingManifest;

/** The Secret shop-infrastructure, written by External Secrets Operator from the platform's store. */
class InfrastructureExternalSecret extends AbstractSelfMakingManifest
{
    private const string STORE = 'platform';
    private const string REMOTE_KEY = 'shop/infrastructure';

    static apiVersion(): string => 'external-secrets.io/v1';

    static kind(): string => 'ExternalSecret';

    static shortName(): string => 'infrastructure';

    spec(): map<string, mixed> => [
        'refreshInterval' => '1h',
        'secretStoreRef' => ['name' => self::STORE, 'kind' => 'ClusterSecretStore'],
        // the Secret it writes takes this resource's own derived name
        'target' => ['name' => $this->computedFullName],
        'dataFrom' => [['extract' => ['key' => self::REMOTE_KEY]]],
    ];
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use Klass8s\Manifest\AbstractSelfMakingManifest;

/** The Secret shop-infrastructure, written by External Secrets Operator from the platform's store. */
class InfrastructureExternalSecret extends AbstractSelfMakingManifest
{
    private const string STORE = 'platform';
    private const string REMOTE_KEY = 'shop/infrastructure';

    public static function apiVersion(): string
    {
        return 'external-secrets.io/v1';
    }

    public static function kind(): string
    {
        return 'ExternalSecret';
    }

    public static function shortName(): string
    {
        return 'infrastructure';
    }

    /**
     * @return array<string, mixed>
     */
    public function spec(): array
    {
        return [
            'refreshInterval' => '1h',
            'secretStoreRef' => ['name' => self::STORE, 'kind' => 'ClusterSecretStore'],
            // the Secret it writes takes this resource's own derived name
            'target' => ['name' => $this->computedFullName],
            'dataFrom' => [['extract' => ['key' => self::REMOTE_KEY]]],
        ];
    }
}

A self-making manifest is a manifest like any other: a derived name and identity labels, metadata(), dependency injection, environment methods, its App. Above, $this->computedFullName gives the Secret it asks for the resource's own derived name. spec() may also return a JsonSerializable.

The specification is code

Because spec() is a method, everything else on these pages applies: a store whose provider depends on the environment (example), or a reference to a sibling manifest, by class, inside a plain array:

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

use Klass8s\Manifest\AbstractSelfMakingManifest;

// An operator's custom resource that names a sibling manifest, by class, inside a plain array.
class DatabaseCluster extends AbstractSelfMakingManifest
{
    static apiVersion(): string => 'postgresql.cnpg.io/v1';

    static kind(): string => 'Cluster';

    static shortName(): string => 'database';

    spec(): map<string, mixed> => [
        'instances' => 3,
        'storage' => ['size' => '20Gi'],
        'bootstrap' => ['initdb' => [
            'database' => 'shop',
            'secret' => ['name' => $this->app->resourceNameFromManifestClass(InfrastructureExternalSecret::class)],
        ]],
    ];
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use Klass8s\Manifest\AbstractSelfMakingManifest;

// An operator's custom resource that names a sibling manifest, by class, inside a plain array.
class DatabaseCluster extends AbstractSelfMakingManifest
{
    public static function apiVersion(): string
    {
        return 'postgresql.cnpg.io/v1';
    }

    public static function kind(): string
    {
        return 'Cluster';
    }

    public static function shortName(): string
    {
        return 'database';
    }

    /**
     * @return array<string, mixed>
     */
    public function spec(): array
    {
        return [
            'instances' => 3,
            'storage' => ['size' => '20Gi'],
            'bootstrap' => ['initdb' => [
                'database' => 'shop',
                'secret' => ['name' => $this->app->resourceNameFromManifestClass(InfrastructureExternalSecret::class)],
            ]],
        ];
    }
}
Renderedbin/console k8s:render:apps certs shop
# File: /shop/database.cluster.yaml
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: database
  name: shop-database
spec:
  instances: 3
  storage:
    size: 20Gi
  bootstrap:
    initdb:
      database: shop
      secret:
        name: shop-infrastructure
---
# File: /shop/infrastructure.external-secret.yaml
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
  annotations:
    klass8s.dev/app: shop
    klass8s.dev/deploy-priority: '0'
  labels:
    app.kubernetes.io/name: shop
    app.kubernetes.io/component: infrastructure
  name: shop-infrastructure
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: platform
    kind: ClusterSecretStore
  target:
    name: shop-infrastructure
  dataFrom:
    -
      extract:
        key: shop/infrastructure

Limits

  • The output is apiVersion, kind, metadata and spec. A kind that needs other top-level keys does not fit; such kinds are rare.
  • A resource that needs an exact name (some operators look for one) implements FullNameAwareInterface with fullName().
  • Never use a self-making manifest for a kind Kubernetes knows: the base class of that kind brings its configurators, events and the framework's rules, and a self-made Deployment silently does without them.

CustomResourceDefinitions

An operator's CustomResourceDefinition is a resource most tools leave as hundreds of lines of YAML. Klass8s types its frame (names, versions, scope, subresources) and leaves the OpenAPI schema an array, which is your contract:

src/K8S/Certs/Manifest/CertificateCrd.phnsrc/K8S/Certs/Manifest/CertificateCrd.php
namespace App\K8S\Certs\Manifest;

use Klass8s\Core\Crd\AbstractCustomResourceDefinition;
use Klass8s\Core\Crd\Configurator\CrdNamesConfigurator;
use Klass8s\Core\Crd\Configurator\CrdVersionsConfigurator;

class CertificateCrd extends AbstractCustomResourceDefinition
{
    static shortName(): string => 'certificate-crd';

    group(): string => 'certs.acme.io';

    resourceKind(): string => 'Certificate';

    plural(): string => 'certificates';

    names(CrdNamesConfigurator $names): void => $names->singular('certificate')->shortNames('cert', 'certs')->categories('acme');

    versions(CrdVersionsConfigurator $versions): void {
        $v1 = $versions->addVersion('v1');
        $v1->openApiV3Schema([
            'type' => 'object',
            'properties' => [
                'spec' => [
                    'type' => 'object',
                    'required' => ['secretName', 'issuerRef'],
                    'properties' => [
                        'secretName' => ['type' => 'string'],
                        'issuerRef' => ['type' => 'object', 'properties' => ['name' => ['type' => 'string']]],
                    ],
                ],
                'status' => ['type' => 'object', 'properties' => ['ready' => ['type' => 'boolean']]],
            ],
        ]);
        $v1->addPrinterColumn('Ready', 'boolean', '.status.ready')->description('Whether the certificate is ready');
        $v1->subresources()->enableStatus();
        $v1->addSelectableField('.spec.issuerRef.name');

        $versions->addVersion('v1alpha1', served: true, storage: false)
            ->deprecated(warning: 'certs.acme.io/v1alpha1 is deprecated; use v1');
    }
}
<?php

declare(strict_types=1);

namespace App\K8S\Certs\Manifest;

use Klass8s\Core\Crd\AbstractCustomResourceDefinition;
use Klass8s\Core\Crd\Configurator\CrdNamesConfigurator;
use Klass8s\Core\Crd\Configurator\CrdVersionsConfigurator;

class CertificateCrd extends AbstractCustomResourceDefinition
{
    public static function shortName(): string
    {
        return 'certificate-crd';
    }

    public function group(): string
    {
        return 'certs.acme.io';
    }

    public function resourceKind(): string
    {
        return 'Certificate';
    }

    public function plural(): string
    {
        return 'certificates';
    }

    public function names(CrdNamesConfigurator $names): void
    {
        $names->singular('certificate')->shortNames('cert', 'certs')->categories('acme');
    }

    public function versions(CrdVersionsConfigurator $versions): void
    {
        $v1 = $versions->addVersion('v1');
        $v1->openApiV3Schema([
            'type' => 'object',
            'properties' => [
                'spec' => [
                    'type' => 'object',
                    'required' => ['secretName', 'issuerRef'],
                    'properties' => [
                        'secretName' => ['type' => 'string'],
                        'issuerRef' => ['type' => 'object', 'properties' => ['name' => ['type' => 'string']]],
                    ],
                ],
                'status' => ['type' => 'object', 'properties' => ['ready' => ['type' => 'boolean']]],
            ],
        ]);
        $v1->addPrinterColumn('Ready', 'boolean', '.status.ready')->description('Whether the certificate is ready');
        $v1->subresources()->enableStatus();
        $v1->addSelectableField('.spec.issuerRef.name');

        $versions->addVersion('v1alpha1', served: true, storage: false)
            ->deprecated(warning: 'certs.acme.io/v1alpha1 is deprecated; use v1');
    }
}
  • Identity. group(), resourceKind() and plural() are required. The resource name is <plural>.<group> (certificates.certs.acme.io), as Kubernetes requires; shortName() still identifies the class to the framework.
  • Scope. scope() returns CrdScope::Namespaced unless overridden with CrdScope::Cluster.
  • Versions. Each addVersion($name, served:, storage:) returns a builder for that version: its schema, printer columns for kubectl get, the status and scale subresources, selectable fields and deprecation.
  • configureCrd() receives the generated object.

Next