Covers externalised configuration for cloud-hosted .NET services: environment variables, Azure App Configuration, Key Vault (direct and via references), Kubernetes and Container Apps secrets mounted as files with the key-per-file provider, managed identity, refresh with IOptionsMonitor and secret rotation.
I split settings from secrets. Non-secret settings that vary by environment come from environment variables (Orders__TimeoutSeconds) or, when many services share them, Azure App Configuration with labels per environment and feature flags. Secrets live in Azure Key Vault and reach the app either through the AddAzureKeyVault configuration provider, through Key Vault references resolved by App Service, Container Apps or App Configuration, or as files mounted by Kubernetes or the Secrets Store CSI driver and read with AddKeyPerFile. The app authenticates with managed identity, so there is no bootstrap secret. All of them land in IConfiguration, so code just binds options.
The trade-off is refresh: IOptions<T> is fixed at start-up, so anything that rotates needs IOptionsMonitor<T> and a reload interval, or a restart.
"Externalised configuration means the container image contains no environment-specific values, and especially no secrets. Everything that changes between dev, test and production is supplied by the platform at run time. In .NET that is easy because every source plugs into the same
IConfigurationpipeline, and the code binds strongly typed options without caring where a value came from.I use four sources, each for a different job. Environment variables for simple, non-secret settings such as a log level or a downstream URL; ASP.NET Core maps
Orders__TimeoutSecondstoOrders:TimeoutSeconds. Azure App Configuration when ten services share settings or I need feature flags and changes without a redeploy; I use labels for environments and a sentinel key so a change triggers a refresh. Azure Key Vault for secrets: either the app loads them withAddAzureKeyVaultusing managed identity, or the platform resolves a Key Vault reference and hands the value to the app as an environment variable or secret. And on Kubernetes, mounted secret files through the Secrets Store CSI driver, read with the key-per-file provider, which can pick up rotated files without a restart.The mistake I see is treating an environment variable as a safe place for a database password. It ends up in
docker inspect, crash dumps and the portal. Better still is not having the secret at all: with managed identity to Azure SQL, Service Bus and Storage there is nothing to rotate."
| Source | Best for | How it reaches IConfiguration |
Refresh | Watch out for |
|---|---|---|---|---|
| Environment variables | Non-secret, per-environment settings | Built-in provider, __ separator |
Restart (new revision / pod) | Visible in dumps and inspect output |
| Azure App Configuration | Shared settings, feature flags | AddAzureAppConfiguration + UseAzureAppConfiguration middleware |
Sentinel key + refresh interval | Cost per request tier, throttling if refresh is too aggressive |
| Key Vault (provider) | Secrets the app loads itself | AddAzureKeyVault(uri, credential) |
ReloadInterval |
Start-up depends on Key Vault; throttling at scale |
| Key Vault references | Secrets the platform resolves | Arrive as env vars / secrets | Platform re-fetches (App Service, Container Apps) or App Config resolves | Rotation pick-up depends on the platform |
| Mounted files (K8s, CSI driver) | AKS, multi-cloud | AddKeyPerFile("/mnt/secrets", optional: true, reloadOnChange: true) |
File change notifications | Symlink updates; subPath mounts never update |
| Kind | Example | Where |
|---|---|---|
| Setting | Timeout, feature switch, downstream base URL | Env vars, App Configuration |
| Secret | Third-party API key, signing key, a password you cannot remove | Key Vault |
| No secret needed | Azure SQL, Storage, Service Bus, Key Vault itself | Managed identity, no value at all |
IOptions<T> is a singleton computed once. Use IOptionsMonitor<T> (singletons) or IOptionsSnapshot<T> (per request) for anything that can change.ServiceBusClient built from a connection string), refreshing IConfiguration is not enough: the client holds the old value. Identity-based connections avoid the problem.A team had 14 App Service apps, each with its own copy of 30 settings in portal app settings, and the same third-party key in five places. Moving shared settings to App Configuration with labels, secrets to Key Vault behind references and Azure SQL access to managed identity cut the secret count from 23 to 4, and the next key rotation took 10 minutes instead of a half-day change window.
Checks whether the candidate can choose the right home for settings versus secrets and knows how values reach IConfiguration and refresh.
Green flags
__, --) and the key-per-file providerIOptions vs IOptionsMonitor and sentinel-key refreshRed flags
appsettings.json in the imageIOptions<T> to pick up changes +--------------------------+
| IConfiguration (merged) | later sources win
+--------------------------+
^ ^ ^ ^
appsettings env vars App Configuration Key Vault / key-per-file
(image) (platform) (central) (secrets)
|
AddOptions<T>().BindConfiguration("Section")
|
IOptions<T> | IOptionsSnapshot<T> | IOptionsMonitor<T>
Every provider produces flat key/value pairs such as Orders:TimeoutSeconds. Binding turns them into typed objects. Because the code depends only on IOptions*, you can move a value from env vars to App Configuration without changing the service.
| Source | Raw name | Configuration key |
|---|---|---|
| Environment variable | Orders__TimeoutSeconds |
Orders:TimeoutSeconds |
| Key Vault secret | Orders--ApiKey |
Orders:ApiKey (the default KeyVaultSecretManager replaces --) |
| Key-per-file | file /mnt/secrets/Orders__ApiKey |
Orders:ApiKey |
| Connection string env var | ConnectionStrings__Sql |
ConnectionStrings:Sql |
Key Vault secret names allow only letters, digits and dashes, hence --.
The provider fetches key-values (filtered by key prefix and label) at start-up. With ConfigureRefresh you register a sentinel key; the middleware checks it at most once per refresh interval (30 seconds by default) and, if its ETag changed, reloads everything. That keeps request costs low and makes changes atomic: you edit several keys, then bump the sentinel. App Configuration can also store Key Vault references; the provider resolves them with the credential you give it, so the app never sees the vault URI in its own settings.
App Service and Azure Container Apps can store a secret as a reference to a Key Vault secret and resolve it using the app's managed identity. The value reaches the app as an environment variable (App Service) or a Container Apps secret mapped to an env var or volume. The platform re-fetches periodically, but your process only sees a new env var after a restart or new revision, which is why files or the provider are better for frequent rotation.
The Secrets Store CSI driver with the Azure Key Vault provider mounts each secret as a file. Kubelet updates mounted volumes atomically by swapping a ..data symlink, so reloadOnChange on AddKeyPerFile works for normal mounts. A subPath mount never updates, a common surprise. Kubernetes Secrets are only base64-encoded in etcd unless encryption at rest is enabled, so on AKS keep the source of truth in Key Vault.
The chicken-and-egg problem is "what secret do I use to read my secrets?" Managed identity solves it: the platform gives the workload an identity (system- or user-assigned, or workload identity federation on AKS), and DefaultAzureCredential or, better in production, ManagedIdentityCredential gets a token from the local identity endpoint. No credential is stored anywhere.
Under the Privacy Act 1988 and the Notifiable Data Breaches scheme, a leaked connection string to a database holding personal information can become a notifiable breach. The ACSC Essential Eight's "restrict administrative privileges" maps neatly to giving each service its own identity with least-privilege RBAC on the vault.
Orders--ApiKey, grant yourself Key Vault Secrets User and load it with AddAzureKeyVault and DefaultAzureCredential locally.IOptions<T> and IOptionsMonitor<T> into one endpoint, change an App Configuration value and the sentinel, and see which one updates.AddKeyPerFile on a local folder, edit a file while the app runs and log IOptionsMonitor.OnChange.docker inspect on a container started with -e DB_PASSWORD=... and see why env vars are not a vault.A service that reads settings from env vars and App Configuration, secrets from Key Vault (or mounted files on AKS), all with managed identity.
// Program.cs (.NET 10)
using Azure.Identity;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
// In production pin the identity; DefaultAzureCredential is convenient locally.
Azure.Core.TokenCredential credential = builder.Environment.IsDevelopment()
? new DefaultAzureCredential()
: new ManagedIdentityCredential(ManagedIdentityId.FromUserAssignedClientId(builder.Configuration["AZURE_CLIENT_ID"]!));
// Shared settings and feature flags, one label per environment.
if (builder.Configuration["AppConfig:Endpoint"] is { } appConfigEndpoint)
{
builder.Configuration.AddAzureAppConfiguration(o => o
.Connect(new Uri(appConfigEndpoint), credential)
.Select("Orders:*", labelFilter: builder.Environment.EnvironmentName)
.ConfigureKeyVault(kv => kv.SetCredential(credential)) // resolves Key Vault references
.ConfigureRefresh(r => r.Register("Orders:Sentinel", refreshAll: true)
.SetRefreshInterval(TimeSpan.FromMinutes(1))));
builder.Services.AddAzureAppConfiguration();
}
// Secrets mounted by the Secrets Store CSI driver on AKS (optional elsewhere).
builder.Configuration.AddKeyPerFile("/mnt/secrets", optional: true, reloadOnChange: true);
builder.Services.AddOptions<PaymentsOptions>()
.BindConfiguration(PaymentsOptions.Section)
.ValidateOnStart();
var app = builder.Build();
if (app.Configuration["AppConfig:Endpoint"] is not null) app.UseAzureAppConfiguration();
// IOptionsMonitor sees refreshed values; IOptions<T> would keep the start-up value forever.
app.MapGet("/payments/config", (IOptionsMonitor<PaymentsOptions> options) =>
Results.Ok(new { options.CurrentValue.BaseUrl, HasKey = options.CurrentValue.ApiKey.Length > 0 }));
app.Run();
public sealed record PaymentsOptions
{
public const string Section = "Payments";
public string BaseUrl { get; init; } = "";
public string ApiKey { get; init; } = ""; // from Key Vault secret Payments--ApiKey or file Payments__ApiKey
}
# Non-secret settings come from the platform as env vars
Payments__BaseUrl=https://api.example-payments.test
AppConfig__Endpoint=https://orders-config.azconfig.io
docker inspect, dumps, portal screens and etcd backups. Instead: Keep secrets in Key Vault and, where possible, use managed identity so there is no password.IOptions<T> and expecting refreshed values. Why it is wrong: IOptions<T> is computed once and never changes. Instead: Use IOptionsMonitor<T> or IOptionsSnapshot<T> for settings that refresh.subPath and expecting rotation to reach the app. Why it is wrong: Kubelet updates a volume by swapping the ..data symlink of the whole mount; a subPath mount binds the original file directly, so it keeps the old content until the pod restarts. A whole-volume mount at its own directory does receive updates (after the kubelet sync period, typically up to a minute or two). Instead: Mount the whole secret volume at a dedicated path such as /mnt/secrets and read it with AddKeyPerFile(..., reloadOnChange: true); if you must use subPath, plan a rolling restart after rotation.DefaultAzureCredential unchanged in production. Why it is wrong: It tries several credential types in turn, adding latency and surprises when one is unexpectedly present. Instead: Use ManagedIdentityCredential (or exclude unused credential types) in production.The senior move is reducing the number of secrets, not storing them more cleverly. Every Azure service that supports Entra ID authentication (SQL, Storage, Service Bus, Event Hubs, Key Vault, App Configuration, Redis) should be reached with managed identity; what remains in Key Vault is the handful of third-party keys you cannot avoid. That shrinks the blast radius of a leak, makes access auditable per workload identity (who read which secret, in Key Vault diagnostic logs), and maps directly to Essential Eight least-privilege expectations and to what an auditor asks under the Privacy Act. Then pick the delivery mechanism by how often a value changes.
Two availability details separate a senior answer. First, every configuration source you load at start-up is a start-up dependency: if Key Vault or App Configuration is throttled or unreachable, new replicas fail to start exactly when you are scaling out. Use one vault per application per environment (Key Vault throttles per vault), load secrets once with a reload interval measured in minutes rather than fetching per request, and consider App Configuration replicas in a second region (Australia Southeast for an Australia East deployment). Second, refresh is not free: with 50 replicas and a 1-second refresh you send 50 requests a second for no value; a sentinel key with a 30-60 second interval gives near-live changes at a tiny fraction of the cost.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Env vars | Few services, settings that change with a release | None | Secrets, or values that change without a deploy |
| App Configuration | Many services, feature flags, live changes | Another dependency, request quotas | One small service |
| Key Vault provider | App-owned secrets, need reload | Start-up dependency, throttling | You can use identity instead |
| Mounted files (CSI) | AKS, frequent rotation | Driver to operate | App Service / Container Apps (use references) |
Measure it with a secret inventory (count of secrets per service, age of each, last rotation), alert on secrets nearing expiry with Key Vault's Event Grid SecretNearExpiry event, and track start-up failures caused by configuration sources.
I'd inventory and classify every setting first: secrets, environment-specific values, shared values, and which must change live. Secrets go to Key Vault. Non-secret settings and feature flags go to Azure App Configuration with a label per environment, and secrets are referenced from there through Key Vault references. The app authenticates with its managed identity using least-privilege roles, and where possible secrets disappear entirely through passwordless Entra ID auth to SQL, Storage and Service Bus.
For refresh, use a sentinel key with a refresh interval and a secret refresh interval, and read live values through IOptionsMonitor. Rotation uses overlapping versions, so old and new both work during the window. Add start-up timeouts and replicas, and keep ValidateOnStart.
The trade-off: central, audited, rotatable configuration, in exchange for a network dependency at start-up that you must design for.
Managed identity gives the app an Entra ID identity that Azure manages, so there is no secret to store or rotate. In code, Azure.Identity gets tokens: DefaultAzureCredential tries managed identity in Azure and the developer's az login or Visual Studio sign-in locally. Then:
AddAzureKeyVault.BlobServiceClient with the credential.CREATE USER [app-name] FROM EXTERNAL PROVIDER, add it to database roles, and use Authentication=Active Directory Default in the connection string.Use a user-assigned identity when several apps share access or it must survive redeploys. The trade-off is setup effort in RBAC and SQL users in exchange for no secrets at all.
IOptions<T> is registered as a singleton, bound once on first use, and never changes. IOptionsSnapshot<T> is registered as scoped: it binds once per DI scope, which in ASP.NET Core means once per HTTP request, so it sees reloaded configuration and gives a consistent value for the whole request, at the cost of a bind per scope. Injecting it into a singleton is a captive-dependency error (scope validation throws in Development); if a singleton needs it, create a scope with IServiceScopeFactory, or more simply use the monitor. IOptionsMonitor<T> is a singleton that returns the latest value via CurrentValue (cached until the source reloads) and raises OnChange. For run-time changes, use IOptionsMonitor<T> in singletons and background services, and IOptionsSnapshot<T> in request-scoped code that needs one consistent value per request.
How to tell it (STAR)
**S:** We ran a payments API on Container Apps with [6] replicas, and the provider's signing key came from Key Vault through an environment variable. **T:** After a scheduled rotation, half our payment calls started failing with 401 and I was on call. **A:** I split the failures by replica in Application Insights and saw only replicas started before the rotation were failing: env vars are read once, so they still held the revoked key. I restarted the revision to stop the bleeding, then moved the key to the Key Vault configuration provider with a reload interval and `IOptionsMonitor`, and rewrote the runbook so the old key stays valid until every instance has reloaded. **R:** The outage lasted [12] minutes, and the next [3] rotations caused zero failed payments.
Last updated 23 Nov 2026.