📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you externalise configuration and secrets for a .NET service running in the cloud? Compare environment variables, Azure App Configuration, Azure Key Vault and secrets mounted as files, explain how each reaches IConfiguration, and how you handle refresh and rotation.

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.

Intermediate Theory Intermediate azure-app-configuration azure-key-vault cloud-native configuration managed-identity secrets-management

🎯 Key points

  • Separate settings (non-secret, vary by environment) from secrets (credentials, keys)
  • Environment variables: simplest, Section__Key; fine for non-secrets, leak into dumps and inspect output
  • Azure App Configuration: central settings, labels per environment, feature flags, sentinel-key refresh
  • Key Vault: secrets via AddAzureKeyVault or Key Vault references in App Config, App Service and Container Apps
  • Mounted files: Kubernetes Secrets or the Secrets Store CSI driver read with AddKeyPerFile
  • Managed identity + DefaultAzureCredential (or a specific credential) instead of a secret to fetch secrets
  • IOptionsMonitor / IOptionsSnapshot for refresh; IOptions<T> never changes after start-up
  • Rotation: reload interval, two active versions, prefer identity-based access that needs no rotation

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 IConfiguration pipeline, 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__TimeoutSeconds to Orders: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 with AddAzureKeyVault using 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."


The options compared

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

Settings versus secrets

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

Refresh and rotation

  • IOptions<T> is a singleton computed once. Use IOptionsMonitor<T> (singletons) or IOptionsSnapshot<T> (per request) for anything that can change.
  • Rotate by keeping two valid versions: issue the new key, let every instance pick it up within the reload interval, then revoke the old one.
  • For secrets your code turns into clients (for example a ServiceBusClient built from a connection string), refreshing IConfiguration is not enough: the client holds the old value. Identity-based connections avoid the problem.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can choose the right home for settings versus secrets and knows how values reach IConfiguration and refresh.

Green flags

  • Separates settings from secrets and prefers managed identity over storing secrets
  • Knows the name mappings (__, --) and the key-per-file provider
  • Explains IOptions vs IOptionsMonitor and sentinel-key refresh
  • Has a rotation plan with overlapping versions

Red flags

  • Puts passwords in env vars or appsettings.json in the image
  • Uses a client secret to read Key Vault
  • Expects IOptions<T> to pick up changes

📚 Learn in depth

1. One pipeline, many sources

            +--------------------------+
            |  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.

2. Name mapping rules

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 --.

3. Azure App Configuration internals

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.

4. Key Vault references on the platform

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.

5. Mounted secrets on Kubernetes

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.

6. Bootstrapping without a secret

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.

7. Australian context

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.

Try it yourself

  1. Bind an options class, then override one value with an env var and another with a command-line argument; print the effective values.
  2. Create a Key Vault, add Orders--ApiKey, grant yourself Key Vault Secrets User and load it with AddAzureKeyVault and DefaultAzureCredential locally.
  3. Inject IOptions<T> and IOptionsMonitor<T> into one endpoint, change an App Configuration value and the sentinel, and see which one updates.
  4. Use AddKeyPerFile on a local folder, edit a file while the app runs and log IOptionsMonitor.OnChange.
  5. Run docker inspect on a container started with -e DB_PASSWORD=... and see why env vars are not a vault.

💻 Code

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

⚠ Common mistakes

  • Mistake: Storing a database password in a plain environment variable or a Kubernetes Secret with no encryption at rest. Why it is wrong: It leaks through 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.
  • Mistake: Injecting 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.
  • Mistake: Refreshing App Configuration on every request or every second. Why it is wrong: It costs requests and leads to throttling across many replicas. Instead: Use a sentinel key and a refresh interval of 30 seconds or more.
  • Mistake: Using a client secret to read Key Vault. Why it is wrong: You now have a secret that protects your secrets, and it needs rotating too. Instead: Use managed identity or workload identity federation.
  • Mistake: Mounting a single secret file into an existing directory with 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.
  • Mistake: Rotating a secret by replacing it in one step. Why it is wrong: Instances that have not reloaded fail until they restart. Instead: Keep two valid versions, roll out the new one, then revoke the old one.
  • Mistake: Using 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions moving settings into App Configuration and Key Vault Why: Checks they can run the migration in a real estate with rotation, start-up failures and feature flags.
    How to answer

    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.

  2. When: Candidate mentions managed identity Why: Checks they can wire DefaultAzureCredential, RBAC roles and SQL users end to end.
    How to answer

    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:

    • Key Vault: grant Key Vault Secrets User and use AddAzureKeyVault.
    • Blob Storage: grant Storage Blob Data Contributor and create BlobServiceClient with the credential.
    • Azure SQL: 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.

  3. When: Candidate mentions refreshing configuration Why: Checks they know the lifetimes and refresh behaviour of the options interfaces.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Key rotation took down half the replicas
Situation
An ASP.NET Core payments API on Azure Container Apps with [6] replicas read a third-party signing key from Key Vault through a Container Apps secret reference mapped to an environment variable. Security rotated the key as part of a quarterly policy.
Signals
Within minutes, about half of outbound calls to the payment provider returned 401. Application Insights showed failures only on older replicas; new replicas created by a scale-out succeeded.
Investigation
Grouped failures by `cloud_RoleInstance` in Application Insights and saw they matched replicas started before the rotation. Checked the Container Apps secret: it had already re-fetched the new version, but environment variables are read once at process start, so old processes still held the revoked key. Confirmed the provider had revoked the old key immediately.
Resolution
Immediate: restarted the revision so every replica picked up the new value, which cleared the errors. Long term: switched to the `AddAzureKeyVault` provider with a 5-minute `ReloadInterval` and `IOptionsMonitor`, and changed the rotation runbook to issue the new key, wait two reload intervals, then revoke the old one.
Prevention
Rotation runbook with an overlap window, an alert on 401 rate per downstream dependency, a Key Vault secret-expiry alert via Event Grid, and an integration test that changes a value in a test vault and asserts the app sees it.

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.

↩ Usually asked after

More in Cloud-Native Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me