Convert Figma logo to code with AI

kubernetes-client logocsharp

Officially supported dotnet Kubernetes Client library

1,088
292
1,088
5

Top Related Projects

Go client for Kubernetes.

6,694

Official Python client library for kubernetes

3,537

Official Java client library for kubernetes

Javascript client

23,209

Complete container management platform

Quick Overview

The kubernetes-client/csharp repository is the official Kubernetes client library for C#. It provides a set of tools and APIs to interact with Kubernetes clusters programmatically using C#. This client library allows developers to manage Kubernetes resources, deploy applications, and automate cluster operations within their C# applications.

Pros

  • Official and well-maintained client library for Kubernetes in C#
  • Supports both synchronous and asynchronous operations
  • Provides strongly-typed models for Kubernetes resources
  • Integrates well with .NET ecosystem and tooling

Cons

  • Learning curve for developers new to Kubernetes concepts
  • Documentation could be more comprehensive
  • May require frequent updates to keep up with Kubernetes API changes
  • Limited community support compared to some other language clients

Code Examples

  1. Creating a Kubernetes client:
using k8s;

var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
var client = new Kubernetes(config);
  1. Listing pods in a namespace:
var pods = await client.ListNamespacedPodAsync("default");
foreach (var pod in pods.Items)
{
    Console.WriteLine($"Pod: {pod.Metadata.Name}");
}
  1. Creating a deployment:
var deployment = new V1Deployment
{
    Metadata = new V1ObjectMeta { Name = "example-deployment" },
    Spec = new V1DeploymentSpec
    {
        Replicas = 3,
        Selector = new V1LabelSelector { MatchLabels = new Dictionary<string, string> { { "app", "example" } } },
        Template = new V1PodTemplateSpec
        {
            Metadata = new V1ObjectMeta { Labels = new Dictionary<string, string> { { "app", "example" } } },
            Spec = new V1PodSpec
            {
                Containers = new List<V1Container>
                {
                    new V1Container
                    {
                        Name = "example-container",
                        Image = "nginx:latest"
                    }
                }
            }
        }
    }
};

await client.CreateNamespacedDeploymentAsync(deployment, "default");

Getting Started

  1. Install the NuGet package:

    dotnet add package KubernetesClient
    
  2. Create a Kubernetes client:

    using k8s;
    
    var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
    var client = new Kubernetes(config);
    
  3. Use the client to interact with your Kubernetes cluster:

    var namespaces = await client.ListNamespaceAsync();
    foreach (var ns in namespaces.Items)
    {
        Console.WriteLine($"Namespace: {ns.Metadata.Name}");
    }
    

Competitor Comparisons

Go client for Kubernetes.

Pros of client-go

  • Written in Go, offering better performance and native integration with Kubernetes (also written in Go)
  • More mature and actively maintained, with frequent updates and a larger community
  • Provides more comprehensive features and deeper integration with Kubernetes internals

Cons of client-go

  • Steeper learning curve for developers not familiar with Go
  • May require more boilerplate code compared to C# for certain operations
  • Less suitable for projects primarily using .NET technologies

Code Comparison

client-go (Go):

clientset, err := kubernetes.NewForConfig(config)
pods, err := clientset.CoreV1().Pods("default").List(context.TODO(), metav1.ListOptions{})
for _, pod := range pods.Items {
    fmt.Printf("Pod Name: %s\n", pod.Name)
}

csharp (C#):

var client = new Kubernetes(KubernetesClientConfiguration.BuildDefaultConfig());
var pods = await client.ListNamespacedPodAsync("default");
foreach (var pod in pods.Items)
{
    Console.WriteLine($"Pod Name: {pod.Metadata.Name}");
}

Both examples demonstrate listing pods in the default namespace, showcasing the syntax differences between Go and C#. The client-go example uses a more explicit approach with separate client creation and method calls, while the csharp client provides a more streamlined API.

6,694

Official Python client library for kubernetes

Pros of python

  • More mature and actively maintained repository with frequent updates
  • Larger community and better documentation
  • Supports both synchronous and asynchronous programming models

Cons of python

  • Slower performance compared to C# for certain operations
  • Less integration with strongly-typed languages and .NET ecosystem
  • May require additional dependencies for some advanced features

Code Comparison

Python:

from kubernetes import client, config

config.load_kube_config()
v1 = client.CoreV1Api()
pods = v1.list_pod_for_all_namespaces()
for pod in pods.items:
    print(f"{pod.metadata.namespace}\t{pod.metadata.name}")

C#:

using k8s;

var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
var client = new Kubernetes(config);
var pods = client.ListPodForAllNamespaces();
foreach (var pod in pods.Items)
{
    Console.WriteLine($"{pod.Metadata.NamespaceProperty}\t{pod.Metadata.Name}");
}

Both examples demonstrate listing pods across all namespaces. The Python version is slightly more concise, while the C# version benefits from strong typing. The Python client offers more flexibility in terms of programming paradigms, while the C# client integrates better with .NET applications and provides compile-time type checking.

3,537

Official Java client library for kubernetes

Pros of java

  • More mature and actively maintained repository
  • Larger community and more frequent updates
  • Better documentation and examples

Cons of java

  • Larger codebase and potentially more complex to use
  • May have higher memory footprint compared to C#

Code Comparison

java:

ApiClient client = Config.defaultClient();
CoreV1Api api = new CoreV1Api(client);
V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);

csharp:

var config = KubernetesClientConfiguration.BuildDefaultConfig();
var client = new Kubernetes(config);
var list = client.ListPodForAllNamespaces();

The java client requires more explicit configuration and API instantiation, while the csharp client provides a more streamlined approach. However, the java client offers more flexibility in terms of customization and parameter passing.

Both repositories provide official Kubernetes client libraries for their respective languages. The java repository has a larger user base and more frequent updates, making it potentially more reliable for production use. On the other hand, the csharp repository offers a simpler API that may be easier for C# developers to integrate into their projects.

When choosing between the two, consider factors such as your team's expertise, project requirements, and the need for specific features or customizations.

Javascript client

Pros of javascript

  • Wider ecosystem and community support in the JavaScript world
  • Easier integration with web-based applications and Node.js environments
  • More flexible and dynamic typing, allowing for quicker prototyping

Cons of javascript

  • Potentially less type safety compared to C#'s strong typing system
  • May have performance limitations for large-scale, computationally intensive operations
  • Asynchronous programming model can be more complex for some developers

Code Comparison

csharp:

var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
var client = new Kubernetes(config);
var pods = await client.ListNamespacedPodAsync("default");
foreach (var item in pods.Items)
{
    Console.WriteLine(item.Metadata.Name);
}

javascript:

const k8s = require('@kubernetes/client-node');
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
const res = await k8sApi.listNamespacedPod('default');
res.body.items.forEach(item => console.log(item.metadata.name));

Both repositories provide client libraries for interacting with Kubernetes clusters, but they cater to different programming languages and ecosystems. The csharp repository is ideal for .NET developers working in strongly-typed environments, while the javascript repository is more suitable for web and Node.js developers who prefer a more flexible and dynamic approach.

23,209

Complete container management platform

Pros of Rancher

  • Provides a complete container management platform with a user-friendly GUI
  • Offers multi-cluster management and supports multiple Kubernetes distributions
  • Includes built-in security features and access control

Cons of Rancher

  • More complex setup and resource-intensive compared to a simple client library
  • May introduce additional overhead for small-scale deployments
  • Steeper learning curve for users new to container orchestration

Code Comparison

While a direct code comparison isn't particularly relevant due to the different nature of these projects, here's a brief example of how they might be used:

Rancher (YAML configuration):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: example

Kubernetes C# Client:

var deployment = new V1Deployment
{
    Metadata = new V1ObjectMeta { Name = "example-deployment" },
    Spec = new V1DeploymentSpec
    {
        Replicas = 3,
        Selector = new V1LabelSelector { MatchLabels = new Dictionary<string, string> { { "app", "example" } } }
    }
};

The Rancher example shows a YAML configuration, while the Kubernetes C# Client demonstrates programmatic creation of a deployment.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Kubernetes C# Client

Github Actions Build Client Capabilities Client Support Level

Usage

KubernetesClient

dotnet add package KubernetesClient

Generate with Visual Studio

dotnet msbuild /Restore /t:SlnGen kubernetes-client.proj

Authentication/Configuration

You should be able to use a standard KubeConfig file with this library, see the BuildConfigFromConfigFile function below. Most authentication methods are currently supported, but a few are not, see the known-issues.

You should also be able to authenticate with the in-cluster service account using the InClusterConfig function shown below.

Monitoring

Metrics are built in to HttpClient using System.Diagnostics.DiagnosticsSource. https://learn.microsoft.com/en-us/dotnet/core/diagnostics/built-in-metrics-system-net

There are many ways these metrics can be consumed/exposed but that decision is up to the application, not KubernetesClient itself. https://learn.microsoft.com/en-us/dotnet/core/diagnostics/metrics-collection

Sample Code

Creating the client

// Load from the default kubeconfig on the machine.
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();

// Load from a specific file:
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(Environment.GetEnvironmentVariable("KUBECONFIG"));

// Load from in-cluster configuration:
var config = KubernetesClientConfiguration.InClusterConfig()

// Use the config object to create a client.
var client = new Kubernetes(config);

Listing Objects

var namespaces = client.CoreV1.ListNamespace();
foreach (var ns in namespaces.Items) {
    Console.WriteLine(ns.Metadata.Name);
    var list = client.CoreV1.ListNamespacedPod(ns.Metadata.Name);
    foreach (var item in list.Items)
    {
        Console.WriteLine(item.Metadata.Name);
    }
}

Creating and Deleting Objects

var ns = new V1Namespace
{
    Metadata = new V1ObjectMeta
    {
        Name = "test"
    }
};

var result = client.CoreV1.CreateNamespace(ns);
Console.WriteLine(result);

var status = client.CoreV1.DeleteNamespace(ns.Metadata.Name, new V1DeleteOptions());

Examples

There is extensive example code in the examples directory.

Running the examples

git clone git@github.com:kubernetes-client/csharp.git
cd csharp\examples\simple
dotnet run

Known issues

While the preferred way of connecting to a remote cluster from local machine is:

var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
var client = new Kubernetes(config);

Not all auth providers are supported at the moment #91. You can still connect to a cluster by starting the proxy command:

$ kubectl proxy
Starting to serve on 127.0.0.1:8001

and changing config:

var config = new KubernetesClientConfiguration {  Host = "http://127.0.0.1:8001" };

Notice that this is a workaround and is not recommended for production use.

Testing

The project uses XUnit as unit testing framework.

To run the tests:

cd csharp\tests
dotnet restore
dotnet test

Update the API model

Prerequisites

You'll need a Linux machine with Docker.

Check out the generator project into some other directory (henceforth $GEN_DIR).

cd $GEN_DIR/..
git clone https://github.com/kubernetes-client/gen

Generating new swagger.json

# Where REPO_DIR points to the root of the csharp repository
cd
${GEN_DIR}/openapi/csharp.sh ${REPO_DIR}/src/KubernetesClient ${REPO_DIR}/csharp.settings

Version Compatibility

SDK VersionKubernetes Version.NET Targeting
14.01.30net6.0;net8.0;net48*;netstandard2.0*
13.01.29net6.0;net7.0;net8.0;net48*;netstandard2.0*
12.01.28net6.0;net7.0;net48*;netstandard2.0*
11.01.27net6.0;net7.0;net48*;netstandard2.0*
10.01.26net6.0;net7.0;net48*;netstandard2.0*
9.11.25netstandard2.1;net6.0;net7.0;net48*;netstandard2.0*
9.01.25netstandard2.1;net5.0;net6.0;net48*;netstandard2.0*
8.01.24netstandard2.1;net5.0;net6.0;net48*;netstandard2.0*
7.21.23netstandard2.1;net5.0;net6.0;net48*;netstandard2.0*
7.01.23netstandard2.1;net5.0;net6.0
6.01.22netstandard2.1;net5.0
5.01.21netstandard2.1;net5
4.01.20netstandard2.0;netstandard2.1
3.01.19netstandard2.0;net452
2.01.18netstandard2.0;net452
1.61.16netstandard1.4;netstandard2.0;net452;
1.41.13netstandard1.4;net451
1.31.12netstandard1.4;net452
  • Starting from 2.0, dotnet sdk versioning adopted

  • Kubernetes Version here means the version sdk models and apis were generated from

  • Kubernetes api server guarantees the compatibility with n-2 (n-3 after 1.28) version. for example:

    • 1.19 based sdk should work with 1.21 cluster, but not guaranteed to work with 1.22 cluster.

    and vice versa:

    • 1.21 based sdk should work with 1.19 cluster, but not guaranteed to work with 1.18 cluster.
      Note: in practice, the sdk might work with much older clusters, at least for the more stable functionality. However, it is not guaranteed past the n-2 (or n-3 after 1.28 ) version. See #1511 for additional details.

    see also https://kubernetes.io/releases/version-skew-policy/

  • Fixes (including security fixes) are not back-ported automatically to older sdk versions. However, contributions from the community are welcomed 😊; See Contributing for instructions on how to contribute.

  • * KubernetesClient.Classic: netstandard2.0 and net48 are supported with limited features

Contributing

Please see CONTRIBUTING.md for instructions on how to contribute.