Skip to content
This repository was archived by the owner on Feb 6, 2026. It is now read-only.

Repository files navigation

K8sOperator.NET

Github ReleaseGitHub Actions Workflow StatusGitHub LicenseGithub Issues OpenGithub Pull Request OpenScheduled Code Security Testing

K8sOperator.NET is a powerful and intuitive library designed for creating Kubernetes Operators using C#. It simplifies the development of robust, cloud-native operators by leveraging the full capabilities of the .NET ecosystem, making it easier than ever to manage complex Kubernetes workloads with custom automation.

Alt text

Table of Contents

Features

  • 🚀 Easy Integration - Simple, intuitive API for building Kubernetes operators
  • 🎯 Custom Resource Support - Built-in support for Custom Resource Definitions (CRDs)
  • 🔄 Automatic Reconciliation - Event-driven reconciliation with finalizer support
  • 📦 MSBuild Integration - Automatic generation of manifests, Docker files, and launch settings
  • 🐳 Docker Ready - Generate optimized Dockerfiles with best practices
  • 🛠️ Built-in Commands - Help, version, install, and code generation commands
  • 🔐 Security First - Non-root containers, RBAC support, and security best practices
  • 📝 Source Generators - Compile-time generation of boilerplate code
  • 🎨 Flexible Configuration - MSBuild properties for operator customization
  • 🧪 Testable - Built with testing in mind

Installation

To install K8sOperator.NET, add the package to your .NET project:

dotnet add package K8sOperator.NET

Or add it manually to your .csproj file:

<PackageReferenceInclude="K8sOperator.NET"Version="*" />

Quick Start

Create a new ASP.NET Core Web Application and add K8sOperator.NET:

dotnet new web -n MyOperator
cd MyOperator
dotnet add package K8sOperator.NET

Update your Program.cs:

usingK8sOperator.NET;varbuilder=WebApplication.CreateBuilder(args);builder.Services.AddOperator();varapp=builder.Build();// Map your controllers here// app.MapController<MyController>();awaitapp.RunOperatorAsync();

Usage

Creating a Custom Resource

Define your custom resource by inheriting from CustomResource:

usingK8sOperator.NET;[KubernetesEntity(Group="example.com",ApiVersion="v1",Kind="MyResource",PluralName="myresources")]publicclassMyResource:CustomResource<MyResource.MySpec,MyResource.MyStatus>{publicclassMySpec{publicstringName{get;set;}=string.Empty;publicintReplicas{get;set;}=1;}publicclassMyStatus{publicstringPhase{get;set;}="Pending";publicDateTime?LastUpdated{get;set;}}}

Implementing a Controller

Create a controller to handle your custom resource:

usingK8sOperator.NET;usingMicrosoft.Extensions.Logging;publicclassMyController:OperatorController<MyResource>{privatereadonlyILogger<MyController>_logger;publicMyController(ILogger<MyController>logger){_logger=logger;}publicoverrideasyncTaskAddOrModifyAsync(MyResourceresource,CancellationTokencancellationToken){_logger.LogInformation("Reconciling {Name} with {Replicas} replicas",resource.Spec.Name,resource.Spec.Replicas);// Your reconciliation logic hereresource.Status=newMyResource.MyStatus{Phase="Running",LastUpdated=DateTime.UtcNow};awaitTask.CompletedTask;}publicoverrideasyncTaskDeleteAsync(MyResourceresource,CancellationTokencancellationToken){_logger.LogInformation("Deleting {Name}",resource.Metadata.Name);// Cleanup logic hereawaitTask.CompletedTask;}publicoverrideasyncTaskFinalizeAsync(MyResourceresource,CancellationTokencancellationToken){_logger.LogInformation("Finalizing {Name}",resource.Metadata.Name);// Finalization logic hereawaitTask.CompletedTask;}}

Setting Up the Operator

Wire everything together in Program.cs:

usingK8sOperator.NET;usingMyOperator;varbuilder=WebApplication.CreateBuilder(args);// Add operator servicesbuilder.Services.AddOperator();varapp=builder.Build();// Map the controller to watch MyResourceapp.MapController<MyController>();// Run the operatorawaitapp.RunOperatorAsync();

Commands

K8sOperator.NET includes several built-in commands:

CommandDescriptionAvailability
operatorRun the operator (watches for resources)All builds
installGenerate Kubernetes installation manifestsAll builds
versionDisplay version informationAll builds
helpShow available commandsAll builds
generate-launchsettingsGenerate Visual Studio launch profilesDebug only
generate-dockerfileGenerate optimized DockerfileDebug only

Note: The generate-* commands are development tools and are only available in Debug builds. They are automatically excluded from Release builds to keep your production operator lean.

Running Commands

# Run the operator
dotnet run -- operator
# Generate installation manifests
dotnet run -- install > install.yaml
# Show version
dotnet run -- version
# Generate launch settings (Debug only)
dotnet run -c Debug -- generate-launchsettings
# Generate Dockerfile (Debug only)
dotnet run -c Debug -- generate-dockerfile

Configuration

MSBuild Properties

K8sOperator.NET uses MSBuild properties to configure your operator. Add these to your .csproj file:

<PropertyGroup>
<!-- Operator Configuration -->
<OperatorName>my-operator</OperatorName>
<OperatorNamespace>my-namespace</OperatorNamespace>
<!-- Container Configuration -->
<ContainerRegistry>ghcr.io</ContainerRegistry>
<ContainerRepository>myorg/my-operator</ContainerRepository>
<ContainerImageTag>1.0.0</ContainerImageTag>
<ContainerFamily>alpine</ContainerFamily>
<!-- Auto-generation (opt-in) -->
<CreateOperatorLaunchSettings>true</CreateOperatorLaunchSettings>
<GenerateOperatorDockerfile>true</GenerateOperatorDockerfile>
</PropertyGroup>

Available Properties

PropertyDefaultDescription
OperatorName{project-name}Name of the operator
OperatorNamespace{project-name}-systemKubernetes namespace
ContainerRegistryghcr.ioContainer registry URL
ContainerRepository{Company}/{OperatorName}Repository path
ContainerImageTag{Version}Image tag
ContainerFamily(empty)Image variant (e.g., alpine, distroless)
CreateOperatorLaunchSettingsfalseAuto-generate launch profiles
GenerateOperatorDockerfilefalseAuto-generate Dockerfile

Auto-Generated Files

When enabled, K8sOperator.NET automatically generates:

1. Assembly Attributes

Metadata is embedded in your assembly:

[assembly:OperatorNameAttribute("my-operator")][assembly:NamespaceAttribute("my-namespace")][assembly:DockerImageAttribute("ghcr.io","myorg/my-operator","1.0.0-alpine")]

2. Launch Settings (Properties/launchSettings.json)

Visual Studio launch profiles for all registered commands:

{
"profiles": {
"Operator": {
"commandName": "Project",
"commandLineArgs": "operator",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Install": {
"commandName": "Project",
"commandLineArgs": "install > ./install.yaml"
}
}
}

3. Dockerfile

Optimized multi-stage Dockerfile with security best practices:

FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY ["MyOperator.csproj", "./"]
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app/publish
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
WORKDIR /app
RUN groupadd -r operator && useradd -r -g operator operator
COPY --from=build /app/publish .
RUN chown -R operator:operator /app
USER operator
ENTRYPOINT ["dotnet", "MyOperator.dll"]
CMD ["operator"]

4. .dockerignore

Optimized Docker ignore file to reduce image size.

Docker Support

Building Docker Images

K8sOperator.NET generates production-ready Dockerfiles with:

  • ✅ Multi-stage builds for smaller images
  • ✅ Non-root user for security
  • ✅ Health checks
  • ✅ .NET 10 runtime
  • ✅ Optimized layer caching

Generate a Dockerfile:

dotnet run -- generate-dockerfile

Build the image:

docker build -t ghcr.io/myorg/my-operator:1.0.0 .

Push to registry:

docker push ghcr.io/myorg/my-operator:1.0.0

Installing in Kubernetes

Generate installation manifests:

dotnet run -- install > install.yaml

The generated manifest includes:

  • Custom Resource Definitions (CRDs)
  • ServiceAccount
  • ClusterRole and ClusterRoleBinding
  • Deployment

Apply to your cluster:

kubectl apply -f install.yaml

Verify Installation

# Check if operator is running
kubectl get pods -n my-namespace
# View operator logs
kubectl logs -n my-namespace deployment/my-operator -f
# Check CRDs
kubectl get crds
# Create a custom resource
kubectl apply -f my-resource.yaml

Contributing

Contributions are welcome! Please feel free to submit a pull request or open an issue if you encounter any bugs or have feature requests.

Development Setup

  1. Clone the repository

    git clone https://github.com/pmdevers/K8sOperator.NET.git
    cd K8sOperator.NET
  2. Build the solution

    dotnet build
  3. Run tests

    dotnet test
  4. Run the example operator

    cd examples/SimpleOperator
    dotnet run -- operator

Contribution Guidelines

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Please ensure:

  • ✅ All tests pass
  • ✅ Code follows existing style conventions
  • ✅ New features include tests
  • ✅ Documentation is updated

License

This project is licensed under the MIT License - see the LICENSE file for details.


Built with ❤️ using .NET 10

For more examples and documentation, visit the GitHub repository.

About

K8sOperator.NET is a powerful and intuitive library designed for creating Kubernetes Operators using C#. It simplifies the development of robust, cloud-native operators by leveraging the full capabilities of the .NET ecosystem, making it easier than ever to manage complex Kubernetes workloads with custom automation.

Resources

Code of conduct

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages