Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Apply Octopus Deploy variables to config files during deployment
<#
# Any variables in $OctopusParameters that use the following format will be used.
#
# {config file name w/o extension (aka BaseName)}:{xpath to node value to change}
#
# Examples:
#
# Given the configFilename = log4net.config
# And an Octopus variable named = log4net://configuration/log4net/appender[@name='FileAppender']/file/@value
# The value of the Octopus variable will be placed into the value of that node.
#
#>
function Set-ConfigurationVariables
{
param($configFilename)
Write-Host "Checking for Octopus Deploy deployment parameters..."
if (!$OctopusParameters)
{
Write-Host "No deployment parameters were provided from Octopus Deploy. Verify that Octopus Deploy is running this script or that you have specified $OctopusParameters from the executing environment."
Return
}
$configFile = Get-ChildItem $configFilename
if (!$configFile)
{
Write-Host "No configuration file was specified or found."
Return
}
Write-Host "Applying variables to $configFile.Fullname"
$configuration = [xml](Get-Content $configFile)
$variablesForThisConfig = $OctopusParameters.Keys | Where-Object {$_.StartsWith($configFile.BaseName + ":", "CurrentCultureIgnoreCase")}
if (!$variablesForThisConfig)
{
Write-Host "No variables for this config file were found."
Return
}
foreach ($variable in $variablesForThisConfig)
{
# Skip past the config file base name to get the xpath from the variable name.
$query = $variable.SubString(($configFile.BaseName + ":").Length)
Write-Host "Attempting to apply variable to $query"
$node = $configuration.SelectSingleNode($query)
if ($node)
{
Write-Host "Node located, applying value."
$node.Set_InnerText($OctopusParameters[$variable])
}
else
{
Write-Host "Specified node could not be found."
}
}
$configuration.Save($configFile.Fullname)
Write-Host "Done applying variables to $configFile.Fullname"
}
function Invoke-ApplyConfigurationFilesVariables
{
dir *.config | ForEach-Object {
Set-ConfigurationVariables($_)
}
}
Write-Host Running
Invoke-ApplyConfigurationFilesVariables
Write-Host Done
$OctopusParameters = @{
"sample://configuration/someSection/theSubNode" = "Value from script"
}
<configuration>
<someSection>
<theSubNode>OriginalValue</theSubNode>
</someSection>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment