GuideConfiguration and DI

Guide

Configuration and DI

How values reach manifests - bindings for facts of the platform, injected services for shared logic, and per-manifest data from the configuration files.

Manifests are Symfony services. That replaces the whole question of how values get into templates (values.yaml, --set, patches) with the mechanisms every Symfony application already has. There are three channels.

Bindings: facts of the platform

A value many manifests need (the environment, a hostname, the image tag a pipeline chose) is bound once in config/services.yaml and reaches every constructor that names the parameter. Symfony's parameters and environment variables work as anywhere else, with defaults for a render on a laptop:

config/services.yaml
parameters:
    # defaults for a render on a laptop; a pipeline sets the variables
    env(IMAGE_TAG): 'latest'
    env(PUBLIC_HOSTNAME): 'shop.example.test'

services:
    _defaults:
        autowire: true
        autoconfigure: true
        bind:
            $imageTag: '%env(IMAGE_TAG)%'
            $publicHostname: '%env(PUBLIC_HOSTNAME)%'

    App\:
        resource: '../src/'
        exclude:
            - '../src/Kernel.php'
            - '../src/K8S/*/Container/'

Symfony refuses a binding no constructor uses, which keeps the list honest.

Services: logic you would otherwise copy

Constructors take whole services, not only values. A rule that several manifests need is a class:

src/Service/DatabaseUrls.phnsrc/Service/DatabaseUrls.php
namespace App\Service;

use App\K8S\Database\DatabaseApp;
use App\K8S\Database\Manifest\PostgresService;
use Klass8s\Registry\AppRegistry;

/** Connection URLs to the database App's Service, for any manifest that needs one. */
final readonly class DatabaseUrls
{
    __construct(private AppRegistry $apps) {}

    forDatabase(string $database): string {
        $host = $this->apps->get(DatabaseApp::NAME)->resourceNameFromManifestClass(PostgresService::class);

        return sprintf('postgresql://%s:%d/%s', $host, PostgresService::PORT, $database);
    }
}
<?php

declare(strict_types=1);

namespace App\Service;

use App\K8S\Database\DatabaseApp;
use App\K8S\Database\Manifest\PostgresService;
use Klass8s\Registry\AppRegistry;

/** Connection URLs to the database App's Service, for any manifest that needs one. */
final readonly class DatabaseUrls
{
    public function __construct(private AppRegistry $apps) {}

    public function forDatabase(string $database): string
    {
        $host = $this->apps->get(DatabaseApp::NAME)->resourceNameFromManifestClass(PostgresService::class);

        return sprintf('postgresql://%s:%d/%s', $host, PostgresService::PORT, $database);
    }
}
src/K8S/Shop/Manifest/ApiDeployment.phnsrc/K8S/Shop/Manifest/ApiDeployment.php
namespace App\K8S\Shop\Manifest;

use App\Service\DatabaseUrls;
use Klass8s\Core\Container\Env\EnvConfigurator;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Deployment\AbstractContainerDeployment;

class ApiDeployment extends AbstractContainerDeployment
{
    // $imageTag and $publicHostname are bindings of config/services.yaml; DatabaseUrls is a service
    __construct(
        private string $imageTag,
        private string $publicHostname,
        private DatabaseUrls $databases,
    ) {}

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

    image(): Image => Image::fromName('acme/shop-api')->setTag($this->imageTag);

    env(EnvConfigurator $env): void {
        $env->var('PUBLIC_URL', 'https://'.$this->publicHostname)
            ->var('DATABASE_URL', $this->databases->forDatabase('shop'));
    }
}
<?php

declare(strict_types=1);

namespace App\K8S\Shop\Manifest;

use App\Service\DatabaseUrls;
use Klass8s\Core\Container\Env\EnvConfigurator;
use Klass8s\Core\Container\Image\Image;
use Klass8s\Core\Deployment\AbstractContainerDeployment;

class ApiDeployment extends AbstractContainerDeployment
{
    // $imageTag and $publicHostname are bindings of config/services.yaml; DatabaseUrls is a service
    public function __construct(
        private string $imageTag,
        private string $publicHostname,
        private DatabaseUrls $databases,
    ) {}

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

    public function image(): Image
    {
        return Image::fromName('acme/shop-api')->setTag($this->imageTag);
    }

    public function env(EnvConfigurator $env): void
    {
        $env->var('PUBLIC_URL', 'https://'.$this->publicHostname)
            ->var('DATABASE_URL', $this->databases->forDatabase('shop'));
    }
}

AppRegistry, the registry of Apps by name, is the framework service injected most often (Apps).

A pipeline sets the variables, and the class does not change:

IMAGE_TAG=sha-4f2c9e1 PUBLIC_HOSTNAME=shop.example.com bin/console k8s:render:apps shop
RenderedIMAGE_TAG=sha-4f2c9e1 PUBLIC_HOSTNAME=shop.example.com bin/console k8s:render:apps shop
# File: /shop/api.deployment.yaml
apiVersion: apps/v1
kind: Deployment
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:
  replicas: 1
  revisionHistoryLimit: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: shop
      app.kubernetes.io/component: api
  template:
    metadata:
      annotations:
        klass8s.dev/env-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
        klass8s.dev/volume-sources-checksum: d41d8cd98f00b204e9800998ecf8427e
      labels:
        app.kubernetes.io/name: shop
        app.kubernetes.io/component: api
    spec:
      containers:
        -
          env:
            - { name: PUBLIC_URL, value: 'https://shop.example.com' }
            - { name: DATABASE_URL, value: 'postgresql://database-postgres:5432/shop' }
          image: 'acme/shop-api:sha-4f2c9e1'
          imagePullPolicy: IfNotPresent
          name: app

Per-manifest data: $this->config

Every manifest receives the keys its App's entry in config/packages/klass8s.yaml gives it, as $this->config. Unknown keys are allowed by design: the schema is yours. With per-environment configuration files, production can get other values without a line of code; Manifests shows both.

Choosing a channel

The value isUseExample
a fact of the whole projecta bindingthe environment, a gateway's name, a hostname
chosen by the pipeline for each rendera binding to an environment variable$imageTag from %env(IMAGE_TAG)%
computed, or logic several manifests sharean injected serviceURL builders, naming helpers
tuning for one manifest, possibly per environment$this->configa rate limit, a feature switch
a difference in structure between environmentsnone of these: environment methodsreplicasProd()

Code for structure, configuration for numbers: when a value changes the shape of a resource (an extra listener, another volume), express it as a method a reviewer reads; when it is a dial (replicas, limits, a rate), let it be data.

What to avoid

  • Reading the process environment in a manifest (getenv(), $_ENV). It bypasses the container, ignores per-environment configuration and hides the dependency. Declare a constructor parameter and bind it.
  • ConfigMaps as the input of the render. Bindings and $this->config configure the program that renders; ConfigMaps configure the workloads at run time.
  • Resource names as strings. A name another class derives, typed out by hand, is the drift Klass8s exists to prevent; use a class reference or resourceNameFromManifestClass().

The framework's own configuration

The framework's settings (locations, the behaviour flags, Apps, Helm releases) are under the same klass8s: key and listed in the configuration reference.

Next

Environments: the logic side of what differs between environments.