Mike
Mike

Reputation: 161

VSTS - best practices for web.config.token replacing

Looking for a walk-through for replacing config tokens at release time. I have tried several of the token replacing tasks / extensions out there but just can't get ANY of them working. I am new to VSTS so it may be that they expect some level of expertise or just know to do something between step x & y. I've tried

IIS Web App Deploy (out-of-the-box) only works for certain sections, and I have to tokenize actual web.config (would like to keep web.config non-tokenized for local debugging)

Azure App Service Deploy (out-of-the-box)

Tokenization by Total ALM

Replace Tokens by Colin's ALM Corner

Replace Tokens by Guillaume Rouchon

and the last 3 just won't work. Anyone have experience with these or know of a walk-through?

Upvotes: 1

Views: 1843

Answers (1)

Daniel Mann
Daniel Mann

Reputation: 59035

The last 3 work by injecting values from the variables section of your release definition, which frankly I just don't like period -- I prefer to keep application configuration as code (with the exception of passwords), driven from a source-controlled configuration file. I then do token replacement via PowerShell, as part of my deployment scripts for the application.

Here's a function I wrote and commonly use to perform token replacement. It works nicely if you put it in a PowerShell module, but is fine as a standalone function.

function Invoke-ReplaceTokens {
param(
[string]$FileSpec,
[string]$FilePath,
[HashTable]$Values)

    try {
        $files = gci -Path $FilePath -Filter $FileSpec -Recurse
        Write-Output "Found files:"

        Write-Output ($files | select-object -expandproperty FullName)
        $files | % {
            $contents = Get-Content $_.FullName -Raw
            $changedContents = $false
            foreach ($key in $Values.Keys) {
                if ($contents.Contains($key)) {
                    Write-Output "$($_.FullName) contains `"$key`". Replacing it with `"$($Values[$key])`""
                    $contents = $contents.Replace($key, $Values[$key])
                    $changedContents = $true
                }
            }
            if ($changedContents) {
                set-content -Path $_.FullName -Value $contents
            }
        }
    }
    catch {
        Write-Output $_
        throw $_
    }
}

Usage in a deployment script:

Invoke-ReplaceTokens -FileSpec '*.config' -FilePath 'C:\Location\Of\My\Config\File' -Values @{ '__Token__' = 'ActualValue' }

Also, the question as you asked it is off-topic for Stack Overflow (off-site resource recommendations are off-topic), so I answered the natural evolution of your initial question: "What is a good method for config file management during deployment?"

Upvotes: 1

Related Questions