Wednesday, February 5, 2025

Read ConfigMap of Pods Namespace in AKS using .Net Core

 To fetch ConfigMaps using the above approach, you can modify the code to use the Kubernetes client API for retrieving ConfigMaps.

🔹 Steps to Fetch ConfigMaps in a Namespace

  1. Modify the code to call ListNamespacedConfigMapAsync.
  2. Iterate through the retrieved ConfigMaps.
  3. Extract and display the required details.

Updated C# Code to Fetch ConfigMaps in the openlens Namespace

using System;
using System.Threading.Tasks;
using k8s;
using k8s.Models;

class Program
{
    static async Task Main(string[] args)
    {
        // Load Kubernetes config
        var config = KubernetesClientConfiguration.BuildDefaultConfig();

        // Create Kubernetes client
        IKubernetes client = new Kubernetes(config);

        // Specify the namespace
        string namespaceName = "openlens"; // Change as needed

        try
        {
            // Get the list of ConfigMaps in the namespace
            var configMapList = await client.CoreV1.ListNamespacedConfigMapAsync(namespaceName);

            Console.WriteLine($"ConfigMaps in namespace '{namespaceName}':");

            foreach (var configMap in configMapList.Items)
            {
                Console.WriteLine($"- Name: {configMap.Metadata.Name}");
                Console.WriteLine("  Data:");

                // Display the key-value pairs inside the ConfigMap
                if (configMap.Data != null)
                {
                    foreach (var kvp in configMap.Data)
                    {
                        Console.WriteLine($"    {kvp.Key}: {kvp.Value}");
                    }
                }
                else
                {
                    Console.WriteLine("    (No data)");
                }

                Console.WriteLine(new string('-', 40));
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error fetching ConfigMaps: {ex.Message}");
        }
    }
}

How This Works

  1. Uses ListNamespacedConfigMapAsync(namespaceName) to get all ConfigMaps in the given namespace.
  2. Iterates through each ConfigMap and prints:
    • Name
    • Key-value pairs (if any)
  3. Handles errors gracefully.

🔹 Steps to Run

  1. Ensure kubectl is configured correctly.
  2. Install the KubernetesClient NuGet package:
    dotnet add package KubernetesClient
    
  3. Run the program:
    dotnet run
    


No comments :