K8sOperator.NET 0.0.2-alpha0001

This is a prerelease version of K8sOperator.NET.
dotnet add package K8sOperator.NET --version 0.0.2-alpha0001
                    
NuGet\Install-Package K8sOperator.NET -Version 0.0.2-alpha0001
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="K8sOperator.NET" Version="0.0.2-alpha0001" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="K8sOperator.NET" Version="0.0.2-alpha0001" />
                    
Directory.Packages.props
<PackageReference Include="K8sOperator.NET" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add K8sOperator.NET --version 0.0.2-alpha0001
                    
#r "nuget: K8sOperator.NET, 0.0.2-alpha0001"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package K8sOperator.NET@0.0.2-alpha0001
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=K8sOperator.NET&version=0.0.2-alpha0001&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=K8sOperator.NET&version=0.0.2-alpha0001&prerelease
                    
Install as a Cake Tool

K8sOperator.NET

Github Release GitHub Actions Workflow Status GitHub License Github Issues Open Github Pull Request Open Scheduled 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:

<PackageReference Include="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:

using K8sOperator.NET;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOperator();

var app = builder.Build();

// Map your controllers here
// app.MapController<MyController>();

await app.RunOperatorAsync();

Usage

Creating a Custom Resource

Define your custom resource by inheriting from CustomResource:

using K8sOperator.NET;

[KubernetesEntity(
    Group = "example.com",
    ApiVersion = "v1",
    Kind = "MyResource",
    PluralName = "myresources")]
public class MyResource : CustomResource<MyResource.MySpec, MyResource.MyStatus>
{
    public class MySpec
    {
        public string Name { get; set; } = string.Empty;
        public int Replicas { get; set; } = 1;
    }

    public class MyStatus
    {
        public string Phase { get; set; } = "Pending";
        public DateTime? LastUpdated { get; set; }
    }
}

Implementing a Controller

Create a controller to handle your custom resource:

using K8sOperator.NET;
using Microsoft.Extensions.Logging;

public class MyController : OperatorController<MyResource>
{
    private readonly ILogger<MyController> _logger;

    public MyController(ILogger<MyController> logger)
    {
        _logger = logger;
    }

    public override async Task AddOrModifyAsync(
        MyResource resource, 
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Reconciling {Name} with {Replicas} replicas",
            resource.Spec.Name,
            resource.Spec.Replicas);

        // Your reconciliation logic here
        resource.Status = new MyResource.MyStatus
        {
            Phase = "Running",
            LastUpdated = DateTime.UtcNow
        };

        await Task.CompletedTask;
    }

    public override async Task DeleteAsync(
        MyResource resource, 
        CancellationToken cancellationToken)
    {
        _logger.LogInformation("Deleting {Name}", resource.Metadata.Name);
        
        // Cleanup logic here
        await Task.CompletedTask;
    }

    public override async Task FinalizeAsync(
        MyResource resource, 
        CancellationToken cancellationToken)
    {
        _logger.LogInformation("Finalizing {Name}", resource.Metadata.Name);
        
        // Finalization logic here
        await Task.CompletedTask;
    }
}

Setting Up the Operator

Wire everything together in Program.cs:

using K8sOperator.NET;
using MyOperator;

var builder = WebApplication.CreateBuilder(args);

// Add operator services
builder.Services.AddOperator();

var app = builder.Build();

// Map the controller to watch MyResource
app.MapController<MyController>();

// Run the operator
await app.RunOperatorAsync();

Commands

K8sOperator.NET includes several built-in commands:

Command Description Availability
operator Run the operator (watches for resources) All builds
install Generate Kubernetes installation manifests All builds
version Display version information All builds
help Show available commands All builds
generate-launchsettings Generate Visual Studio launch profiles Debug only
generate-dockerfile Generate optimized Dockerfile Debug 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>
  
  <OperatorName>my-operator</OperatorName>
  <OperatorNamespace>my-namespace</OperatorNamespace>
  
  
  <ContainerRegistry>ghcr.io</ContainerRegistry>
  <ContainerRepository>myorg/my-operator</ContainerRepository>
  <ContainerImageTag>1.0.0</ContainerImageTag>
  <ContainerFamily>alpine</ContainerFamily>
  
  
  <CreateOperatorLaunchSettings>true</CreateOperatorLaunchSettings>
  <GenerateOperatorDockerfile>true</GenerateOperatorDockerfile>
</PropertyGroup>
Available Properties
Property Default Description
OperatorName {project-name} Name of the operator
OperatorNamespace {project-name}-system Kubernetes namespace
ContainerRegistry ghcr.io Container registry URL
ContainerRepository {Company}/{OperatorName} Repository path
ContainerImageTag {Version} Image tag
ContainerFamily (empty) Image variant (e.g., alpine, distroless)
CreateOperatorLaunchSettings false Auto-generate launch profiles
GenerateOperatorDockerfile false Auto-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.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on K8sOperator.NET:

Package Downloads
K8sOperator.NET.Generators

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.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.0.2-alpha0001 0 1/23/2026
0.0.1-alpha0021 49 1/12/2026
0.0.1-alpha0020 259 4/9/2025
0.0.1-alpha0019 261 4/2/2025
0.0.1-alpha0018 497 3/26/2025
0.0.1-alpha0017 477 3/25/2025
0.0.1-alpha0016 201 9/24/2024
0.0.1-alpha0015 108 9/18/2024
0.0.1-alpha0014 87 9/18/2024
0.0.1-alpha0013 92 9/18/2024
0.0.1-alpha0012 99 9/18/2024
0.0.1-alpha0011 108 9/17/2024
0.0.1-alpha0010 107 9/17/2024
0.0.1-alpha0009 196 9/10/2024
0.0.1-alpha0008 104 9/10/2024
0.0.1-alpha0007 106 9/10/2024
0.0.1-alpha0006 137 9/7/2024
0.0.1-alpha0005 103 9/7/2024
0.0.1-alpha0004 99 9/7/2024
0.0.1-alpha0003 117 9/3/2024
0.0.1-alpha0002 107 9/3/2024
0.0.1-alpha0001 95 9/3/2024