Skip to content

Commit a491fb3

Browse files
Merge pull request #1531 from OctopusDeploy/update-sql-execute-script-files
Fixing bug in sql-execute-sql-files.json
2 parents 068b99b + 6873e18 commit a491fb3

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

step-templates/sql-execute-sql-files.json

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"Name": "SQL - Execute SQL Script Files",
44
"Description": "Executes SQL script file(s) against the specified database using the `SQLServer` Powershell Module. This template includes an `Authentication` selector and supports SQL Authentication, Windows Authentication, and Azure Managed Identity.\n\nNote: If the `SqlServer` PowerShell module is not present, the template will download a temporary copy to perform the task.",
55
"ActionType": "Octopus.Script",
6-
"Version": 5,
6+
"Version": 6,
77
"CommunityActionTemplateId": null,
88
"Packages": [
99
{
@@ -21,7 +21,7 @@
2121
}
2222
],
2323
"Properties": {
24-
"Octopus.Action.Script.ScriptBody": "\nfunction Get-ModuleInstalled {\n # Define parameters\n param(\n $PowerShellModuleName\n )\n\n # Check to see if the module is installed\n if ($null -ne (Get-Module -ListAvailable -Name $PowerShellModuleName)) {\n # It is installed\n return $true\n }\n else {\n # Module not installed\n return $false \n }\n}\n\nfunction Get-NugetPackageProviderNotInstalled {\n # See if the nuget package provider has been installed\n return ($null -eq (Get-PackageProvider -ListAvailable -Name Nuget -ErrorAction SilentlyContinue))\n}\n\nfunction Install-PowerShellModule {\n # Define parameters\n param(\n $PowerShellModuleName,\n $LocalModulesPath\n )\n \n # Set TLS order\n [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls12\n\n # Check to see if the package provider has been installed\n if ((Get-NugetPackageProviderNotInstalled) -ne $false) {\n # Display that we need the nuget package provider\n Write-Output \"Nuget package provider not found, installing ...\"\n \n # Install Nuget package provider\n Install-PackageProvider -Name Nuget -Force\n }\n\n # Save the module in the temporary location\n Save-Module -Name $PowerShellModuleName -Path $LocalModulesPath -Force\n}\n\n\nfunction Invoke-ExecuteSQLScript {\n\n [CmdletBinding()]\n param\n (\n [parameter(Mandatory = $true, Position = 0)]\n [ValidateNotNullOrEmpty()]\n [string]\n $serverInstance,\n\n [parameter(Mandatory = $true, Position = 1)]\n [ValidateNotNullOrEmpty()]\n [string]\n $dbName,\n\n [string]\n $Authentication,\n\n [string]\n $SQLScripts,\n\n [bool]\n $DisplaySqlServerOutput,\n \n [bool]\n $TrustServerCertificate\n )\n \n # Check to see if SqlServer module is installed\n if ((Get-ModuleInstalled -PowerShellModuleName \"SqlServer\") -ne $true) {\n # Display message\n Write-Output \"PowerShell module SqlServer not present, downloading temporary copy ...\"\n\n # Download and install temporary copy\n Install-PowerShellModule -PowerShellModuleName \"SqlServer\" -LocalModulesPath $LocalModules\n }\n\n # Display\n Write-Output \"Importing module SqlServer ...\"\n\n # Import the module\n Import-Module -Name \"SqlServer\"\n \n $ExtractedPackageLocation = $($OctopusParameters['Octopus.Action.Package[template.Package].ExtractedPath'])\n\n $matchingScripts = @()\n\n # 1. Locate matching scripts\n foreach ($SQLScript in $SQLScripts.Split(\"`n\", [System.StringSplitOptions]::RemoveEmptyEntries)) {\n try {\n \n Write-Verbose \"Searching for scripts matching '$($SQLScript)'\"\n $scripts = @()\n $parent = Split-Path -Path $SQLScript -Parent\n $leaf = Split-Path -Path $SQLScript -Leaf\n Write-Verbose \"Parent: '$parent', Leaf: '$leaf'\"\n if (-not [string]::IsNullOrWhiteSpace($parent)) {\n $path = Join-Path $ExtractedPackageLocation $parent\n if (Test-Path $path) {\n Write-Verbose \"Searching for items in '$path' matching '$leaf'\"\n $scripts += @(Get-ChildItem -Path $path -Filter $leaf)\n }\n else {\n Write-Warning \"Path '$path' not found. Please check the path exists, and is relative to the package contents.\"\n }\n }\n else {\n Write-Verbose \"Searching in root of package for '$leaf'\"\n $scripts += @(Get-ChildItem -Path $ExtractedPackageLocation -Filter $leaf)\n }\n \n Write-Output \"Found $($scripts.Count) SQL scripts matching input '$SQLScript'\"\n\n $matchingScripts += $scripts\n }\n catch {\n Write-Error $_.Exception\n }\n }\n \n # Create arguments hash table\n $sqlcmdArguments = @{}\n\n\t# Add bound parameters\n $sqlcmdArguments.Add(\"ServerInstance\", $serverInstance)\n $sqlcmdArguments.Add(\"Database\", $dbName)\n #$sqlcmdArguments.Add(\"Query\", $SQLScripts)\n \n if ($DisplaySqlServerOutput)\n {\n \t$sqlcmdArguments.Add(\"Verbose\")\n }\n \n if ($TrustServerCertificate)\n {\n \t$sqlcmdArguments.Add(\"TrustServerCertificate\", $TrustServerCertificate)\n }\n\n # Only execute if we have matching scripts\n if ($matchingScripts.Count -gt 0) {\n foreach ($script in $matchingScripts) {\n $sr = New-Object System.IO.StreamReader($script.FullName)\n $scriptContent = $sr.ReadToEnd()\n \n # Execute based on selected authentication method\n switch ($Authentication) {\n \"AzureADManaged\" {\n # Get login token\n Write-Verbose \"Authenticating with Azure Managed Identity ...\"\n \n $response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fdatabase.windows.net%2F' -Method GET -Headers @{Metadata = \"true\" } -UseBasicParsing\n $content = $response.Content | ConvertFrom-Json\n $AccessToken = $content.access_token\n \n $sqlcmdArguments.Add(\"AccessToken\", $AccessToken)\n\n break\n }\n \"SqlAuthentication\" {\n Write-Verbose \"Authentication with SQL Authentication ...\"\n $sqlcmdArguments.Add(\"Username\", $username)\n $sqlcmdArguments.Add(\"Password\", $password)\n\n break\n }\n \"WindowsIntegrated\" {\n Write-Verbose \"Authenticating with Windows Authentication ...\"\n break\n }\n }\n \n $sqlcmdArguments.Add(\"Query\", $scriptContent)\n \n # Invoke sql cmd\n Invoke-SqlCmd @sqlcmdArguments\n \n $sr.Close()\n\n Write-Verbose (\"Executed manual script - {0}\" -f $script.Name)\n }\n }\n}\n\n# Define PowerShell Modules path\n$LocalModules = (New-Item \"$PSScriptRoot\\Modules\" -ItemType Directory -Force).FullName\n$env:PSModulePath = \"$LocalModules$([System.IO.Path]::PathSeparator)$env:PSModulePath\"\n\nif (Test-Path Variable:OctopusParameters) {\n Write-Verbose \"Locating scripts from the literal entry of Octopus Parameter SQLScripts\"\n $ScriptsToExecute = $OctopusParameters[\"SQLScripts\"]\n $DisplaySqlServerOutput = $OctopusParameters[\"ExecuteSQL.DisplaySQLServerOutput\"] -ieq \"True\"\n $TemplateTrustServerCertificate = [System.Convert]::ToBoolean($OctopusParameters[\"ExecuteSQL.TrustServerCertificate\"])\n \n Invoke-ExecuteSQLScript -serverInstance $OctopusParameters[\"serverInstance\"] `\n -dbName $OctopusParameters[\"dbName\"] `\n -Authentication $OctopusParameters[\"Authentication\"] `\n -SQLScripts $ScriptsToExecute `\n -DisplaySqlServerOutput $DisplaySqlServerOutput `\n -TrustServerCertificate $TemplateTrustServerCertificate\n}",
24+
"Octopus.Action.Script.ScriptBody": "\nfunction Get-ModuleInstalled {\n # Define parameters\n param(\n $PowerShellModuleName\n )\n\n # Check to see if the module is installed\n if ($null -ne (Get-Module -ListAvailable -Name $PowerShellModuleName)) {\n # It is installed\n return $true\n }\n else {\n # Module not installed\n return $false \n }\n}\n\nfunction Get-NugetPackageProviderNotInstalled {\n # See if the nuget package provider has been installed\n return ($null -eq (Get-PackageProvider -ListAvailable -Name Nuget -ErrorAction SilentlyContinue))\n}\n\nfunction Install-PowerShellModule {\n # Define parameters\n param(\n $PowerShellModuleName,\n $LocalModulesPath\n )\n \n # Set TLS order\n [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls12\n\n # Check to see if the package provider has been installed\n if ((Get-NugetPackageProviderNotInstalled) -ne $false) {\n # Display that we need the nuget package provider\n Write-Output \"Nuget package provider not found, installing ...\"\n \n # Install Nuget package provider\n Install-PackageProvider -Name Nuget -Force\n }\n\n # Save the module in the temporary location\n Save-Module -Name $PowerShellModuleName -Path $LocalModulesPath -Force\n}\n\n\nfunction Invoke-ExecuteSQLScript {\n\n [CmdletBinding()]\n param\n (\n [parameter(Mandatory = $true, Position = 0)]\n [ValidateNotNullOrEmpty()]\n [string]\n $serverInstance,\n\n [parameter(Mandatory = $true, Position = 1)]\n [ValidateNotNullOrEmpty()]\n [string]\n $dbName,\n\n [string]\n $Authentication,\n\n [string]\n $SQLScripts,\n\n [bool]\n $DisplaySqlServerOutput,\n \n [bool]\n $TrustServerCertificate\n )\n \n # Check to see if SqlServer module is installed\n if ((Get-ModuleInstalled -PowerShellModuleName \"SqlServer\") -ne $true) {\n # Display message\n Write-Output \"PowerShell module SqlServer not present, downloading temporary copy ...\"\n\n # Download and install temporary copy\n Install-PowerShellModule -PowerShellModuleName \"SqlServer\" -LocalModulesPath $LocalModules\n }\n\n # Display\n Write-Output \"Importing module SqlServer ...\"\n\n # Import the module\n Import-Module -Name \"SqlServer\"\n \n $ExtractedPackageLocation = $($OctopusParameters['Octopus.Action.Package[template.Package].ExtractedPath'])\n\n $matchingScripts = @()\n\n # 1. Locate matching scripts\n foreach ($SQLScript in $SQLScripts.Split(\"`n\", [System.StringSplitOptions]::RemoveEmptyEntries)) {\n try {\n \n Write-Verbose \"Searching for scripts matching '$($SQLScript)'\"\n $scripts = @()\n $parent = Split-Path -Path $SQLScript -Parent\n $leaf = Split-Path -Path $SQLScript -Leaf\n Write-Verbose \"Parent: '$parent', Leaf: '$leaf'\"\n if (-not [string]::IsNullOrWhiteSpace($parent)) {\n $path = Join-Path $ExtractedPackageLocation $parent\n if (Test-Path $path) {\n Write-Verbose \"Searching for items in '$path' matching '$leaf'\"\n $scripts += @(Get-ChildItem -Path $path -Filter $leaf)\n }\n else {\n Write-Warning \"Path '$path' not found. Please check the path exists, and is relative to the package contents.\"\n }\n }\n else {\n Write-Verbose \"Searching in root of package for '$leaf'\"\n $scripts += @(Get-ChildItem -Path $ExtractedPackageLocation -Filter $leaf)\n }\n \n Write-Output \"Found $($scripts.Count) SQL scripts matching input '$SQLScript'\"\n\n $matchingScripts += $scripts\n }\n catch {\n Write-Error $_.Exception\n }\n }\n \n # Create arguments hash table\n $sqlcmdArguments = @{}\n\n\t# Add bound parameters\n $sqlcmdArguments.Add(\"ServerInstance\", $serverInstance)\n $sqlcmdArguments.Add(\"Database\", $dbName)\n #$sqlcmdArguments.Add(\"Query\", $SQLScripts)\n \n if ($DisplaySqlServerOutput)\n {\n \tWrite-Host \"Adding Verbose to argument list to display output ...\"\n $sqlcmdArguments.Add(\"Verbose\", $DisplaySqlServerOutput)\n }\n \n if ($TrustServerCertificate)\n {\n \t$sqlcmdArguments.Add(\"TrustServerCertificate\", $TrustServerCertificate)\n }\n\n # Only execute if we have matching scripts\n if ($matchingScripts.Count -gt 0) {\n foreach ($script in $matchingScripts) {\n $sr = New-Object System.IO.StreamReader($script.FullName)\n $scriptContent = $sr.ReadToEnd()\n \n # Execute based on selected authentication method\n switch ($Authentication) {\n \"AzureADManaged\" {\n # Get login token\n Write-Verbose \"Authenticating with Azure Managed Identity ...\"\n \n $response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fdatabase.windows.net%2F' -Method GET -Headers @{Metadata = \"true\" } -UseBasicParsing\n $content = $response.Content | ConvertFrom-Json\n $AccessToken = $content.access_token\n \n $sqlcmdArguments.Add(\"AccessToken\", $AccessToken)\n\n break\n }\n \"SqlAuthentication\" {\n Write-Verbose \"Authentication with SQL Authentication ...\"\n $sqlcmdArguments.Add(\"Username\", $username)\n $sqlcmdArguments.Add(\"Password\", $password)\n\n break\n }\n \"WindowsIntegrated\" {\n Write-Verbose \"Authenticating with Windows Authentication ...\"\n break\n }\n }\n \n $sqlcmdArguments.Add(\"Query\", $scriptContent)\n \n # Invoke sql cmd\n Invoke-SqlCmd @sqlcmdArguments\n \n $sr.Close()\n\n Write-Verbose (\"Executed manual script - {0}\" -f $script.Name)\n }\n }\n}\n\n# Define PowerShell Modules path\n$LocalModules = (New-Item \"$PSScriptRoot\\Modules\" -ItemType Directory -Force).FullName\n$env:PSModulePath = \"$LocalModules$([System.IO.Path]::PathSeparator)$env:PSModulePath\"\n\nif (Test-Path Variable:OctopusParameters) {\n Write-Verbose \"Locating scripts from the literal entry of Octopus Parameter SQLScripts\"\n $ScriptsToExecute = $OctopusParameters[\"SQLScripts\"]\n $DisplaySqlServerOutput = $OctopusParameters[\"ExecuteSQL.DisplaySQLServerOutput\"] -ieq \"True\"\n $TemplateTrustServerCertificate = [System.Convert]::ToBoolean($OctopusParameters[\"ExecuteSQL.TrustServerCertificate\"])\n \n Invoke-ExecuteSQLScript -serverInstance $OctopusParameters[\"serverInstance\"] `\n -dbName $OctopusParameters[\"dbName\"] `\n -Authentication $OctopusParameters[\"Authentication\"] `\n -SQLScripts $ScriptsToExecute `\n -DisplaySqlServerOutput $DisplaySqlServerOutput `\n -TrustServerCertificate $TemplateTrustServerCertificate\n}",
2525
"Octopus.Action.Script.Syntax": "PowerShell",
2626
"Octopus.Action.Script.ScriptSource": "Inline",
2727
"Octopus.Action.RunOnServer": "false"
@@ -121,8 +121,8 @@
121121
],
122122
"StepPackageId": "Octopus.Script",
123123
"$Meta": {
124-
"ExportedAt": "2023-07-25T00:47:23.210Z",
125-
"OctopusVersion": "2023.3.6319-hotfix.6572",
124+
"ExportedAt": "2024-07-12T22:26:51.480Z",
125+
"OctopusVersion": "2024.2.9303",
126126
"Type": "ActionTemplate"
127127
},
128128
"LastModifiedBy": "twerthi",

0 commit comments

Comments
 (0)