Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions step-templates/sql-execute-sql-files.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"Name": "SQL - Execute SQL Script Files",
"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.",
"ActionType": "Octopus.Script",
"Version": 6,
"Version": 7,
"CommunityActionTemplateId": null,
"Packages": [
{
Expand All @@ -21,7 +21,7 @@
}
],
"Properties": {
"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}",
"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 # 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 # 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 $cmdArguments = @{}\n $cmdArguments += $sqlcmdArguments\n \n $cmdArguments.Add(\"Query\", $scriptContent)\n \n # Invoke sql cmd\n Invoke-SqlCmd @cmdArguments\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}",
"Octopus.Action.Script.Syntax": "PowerShell",
"Octopus.Action.Script.ScriptSource": "Inline",
"Octopus.Action.RunOnServer": "false"
Expand Down Expand Up @@ -120,11 +120,11 @@
}
],
"StepPackageId": "Octopus.Script",
"$Meta": {
"ExportedAt": "2024-07-12T22:26:51.480Z",
"OctopusVersion": "2024.2.9303",
"Type": "ActionTemplate"
},
"$Meta": {
"ExportedAt": "2026-04-09T00:26:48.778Z",
"OctopusVersion": "2026.1.11319",
"Type": "ActionTemplate"
},
"LastModifiedBy": "twerthi",
"Category": "sql"
}
Loading