-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert-appsettingsjson-to-env.ps1
55 lines (43 loc) · 1.47 KB
/
convert-appsettingsjson-to-env.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<#
.SYNOPSIS
The script converts .NET appsettings.json configuration file to Environment variables format
.NOTES
dot (`.`) couldn't be used in config keys: https://github.com/dotnet/runtime/issues/35989
.EXAMPLE
./convert-appsettingsjson-to-env.ps1 -SourceFilePath 'appsettings.Development.json' -EnvKeyPrefix 'K8S_SECRET_' | Format-List
.LINK
JSON configuration provider: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/#jcp
.LINK
Environment variables: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/#evcp
#>
[CmdletBinding()]
param(
[parameter(Mandatory = $true)]
[string]$SourceFilePath,
[string]$EnvKeyPrefix = ''
)
$Root = Get-Content -Path $SourceFilePath |
ConvertFrom-Json -AsHashtable
function Get-EnvVars {
param (
[Hashtable]$Root,
[string]$RootKeyPrefix
)
$EnvKeys = @{}
foreach ($Key in $Root.Keys) {
$KeyPrefix = "$RootKeyPrefix$Key"
$Value = $Root[$Key]
if ($Value -is [Hashtable]) {
$EnvKeys += Get-EnvVars -Root $Value -RootKeyPrefix "${KeyPrefix}__"
} elseif ($Value -is [array]) {
for ($ArrayIndex = 0; $ArrayIndex -lt $Value.Count; $ArrayIndex++) {
$EnvKeys += Get-EnvVars -Root $Value[$ArrayIndex] -RootKeyPrefix "${KeyPrefix}__${ArrayIndex}__"
}
} else {
$EnvKeys += @{$KeyPrefix=$Value}
}
}
return $EnvKeys
}
$EnvVars = Get-EnvVars -Root $Root -RootKeyPrefix $EnvKeyPrefix
$EnvVars.GetEnumerator() | Sort-Object -Property key