Skip to main content

Webhooks

Webhooks let the API server ask your operator before it stores a resource: to set defaults, to reject invalid input, or to convert between the versions of an entity.

You implement

MutationWebhook<TEntity>, ValidationWebhook<TEntity> or ConversionWebhook<TEntity>

It runs
Synchronously in every create, update or delete request, before the resource is stored
You return
Modified or NoChanges; Success or Fail; the converted entity
Never
Cause side effects; webhooks also run for dryRun requests and may run twice

Set up webhooks​

Webhooks need the KubeOps.Operator.Web package and an ASP.NET Core app (Microsoft.NET.Sdk.Web) that maps the controllers:

Program.cs
builder.Services.AddKubernetesOperator().RegisterComponents();
builder.Services.AddControllers();

var app = builder.Build();
app.UseRouting();
app.MapControllers();

RegisterComponents() registers every webhook class of the project. The generated manifests contain the webhook configurations, the service and the certificates; for a webhook on your machine, see Local Development.

How webhooks work​

WebhookUse it toBase class
MutationSet defaults and normalize values; runs firstMutationWebhook<TEntity>
ValidationReject invalid resources; runs after all mutationsValidationWebhook<TEntity>
ConversionConvert between the versions of an entityConversionWebhook<TEntity>
  1. Mutation webhooks run first and may change the resource.
  2. Validation webhooks see the mutated resource and may only accept or reject it.
  3. The API server stores the resource only if every validation webhook allows it; otherwise the client gets the error message of your webhook.

Conversion webhooks are not part of this flow: the API server calls them whenever it reads or writes a resource in a version other than the stored one.

Mutation webhooks​

Return Modified(entity) with the changed entity or NoChanges():

DemoMutationWebhook.cs
[MutationWebhook(typeof(V1DemoEntity))]
public class DemoMutationWebhook : MutationWebhook<V1DemoEntity>
{
public override MutationResult<V1DemoEntity> Create(
V1DemoEntity entity, bool dryRun)
{
if (!string.IsNullOrEmpty(entity.Spec.Username))
{
return NoChanges();
}

entity.Spec.Username = "anonymous";
return Modified(entity);
}
}
  • Idempotent. The API server may call the webhook again on the mutated object; the result must stay the same.
  • Defaults only. Reject invalid input in a validation webhook instead of fixing it silently; your validator must accept everything your mutator produces.

Validation webhooks​

Override Create, Update or Delete, or their …Async variants, and return Success() or Fail():

DemoValidationWebhook.cs
[ValidationWebhook(typeof(V1DemoEntity))]
public class DemoValidationWebhook : ValidationWebhook<V1DemoEntity>
{
public override ValidationResult Create(V1DemoEntity entity, bool dryRun)
=> entity.Spec.Username == "forbidden"
? Fail("spec.username must not be 'forbidden'.", 422)
: Success();
}
  • Fast and local. The API server waits at most 10 seconds by default. Validate the request itself; avoid calls to other systems.
  • Clear messages. The message appears in the kubectl output: name the field and a valid value.
  • Warnings. Success("…") accepts the resource and shows the warnings to the user.

Conversion webhooks​

When an entity has several versions, Kubernetes stores each resource in the storage version and converts it for clients of the other versions. Register one converter per other version:

DemoConversionWebhook.cs
[ConversionWebhook(typeof(V2DemoEntity))]
public class DemoConversionWebhook : ConversionWebhook<V2DemoEntity>
{
protected override IEnumerable<IEntityConverter<V2DemoEntity>> Converters =>
[new V1ToV2()];

private sealed class V1ToV2 : IEntityConverter<V1DemoEntity, V2DemoEntity>
{
public V2DemoEntity Convert(V1DemoEntity from)
{
var result = new V2DemoEntity { Metadata = from.Metadata };
result.Spec.DisplayName = from.Spec.Name;
return result;
}

public V1DemoEntity Revert(V2DemoEntity to)
{
var result = new V1DemoEntity { Metadata = to.Metadata };
result.Spec.Name = to.Spec.DisplayName;
return result;
}
}
}
  • Lossless round trips. Revert(Convert(x)) must return x, or an old client destroys data on its next write. Keep fields that only exist in the newer version, e.g. in an annotation.
  • Storage version last. Ship a new version as served first and make it the storage version once its conversion works; test with stored resources of every version.

Routes and registration​

WebhookRouteExample for V1DemoEntity
Validation/validate/{type}/validate/v1demoentity
Mutation/mutate/{type}/mutate/v1demoentity
Conversion/convert/{group}/{plural}/convert/demo.kubeops.dev/demoentities

{type} is the C# type name of the entity in lowercase.

  • Own base classes. A webhook class may derive from its base class through a class of your own, e.g. an abstract generic base that adds logging. Abstract classes are not registered.
  • One per entity. Each entity kind, group and version can have one validation and one mutation webhook. With a second one, the operator fails to start and names the duplicate.
  • Resources only. The webhooks are registered for the resource, not for its status subresource.

Common pitfalls​

An unreachable webhook blocks the resource type

By default the API server rejects every write when a webhook is down, including the operator's own writes. Set FailurePolicy to Ignore in a custom webhook configuration factory if a skipped check is acceptable.

Local development considerations​

When the operator runs on your machine, the API server must reach its webhooks over HTTPS: with a certificate for your IP, a tunnel or Aspire. See Local Development for the setup, security notes and leftover webhook configurations.

Next steps​