Configuration - Encrypt App or Web Config Section

Octopus.Script exported 2017-09-19 by KevinKelchen belongs to ‘Encrypt’ category.

Encrypts a configuration section for the specified executable.

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

Executable path

ExecutablePath

For Web: The virtual path to the web site.

For Windows: The path to the executable that has a corresponding [Executable].exe.config file.

You can get the InstallationDirectoryPath like so #{Octopus.Action[StepName].Output.Package.InstallationDirectoryPath}

Section to encrypt

SectionToEncrypt

The name of the section(s) in the config to encrypt e.g. appSettings, connectionStrings etc.

Separate multiple sections with comma ’,’.

Provider Name

Provider

The provider to use for encryption

Application Type

ApplicationType = Web

The application type would be web or windows. Web will be used to encrypt web.config file. And Windows type application will encrypt file with “exe.config” or “dll.config” extension.

Web Site Name

WebSiteName

Enter the web site name installed in IIS.

Script body

Steps based on this template will execute the following PowerShell script.

$ErrorActionPreference = "Stop" 
function Get-Parameter($Name, $Default, [switch]$Required) {
    $result = $null

    if ($OctopusParameters -ne $null) {
        $result = $OctopusParameters[$Name]
    }

    if ($result -eq $null) {
        if ($Required) {
            throw "Missing parameter value $Name"
        } else {
            $result = $Default
        }
    }

    Write-Verbose "Get-Parameter for '$($Name)' [value='$($result)' default='$($Default)']"

    return $result
}

function HandleError($message) {
	if (!$whatIf) {
		throw $message
	} else {
		Write-Host $message -Foreground Yellow
	}
}

function Invoke-EncryptAppConfigFile() {

    if (!(Test-Path $appPath)) {
        HandleError "The directory $appPath must exist"
    }

    $configurationAssembly = "System.Configuration, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a"
    [void] [Reflection.Assembly]::Load($configurationAssembly)
    $configuration = [System.Configuration.ConfigurationManager]::OpenExeConfiguration($appPath)

    Invoke-ProtectSections $configuration
}

function Invoke-EncryptWebConfigFile() {
    Import-module WebAdministration

	$IISPath = "IIS:\Sites\$($webSiteName)$($appPath)\"

    if (Test-Path $IISPath) { 
        Write-Verbose "$webSiteName web site exists."

        $configurationAssembly = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        [void] [Reflection.Assembly]::Load($configurationAssembly)
        $configuration = [System.Web.Configuration.WebConfigurationManager]::OpenWebConfiguration($appPath, $webSiteName)

        Invoke-ProtectSections $configuration
    }
    else {
        HandleError "$webSiteName web site doesn't exists. Please check if the web site is installed."
    }    
}

function Invoke-ProtectSections($configuration) {

    $saveConfigFile = $false

    foreach ($sectionName in $sections) {
        $sectionName = $sectionName.Trim()      # compatible with Powershell 2.0 
        $section = $configuration.GetSection($sectionName)
        
        if ($section) {
            if (-not $section.SectionInformation.IsProtected)
            {
                Write-Verbose "Encrypting $($section.SectionInformation.SectionName) section."
                $section.SectionInformation.ProtectSection($provider);
                $section.SectionInformation.ForceSave = [System.Boolean]::True;
                $saveConfigFile = $true
            }
            else {
                Write-Host "Section $($section.SectionInformation.SectionName) is already protected."
            }
        }
        else {
            Write-Warning "Section $($sectionName) doesn't exists in the configuratoin file."
        }

    }       

    if ($saveConfigFile) {            
        $configuration.Save([System.Configuration.ConfigurationSaveMode]::Modified);
        Write-Host "Encryption completed successfully."
    }
    else {
        Write-Host "No section(s) in the configuration were encrypted."
    }
}

$appType = Get-Parameter "ApplicationType" -Required
if ($appType -eq "Web") {
    $appPath = Get-Parameter "ExecutablePath" "/"
    $webSiteName = Get-Parameter "WebSiteName"
}
else {
    $appPath = Get-Parameter "ExecutablePath" -Required
}
$sectionName = Get-Parameter "SectionToEncrypt" -Required
$sections = $sectionName.Split(',')         # adding .Trim() doesn't work on Powershell 2.0 or below
$provider = Get-Parameter "Provider" "DataProtectionConfigurationProvider"

Write-Host "Configuration - Encrypt config file"
Write-Host "Application Type: $appType"
Write-Host "Application Path: $appPath"
if ($appType -eq "Web") { Write-Host "Web Site Name: $webSiteName" }
Write-Host "Section to Encrypt: $sectionName"
Write-Host "Provider: $provider"

if ($appType -eq "Web") {
    Invoke-EncryptWebConfigFile
}
else {
    Invoke-EncryptAppConfigFile 
}

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "c79b5e6b-88ac-47d5-8678-99e8ab2a1cd9",
  "Name": "Configuration - Encrypt App or Web Config Section",
  "Description": "Encrypts a configuration section for the specified executable.",
  "Version": 17,
  "ExportedAt": "2017-09-19T22:33:58.801Z",
  "ActionType": "Octopus.Script",
  "Author": "KevinKelchen",
  "Parameters": [
    {
      "Id": "9ab1281d-cf2e-4248-a583-b08e9609c96d",
      "Name": "ExecutablePath",
      "Label": "Executable path",
      "HelpText": "For Web:\nThe virtual path to the web site.\n\nFor Windows:\nThe path to the executable that has a corresponding `[Executable].exe.config` file.\n \nYou can get the InstallationDirectoryPath like so `#{Octopus.Action[StepName].Output.Package.InstallationDirectoryPath}`",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "0cb4f8ec-5415-47e3-87f1-3e086cc1caa1",
      "Name": "SectionToEncrypt",
      "Label": "Section to encrypt",
      "HelpText": "The name of the section(s) in the config to encrypt e.g. appSettings, connectionStrings etc.\n\nSeparate multiple sections with comma ','.",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "a30203d3-53d1-450d-bbcd-92a6eb31e906",
      "Name": "Provider",
      "Label": "Provider Name",
      "HelpText": "The provider to use for encryption",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "9116d4b3-b033-416f-844c-2a351d3bbc09",
      "Name": "ApplicationType",
      "Label": "Application Type",
      "HelpText": "The application type would be web or windows.\nWeb will be used to encrypt web.config file.\nAnd Windows type application will encrypt file with \"exe.config\" or \"dll.config\" extension.",
      "DefaultValue": "Web",
      "DisplaySettings": {
        "Octopus.ControlType": "Select",
        "Octopus.SelectOptions": "Web|Web Application\nWindows|Windows Service/Console App/Class Library (Dll)"
      }
    },
    {
      "Id": "90a1578e-efa2-44e4-84c0-34b037882cc5",
      "Name": "WebSiteName",
      "Label": "Web Site Name",
      "HelpText": "Enter the web site name installed in IIS.",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptBody": "$ErrorActionPreference = \"Stop\" \nfunction Get-Parameter($Name, $Default, [switch]$Required) {\n    $result = $null\n\n    if ($OctopusParameters -ne $null) {\n        $result = $OctopusParameters[$Name]\n    }\n\n    if ($result -eq $null) {\n        if ($Required) {\n            throw \"Missing parameter value $Name\"\n        } else {\n            $result = $Default\n        }\n    }\n\n    Write-Verbose \"Get-Parameter for '$($Name)' [value='$($result)' default='$($Default)']\"\n\n    return $result\n}\n\nfunction HandleError($message) {\n\tif (!$whatIf) {\n\t\tthrow $message\n\t} else {\n\t\tWrite-Host $message -Foreground Yellow\n\t}\n}\n\nfunction Invoke-EncryptAppConfigFile() {\n\n    if (!(Test-Path $appPath)) {\n        HandleError \"The directory $appPath must exist\"\n    }\n\n    $configurationAssembly = \"System.Configuration, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a\"\n    [void] [Reflection.Assembly]::Load($configurationAssembly)\n    $configuration = [System.Configuration.ConfigurationManager]::OpenExeConfiguration($appPath)\n\n    Invoke-ProtectSections $configuration\n}\n\nfunction Invoke-EncryptWebConfigFile() {\n    Import-module WebAdministration\n\n\t$IISPath = \"IIS:\\Sites\\$($webSiteName)$($appPath)\\\"\n\n    if (Test-Path $IISPath) { \n        Write-Verbose \"$webSiteName web site exists.\"\n\n        $configurationAssembly = \"System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\n        [void] [Reflection.Assembly]::Load($configurationAssembly)\n        $configuration = [System.Web.Configuration.WebConfigurationManager]::OpenWebConfiguration($appPath, $webSiteName)\n\n        Invoke-ProtectSections $configuration\n    }\n    else {\n        HandleError \"$webSiteName web site doesn't exists. Please check if the web site is installed.\"\n    }    \n}\n\nfunction Invoke-ProtectSections($configuration) {\n\n    $saveConfigFile = $false\n\n    foreach ($sectionName in $sections) {\n        $sectionName = $sectionName.Trim()      # compatible with Powershell 2.0 \n        $section = $configuration.GetSection($sectionName)\n        \n        if ($section) {\n            if (-not $section.SectionInformation.IsProtected)\n            {\n                Write-Verbose \"Encrypting $($section.SectionInformation.SectionName) section.\"\n                $section.SectionInformation.ProtectSection($provider);\n                $section.SectionInformation.ForceSave = [System.Boolean]::True;\n                $saveConfigFile = $true\n            }\n            else {\n                Write-Host \"Section $($section.SectionInformation.SectionName) is already protected.\"\n            }\n        }\n        else {\n            Write-Warning \"Section $($sectionName) doesn't exists in the configuratoin file.\"\n        }\n\n    }       \n\n    if ($saveConfigFile) {            \n        $configuration.Save([System.Configuration.ConfigurationSaveMode]::Modified);\n        Write-Host \"Encryption completed successfully.\"\n    }\n    else {\n        Write-Host \"No section(s) in the configuration were encrypted.\"\n    }\n}\n\n$appType = Get-Parameter \"ApplicationType\" -Required\nif ($appType -eq \"Web\") {\n    $appPath = Get-Parameter \"ExecutablePath\" \"/\"\n    $webSiteName = Get-Parameter \"WebSiteName\"\n}\nelse {\n    $appPath = Get-Parameter \"ExecutablePath\" -Required\n}\n$sectionName = Get-Parameter \"SectionToEncrypt\" -Required\n$sections = $sectionName.Split(',')         # adding .Trim() doesn't work on Powershell 2.0 or below\n$provider = Get-Parameter \"Provider\" \"DataProtectionConfigurationProvider\"\n\nWrite-Host \"Configuration - Encrypt config file\"\nWrite-Host \"Application Type: $appType\"\nWrite-Host \"Application Path: $appPath\"\nif ($appType -eq \"Web\") { Write-Host \"Web Site Name: $webSiteName\" }\nWrite-Host \"Section to Encrypt: $sectionName\"\nWrite-Host \"Provider: $provider\"\n\nif ($appType -eq \"Web\") {\n    Invoke-EncryptWebConfigFile\n}\nelse {\n    Invoke-EncryptAppConfigFile \n}",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptSource": "Inline",
    "Octopus.Action.RunOnServer": "false",
    "Octopus.Action.Script.ScriptFileName": null,
    "Octopus.Action.Package.FeedId": null,
    "Octopus.Action.Package.PackageId": null
  },
  "Category": "Encrypt",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/configuration-encrypt-app-or-web-config-section.json",
  "Website": "/step-templates/c79b5e6b-88ac-47d5-8678-99e8ab2a1cd9",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAIAAAAiOjnJAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAB6NJREFUeNrsnd9vU2UYx/ejXW1lxVlMG+hMtsUFtoTOZBjKBSaacIUJGuKNCSReeaEXeqnX4p03+g/gpZhwxQ2GJXDBUGbcSDZgZCWhm2nDCq7Fdl076uNOXAiwruftOe37nn4+IcvYj6Z79znP8z3veXrWXavVugCcpoclAMQCxALEAkAsQCxALADEAsQCxAJALEAsQCwAxALEAsQCQCxALEAsAMQCTfGxBPl8vlgsWm9LpZJ8ZPud3ZfP59u7d6+84/f7w+FwMBgMhUKRSIRV7e7MV+mIRplMJpfLra2tVatVxx9fJItsEYvFEKsjfEqn06JUgwXJEcStaDQ6ODiIWF6jUqksLy+nUqlW+vRi0xTDRkdHpVcilheUun//vijlRr9TQ/qj6OX5HOZZsTRU6jm9EomEh6uXN8WSIDU/P6+nUs8yNDQk1UvOKBFLd4rF4tzcnJzumfKEJXtNTEx47+TRU2KZUqheJB6Pj4+Pe6l0eUQsSVSilJz6mfsjhMNhKV3yFrE0an8zMzP5fN70H8RLbdF4scSn69evm9j+dkLOFj2wm2q2WN6zavtsUSIXYmGVK3Fe2qK5z78Hq/RETkQWFxcRC6ucR8RKp9OI1bqdhdnZWc9bZWHWZq/ZGWt6etqltY5EIuFw2O/327pCLOVTXHdvtMvn8x0/fty4q4qGibW4hYMPGAwGY1s4Mm4gkolh0r+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