Skip to main content

Custom Entities

An entity is a C# class that KubeOps turns into a Custom Resource Definition (CRD). Its spec holds what the user wants, its status what your controller observed.

You write
A partial class deriving from CustomKubernetesEntity
You get
A CRD manifest, generated on build or by the kubeops CLI
You shape
The schema with attributes: validation, defaults, printer columns
Avoid
[UniqueItems] and self-referencing types; both fail the generation

Define an entity​

V1DemoEntity.cs
[KubernetesEntity(
Group = "demo.kubeops.dev", ApiVersion = "v1", Kind = "DemoEntity")]
public partial class V1DemoEntity : CustomKubernetesEntity<
V1DemoEntity.V1DemoEntitySpec, V1DemoEntity.V1DemoEntityStatus>
{
public class V1DemoEntitySpec
{
public string Username { get; set; } = string.Empty;
}

public class V1DemoEntityStatus
{
public string DemoStatus { get; set; } = string.Empty;
}
}
Base classUse it for
CustomKubernetesEntityMetadata only
CustomKubernetesEntity<TSpec>A desired state in spec
CustomKubernetesEntity<TSpec, TStatus>spec plus an observed state in status; the CRD gets the status subresource

Declare the class partial: the source generator then adds a constructor that sets ApiVersion and Kind. For a class that is not partial or has its own parameterless constructor, call the generated new V1DemoEntity().Initialize() instead. Entities are namespaced by default; add [EntityScope(EntityScope.Cluster)] for a cluster-scoped resource.

How an entity becomes a CRD​

  1. Your entity class defines group, version and kind, and with its properties and attributes the schema of spec and status.
  2. The transpiler reads the compiled assembly and builds the CRD. It runs after a Release build and in kubeops generate operator; see Build Customization to change when.
  3. The CRD manifest lands in the config directory of your project, together with RBAC, deployment and kustomization files.
  4. The cluster gets the CRD with kubectl apply -k in production. During development, kubeops install (CLI) or the CRD Installer install it directly.

Write the status with client.UpdateStatusAsync(entity): with the status subresource, a normal update ignores status. Common CLR types map to OpenAPI types; a Guid becomes a string with format uuid, a DateTime or DateTimeOffset one with format date-time.

Versions​

Several classes with the same group and kind but different ApiVersion form one CRD with several versions. Kubernetes stores every resource in one of them:

  • Storage version. Mark it with [StorageVersion]. Without the attribute, the highest version (v2 over v1beta1) is stored; two marked versions fail the generation.
  • Conversion. The other versions need a conversion webhook.

Required fields​

[Required] on a property makes it required in its object. It also makes spec itself required when it sits on a direct property of the spec class; Kubernetes then rejects a resource without spec. Nested objects are not affected: annotate each level that must be present.

// spec is required, because Username is a direct required property
public class EntitySpec
{
[Required]
public string Username { get; set; } = null!;
}

// spec is required, even without required properties
[Required]
public class EntitySpec
{
public string Username { get; set; } = string.Empty;
}

// spec stays optional: Name is only checked when Nested is present
public class EntitySpec
{
public NestedSpec Nested { get; set; } = new();

public class NestedSpec
{
[Required]
public string Name { get; set; } = null!;
}
}

Attributes​

Entity​

AttributeEffect
[KubernetesEntity]Group, version and kind of the CRD
[EntityScope]Namespaced (default) or Cluster
[KubernetesEntityShortNames]Short names for kubectl, e.g. demo
[StorageVersion]The stored version, see Versions
[ScaleSubresource]Adds the scale subresource, see Scale subresource

Validation​

AttributeEffect
[Required]Required property; see Required fields
[Pattern]Regex for strings
[Length]Minimum and maximum length of a string; use [Items] for arrays
[Items]Minimum and maximum number of array items
[PropertyLimits]Minimum and maximum number of object properties
[RangeMinimum], [RangeMaximum]Numeric bounds, optionally exclusive
[MultipleOf]Number must be a multiple of the value
[EnumValues]Allowed values for strings, numbers and IntOrString; not empty, unique, matching the type
[ValidationRule]CEL rule (x-kubernetes-validations); class rules come before property rules
[XListType]List semantics: Atomic, Set or Map (x-kubernetes-list-type)
[XListMapKeys]Keys of a Map list, e.g. [XListMapKeys("name", "port")]
[XMapType]Object semantics: Granular or Atomic (x-kubernetes-map-type)

[UniqueItems] fails the generation, because CRDs do not allow uniqueItems. Use [XListType(XListType.Set)].

Documentation and defaults​

AttributeEffect
[Description], [Title]Text for a property or class
[ExternalDocs]Link to external documentation
[DefaultValue]OpenAPI default; Json = true for objects and arrays. On a class, it applies wherever the type is used, also to spec and status
[Example]OpenAPI example; Json = true for JSON values
[Format]Overrides the inferred format, e.g. [Format("uri")]; [Format(null)] removes it; an empty value fails

Printer columns​

AttributeEffect
[AdditionalPrinterColumn]Shows the property as a column in kubectl get
[GenericAdditionalPrinterColumn]Adds a column for any JSON path, on the entity class

Schema control​

AttributeEffect
[Ignore]Leaves out a property or entity, including its printer columns
[PreserveUnknownFields]Keeps the property as an open object; the modelled fields are still validated
[EmbeddedResource]Opaque embedded Kubernetes object; the type is not mapped

Use [PreserveUnknownFields] for types the transpiler cannot map, such as types from other libraries or types that refer to themselves (class Tree : List<Tree>, class Config : Dictionary<string, Config>). Without it, they fail the generation with a TranspilationFailedException; so do generic types nested deeper than 100 levels.

Example​

V1DemoEntity.cs
[KubernetesEntity(
Group = "demo.kubeops.dev", ApiVersion = "v1", Kind = "DemoEntity")]
[KubernetesEntityShortNames("demo")]
[Description("A demo entity")]
public partial class V1DemoEntity : CustomKubernetesEntity<
V1DemoEntity.V1DemoEntitySpec, V1DemoEntity.V1DemoEntityStatus>
{
public class V1DemoEntitySpec
{
[Required]
[Length(3, 50)]
[Description("The user the operator creates")]
public string Username { get; set; } = string.Empty;

[DefaultValue(1)]
[RangeMinimum(1)]
[RangeMaximum(10)]
public int Replicas { get; set; } = 1;

[Pattern(@"^[a-z0-9-]+$")]
public string? TargetNamespace { get; set; }

[Format("uri")]
[Example("https://example.com/events")]
public string? CallbackUrl { get; set; }

[DefaultValue("{}", Json = true)]
public Dictionary<string, string> Labels { get; set; } = [];
}

[DefaultValue("{}", Json = true)]
public class V1DemoEntityStatus
{
[AdditionalPrinterColumn]
public string CurrentState { get; set; } = string.Empty;

public DateTime LastUpdated { get; set; }
}
}

Scale subresource​

[ScaleSubresource] lets a HorizontalPodAutoscaler and kubectl scale change your resource. It takes JSON paths into the resource:

ParameterRequiredExample
specReplicasPathYes.spec.replicas
statusReplicasPathYes.status.replicas
labelSelectorPathNo, but needed by an HPA.status.selector
V1DemoEntity.cs
[KubernetesEntity(
Group = "demo.kubeops.dev", ApiVersion = "v1", Kind = "DemoEntity")]
[ScaleSubresource(".spec.replicas", ".status.replicas", ".status.selector")]
public partial class V1DemoEntity : CustomKubernetesEntity<
V1DemoEntity.V1DemoEntitySpec, V1DemoEntity.V1DemoEntityStatus>
{
public class V1DemoEntitySpec
{
public int Replicas { get; set; } = 1;
}

public class V1DemoEntityStatus
{
public int Replicas { get; set; }

public string Selector { get; set; } = string.Empty;
}
}

The generated CRD gets both subresources:

subresources:
status: {}
scale:
specReplicasPath: .spec.replicas
statusReplicasPath: .status.replicas
labelSelectorPath: .status.selector

The two are independent: an entity without a status class gets only scale.

Reuse attributes​

Only these attributes are read from base classes, so they can live on a shared base type: [ValidationRule] (rules along the chain are merged), [GenericAdditionalPrinterColumn] and attributes derived from it, and [DefaultValue] on a class. All other attributes, e.g. [KubernetesEntity], [EntityScope], [KubernetesEntityShortNames], [ScaleSubresource] and [Description], must be on the entity class itself.

For a named, reusable printer column, derive from GenericAdditionalPrinterColumnAttribute:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class ReadyPrinterColumnAttribute
: GenericAdditionalPrinterColumnAttribute
{
public ReadyPrinterColumnAttribute()
: base(
".status.conditions[?(@.type==\"Ready\")].status",
"Ready",
"string")
{
}
}

[KubernetesEntity(
Group = "demo.kubeops.dev", ApiVersion = "v1", Kind = "DemoEntity")]
[ReadyPrinterColumn]
public partial class V1DemoEntity : CustomKubernetesEntity { }

Common pitfalls​

  • An attribute on a base class has no effect. Only the attributes listed in Reuse attributes are inherited; put the others on the entity class.
  • The generation fails. [UniqueItems], self-referencing or unmappable types without [PreserveUnknownFields], or two versions marked [StorageVersion].
  • status is not saved. Use UpdateStatusAsync; a normal update ignores status with the status subresource.

Next steps​