Course contentsShow
← C#
Lesson 1845 of 1,90817. Deployment and Cloud ArchitectureFree lesson

Managing Configuration via ConfigMaps and Secrets

Mount Kubernetes secrets as files or environment variables into .NET application settings.

In this lesson, you will learn how to integrate Kubernetes ConfigMaps and Secrets directly into your .NET application’s configuration pipeline to decouple your infrastructure from your code.

As we move from managing basic environment variables to robust Kubernetes-native configuration, we utilize ConfigMaps for non-sensitive data (like feature flags or API URLs) and Secrets for sensitive data (like connection strings or OAuth tokens). While you can map these to standard environment variables, the most secure and idiomatic way in a Kubernetes environment is to mount them as files within your container.

Mounting Secrets as Files

When you mount a Secret or ConfigMap as a volume in your deployment.yaml, Kubernetes projects each key-value pair as an individual file within a directory. For instance, if you mount a secret to /app/config, a secret key named DbPassword becomes a file located at /app/config/DbPassword.

To make these available to your .NET application, you simply point your ConfigurationBuilder to that directory using the AddKeyPerFile provider:

var builder = WebApplication.CreateBuilder(args);

// Add the directory mounted from your Kubernetes Secret or ConfigMap
builder.Configuration.AddKeyPerFile(directoryPath: "/app/config", optional: true);

var app = builder.Build();

Why This Approach?

Using AddKeyPerFile offers several advantages for advanced .NET container deployments:

  1. Dynamic Updates: If you update a mounted ConfigMap, the files in the directory are updated by the Kubelet. Depending on your reload strategy, the application can pick up these changes without requiring a pod restart.
  2. File Permissions: Unlike environment variables, which can sometimes be dumped in process logs or via /proc/self/environ, file-based mounts allow for granular filesystem permissions.
  3. Configuration Hierarchy: By adding these providers after your appsettings.json and appsettings.{Environment}.json, you ensure that Kubernetes-injected values cleanly override your default development settings, maintaining a consistent IConfiguration abstraction throughout your application.

This method keeps your appsettings.json clean of environment-specific infrastructure details and relies on Kubernetes to "inject" the necessary runtime configuration directly into the expected filesystem location.

Key Takeaway: Use the AddKeyPerFile configuration provider to seamlessly map Kubernetes volumes to your IConfiguration tree, ensuring secure and decoupled settings management.