Advanced API Operations - kubernetes-client/csharp

Advanced API Operations for the Kubernetes client library in C# (kubernetes-client/csharp) include patching objects with strategic merge patches and using the API for Kubernetes events and logs.

Patching Objects with Strategic Merge Patches

Kubernetes objects can be updated using patch requests. A strategic merge patch applies partial updates to a resource by using a JSON merge patch document. The C# library provides a Patch method for this purpose. Here’s an example:

using k8s;
using k8s.Models;
using System;
using System.Collections.Generic;

class Program
{
static void Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);

int namespaceId = 123;
string deploymentName = "my-deployment";

var patch = new Dictionary<string, object>
{
{"spec", new
{
template = new V1PodTemplateSpec
{
Spec = new V1PodSpec
{
Containers = new List<V1Container>
{
new V1Container
{
Name = "my-container",
Image = "my-new-image:latest"
}
}
}
}
}
}
};

client.PatchNamespacedDeploymentStatus(deploymentName, namespaceId, patch, "strategic", null, null, null);
}
}

This example patches a deployment with a new container image. The Patch method takes the following parameters:

  • The name of the resource
  • The namespace of the resource
  • The patch document
  • The merge strategy (“strategic” or “json”)
  • Headers (optional)
  • If-Match value (optional)
  • Prevent retries (optional)

More information about patching resources can be found in the Kubernetes documentation.