The C# Operator SDK is a framework to build Kubernetes operators with C# and .NET Core.
- Easy custom resource and controller definition as C# classes
- Custom resource event watchers at namespace and cluster scope
- Configurable retry-on-failure policy
- Smart concurrent event queues (inspired by Container Solution's article)
- Kubernetes graceful termination policy support
Setup a new .NET Core 3.1 project and add the C# Operator SDK package:
dotnet new console
dotnet add package k8s.Operators
Assuming that you have already added a custom resource definition for MyResource
in your Kubernetes cluster, define a class deriving from CustomResource
for the custom resource schema:
// Set the CRD attributes
[CustomResourceDefinition("example.com", "v1", "myresources")]
public class MyResource : CustomResource<MyResource.MyResourceSpec, MyResource.MyResourceStatus>
{
// Define spec
public class MyResourceSpec
{
public int property1 { get; set; }
// :
}
// Define status
public class MyResourceStatus
{
public int property2 { get; set; }
// :
}
}
Define a class deriving from Controller
for the controller logic:
public class MyResourceController : Controller<MyResource>
{
public MyResourceController(OperatorConfiguration configuration, IKubernetes client, ILoggerFactory loggerFactory = null)
: base(configuration, client, loggerFactory)
{
}
protected override async Task AddOrModifyAsync(MyResource resource, CancellationToken cancellationToken)
{
Console.WriteLine($"Add/Modify {resource}");
// :
// Handle Add/Modify event
}
protected override async Task DeleteAsync(MyResource resource, CancellationToken cancellationToken)
{
Console.WriteLine($"Delete {resource}");
// :
// Handle Delete event
}
}
Setup the operator in Main()
:
static async Task<int> Main(string[] args)
{
// Create the Kubernetes client
using var client = new Kubernetes(KubernetesClientConfiguration.BuildConfigFromConfigFile());
// Setup the operator
var @operator = new Operator(OperatorConfiguration.Default, client);
@operator.AddControllerOfType<MyResourceController>();
// Start the operator
return await @operator.StartAsync();
}
Curiosity: Since
operator
is a reserved keyword in C#, it has been escaped with@operator
.
Start the operator with:
dotnet run
In the /samples/basic
directory you find a sample operator that simulates the interaction with an external service and can be used as a template for real-world operators.
Follow the instructions to run it locally and deploy it to Kubernetes.
git clone https://github.com/falox/csharp-operator-sdk.git
cd csharp-operator-sdk
dotnet restore
dotnet build
Running the tests:
dotnet test
- Jason Dobies and Joshua Wood, Kubernetes Operators, O'Reilly, 2020
- Radu Matei, Writing controllers for Kubernetes CRDs with C#, 2019