Skip to content

Instantly share code, notes, and snippets.

@eivindivine
Created December 3, 2020 12:33
Show Gist options
  • Save eivindivine/83cbfbf2efb97575ec7c1268459a05a0 to your computer and use it in GitHub Desktop.
Save eivindivine/83cbfbf2efb97575ec7c1268459a05a0 to your computer and use it in GitHub Desktop.
net-core-appsettings-json-variable-replacement-in-appveyor-deploy.ps1
Write-Host "Environment Variable Substitution"
$prefix = ${env:APPLICATION_PREFIX} + "*"
$props = gci env:$prefix | Select-Object -Property Name, Value
$configPath = "$env:APPLICATION_PATH\$env:CONFIG_FILE"
Write-Output "Loading config file from $configPath"
$appSettings = Get-Content -Raw $configPath | ConvertFrom-Json
foreach($variable in $props) {
$matchString = $variable.Name.replace(${env:APPLICATION_PREFIX}, "")
$matchProperties = $matchString.Split(".")
if($matchProperties.Count -gt 1) {
$match = $appSettings.($matchProperties[0]).psobject.properties | where { $_.Name -eq $matchProperties[1] }
if ($match) {
$appSettings.($matchProperties[0]).($matchProperties[1]) = $variable.Value
}
else {
Write-Output "Could not find match for $matchString"
}
}
else {
$match = $appSettings.psobject.properties | where { $_.Name -eq $matchString }
if ($match) {
$appSettings.($matchString) = $variable.Value
}
else {
Write-Output "Could not find match for $matchString"
}
}
}
$appSettings | ConvertTo-Json -depth 100 | Out-File $configPath
@eivindivine
Copy link
Author

eivindivine commented Dec 3, 2020

Script above is based on @mitchgollub's script (https://gist.github.com/mitchgollub/ebce195ab188c4f4b9f235229e7866e1) with minor changes to fit my AppVeyor deploy environment. Please look at the authors page for more info: https://mitchgollub.com/net-core-appsettings-json-variable-replacement-in-appveyor/

How to use it
Save script as deploy.ps1 in your netcore project folder.

In this example I have this appsettings.json and want to replace "DEV" with "TEST"
image

I need these settings in my AppVeyor deploy environment:
image

Changes made to the original script
1:
From the original script, I split the following line:
$variables = gci $env:$env:APPLICATION_PREFIX* | Select-Object -Property Key, Value

into two lines:
$prefix = ${env:APPLICATION_PREFIX} + "*"
$props = gci env:$prefix | Select-Object -Property Name, Value

2:
$variables seemed to be reserved in my case and I had to change the name. Therefor the variable is named $props

3:
The attribute Key didn't exist, and was replaced with Name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment