In this lesson, you will learn how to shift from static Kubernetes Secrets to dynamic, on-demand secret injection for your .NET services using HashiCorp Vault.
Moving Beyond Static Secrets
While Kubernetes Secrets (often base64 encoded) are the standard for environment variables, they lack auditing, automatic rotation, and granular access control. By integrating Vault, we move secrets out of the Kubernetes etcd database and into a centralized, encrypted store.
The most effective way to integrate Vault with your .NET microservice in Kubernetes is via the Vault Agent Injector. Instead of your C# code manually authenticating with Vault APIs, you use Kubernetes annotations to instruct a sidecar container to fetch secrets and present them as a file in a shared memory volume (/vault/secrets/).
Implementation Strategy
First, add annotations to your deployment manifest to tell the Vault injector which secrets to fetch:
metadata:
annotations:
vault.hashicorp.com/agent-inject: "true"
vault.hashicorp.com/role: "dotnet-service-role"
vault.hashicorp.com/agent-inject-secret-appsettings.json: "secret/data/my-app/config"
The Vault agent will automatically populate a file at /vault/secrets/appsettings.json. To bridge this into your .NET application, you simply need to extend your IConfigurationBuilder during host initialization to look for this path:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
// Point .NET to the injected Vault secret file
config.AddJsonFile("/vault/secrets/appsettings.json", optional: true, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
Why this matters
By setting reloadOnChange: true, the .NET IOptions pattern will automatically detect changes if Vault rotates the secrets, allowing your application to update its database connection strings or API keys without a pod restart. This architecture separates the secret lifecycle management from the application code, keeping your C# logic clean and your deployment environment hardened against unauthorized access.
Key Takeaway: Leverage the Vault Agent sidecar to project secrets into a shared volume, allowing your .NET application to consume them via standard configuration providers without needing complex Vault-specific SDKs.