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.
MutationWebhook<TEntity>, ValidationWebhook<TEntity> or ConversionWebhook<TEntity>
Modified or NoChanges; Success or Fail; the converted entitydryRun requests and may run twiceSet up webhooks
Webhooks need the KubeOps.Operator.Web package and an ASP.NET Core app (Microsoft.NET.Sdk.Web) that maps the
controllers:
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
| Webhook | Use it to | Base class |
|---|---|---|
| Mutation | Set defaults and normalize values; runs first | MutationWebhook<TEntity> |
| Validation | Reject invalid resources; runs after all mutations | ValidationWebhook<TEntity> |
| Conversion | Convert between the versions of an entity | ConversionWebhook<TEntity> |
- Mutation webhooks run first and may change the resource.
- Validation webhooks see the mutated resource and may only accept or reject it.
- 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():
[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():
[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
kubectloutput: 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:
[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 returnx, 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
| Webhook | Route | Example 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
statussubresource.
Common pitfalls
- The webhook intercepts the operator. Updates of your controller to the resource also pass your webhooks; status updates do not. Accept what the controller writes.
- The webhook is not called. See Webhooks are not called or block resource operations.
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.