LLI Wiki — My Digital Knowledge Base

Per-environment configuration for PowerShell scripts: JSON, Key Vault, App Configuration

config-env.json files, a Set-Parameters style loader, consistency checks across environments, secrets in Key Vault, and Azure App Configuration as an option.

The same PowerShell job runs against staging and production. The code must be identical; only the data differs: server names, subscription, identity, thresholds. The way you store and load that data decides whether an environment switch is a parameter or an incident. Here is the pattern I use, from simple JSON files to a central configuration service.

Files per environment

Each application has a config/ folder:

config/
├── config-common.json   # shared defaults
├── config-stg.json      # staging overrides
└── config-prd.json      # production overrides

Common holds what does not change between environments: retry counts, timeouts, feature switches. The environment files hold what does, grouped by feature:

{
  "sqlAdmin": {
    "server": "sql-contoso-prd.database.windows.net",
    "database": "AppDb"
  },
  "identity": { "name": "uami-dba-batch", "clientId": "00000000-0000-0000-0000-000000000000" },
  "keyVault": { "name": "kv-dba-contoso", "smtpSecretName": "smtp-api-key" }
}

The environment is a validated parameter of the entry script ([ValidateSet('stg','prd')]), so a typo can never load a wrong or empty config.

A loader in the Set-Parameters style

One function loads the config, always, and every script calls it. No script parses JSON by hand. It returns the usual result object so the caller can handle failure.

function Set-Parameters {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][ValidateSet('stg','prd')][string]$Env,
        [Parameter(Mandatory)][string]$ConfigFilePath
    )
    try {
        $merged = @{}
        foreach ($name in "config-common.json", "config-$Env.json") {
            $file = Join-Path $ConfigFilePath $name
            if (-not (Test-Path $file)) { throw "Missing $name" }
            $json = Get-Content $file -Raw | ConvertFrom-Json
            foreach ($p in $json.PSObject.Properties) { $merged[$p.Name] = $p.Value }
        }
        @{ IsValid = $true; Data = $merged; Reason = $null }
    }
    catch { @{ IsValid = $false; Data = $null; Reason = $_.Exception.Message } }
}

The environment file wins over common because it is merged last. Be aware of the shape this produces: the root is a hashtable (use $config['retryAttempts'] or ContainsKey) while nested groups are objects from ConvertFrom-Json (use dot notation, $config.sqlAdmin.server). Indexing a nested object with brackets throws, a classic surprise. The merge is shallow: an environment group replaces the common group entirely, which I prefer to a deep merge because it is predictable.

Detecting where it runs

The same job may run from an admin workstation, a pipeline agent or a batch node, each with its own identity. I keep one identity block per context in the config and detect the context from the environment (pipeline agents set TF_BUILD, Azure Batch nodes set AZ_BATCH_NODE_ID), with an explicit override parameter. Do not name the variable $ExecutionContext; it is a reserved automatic variable.

Checking consistency across environments

Two config files drift silently. A key added to production and forgotten in staging means your staging test proves nothing. I run a check, locally and in CI, that compares the files:

$stg = Get-Content config-stg.json -Raw | ConvertFrom-Json -AsHashtable
$prd = Get-Content config-prd.json -Raw | ConvertFrom-Json -AsHashtable
function Get-KeyPath($h, $prefix = '') {
    foreach ($k in $h.Keys) {
        $p = "$prefix$k"
        if ($h[$k] -is [hashtable]) { Get-KeyPath $h[$k] "$p." } else { $p }
    }
}
Compare-Object (Get-KeyPath $stg) (Get-KeyPath $prd) | Format-Table

Beyond keys, I check values that must agree: a subscription name that matches the server it is paired with, a secret name identical in both environments, no value that looks like a secret.

Secrets: Key Vault

Config files are committed to source control, so they never hold secrets. They hold the name of the secret, and the code fetches the value at run time with the job's managed identity:

$secret = Get-AzKeyVaultSecret -VaultName $config.keyVault.name `
          -Name $config.keyVault.smtpSecretName -AsPlainText -ErrorAction Stop

A review rule is worth adding: any file matching a known key prefix or a connection-string pattern in a config is a failed review. Never log the fetched value.

Azure App Configuration as an option

JSON files in the repo Azure App Configuration
Change a value Commit and deploy Change it in the service, no deploy
History and review Git Service snapshots and labels
Environments One file per environment Labels or one store per environment
Secrets Name only, Key Vault Key Vault references
Runs offline / in CI Yes Needs access to the store
Complexity Minimal An extra resource and an extra permission
flowchart LR
    A["Entry script"] --> L["Set-Parameters loader"]
    L --> C["config-common.json"]
    L --> E["config-env.json"]
    L -. option .-> AC["App Configuration"]
    A --> KV["Key Vault"]
    A --> ID["Managed identity"]
    ID --> KV

For a handful of scheduled jobs I stay with files: they are versioned with the code, reviewed in the same pull request, and testable offline. App Configuration becomes attractive when non-developers must change values without a release, or when many applications share the same settings. If you adopt it, keep the loader's contract: the callers should not notice where the values come from.

Lessons learned

Mastodon LLIMastodon SocialFosstodon