We use a approach for ASP.NET Core applications hosted on IIS servers in which we use GitLab pipelines to set variables as environment variables stored in the web.config file:
variables:
PROJECT_FILE: 'sampleproject01.csproj'
PUBLISH_PATH: 'd:\output'
BUILD_TYPE: 'Debug'
stages:
- deploy
deploy-dev:
stage: deploy
only:
- dev
script:
- 'dotnet publish --output "$env:PUBLISH_PATH" -p:EnvironmentName=Development -c "$env:BUILD_TYPE" "$env:PROJECT_FILE"'
- '$filePath = "$env:PUBLISH_PATH\web.config"'
- '$xml = New-Object XML'
- '$xml = [xml](Get-Content $filePath)'
- '$base64decoded = [Text.Encoding]::Utf8.GetString([Convert]::FromBase64String("$env:Dev__ConnectionStrings__database"))'
- '$envVar = $xml.CreateElement("environmentVariable")'
- '$envVar.SetAttribute("name", "ConnectionStrings__database")'
- '$envVar.SetAttribute("value", $base64decoded)'
- '$xml.configuration.location."system.webServer".aspNetCore.environmentVariables.AppendChild($envVar) | Out-Null'
- '$xml.Save($filePath)'
Resulting web.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\sampleproject01.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
<environmentVariable name="ConnectionStrings__database" value="Server=XXXX;database=YYY;User Id=ZZZZ;Password=XXX;" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
The ConnectionStrings__database
environment variable will be used as value for:
"ConnectionStrings": {
"database": ""
}
Notes:
- Variable
Dev__ConnectionStrings__database
is stored as base64 in GitLab (because it complains about some characters if 'masked' is enable), so the script have to decode it.
- The GitLab runner used in this pipeline uses PowerShell.
- See documentation for using environment variables in application configuration.