SQL - Create Database If Not Exists Enhanced

Octopus.Script exported 2022-12-15 by harrisonmeister belongs to ‘SQL Server’ category.

Creates a database if the database does not exist without using SMO.

Parameters

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

SQL Server

createSqlServer =

The SQL Server to perform the work on

Authentication Method

createAuthenticationMethod =

Select the method for authentication to the SQL Server.

SQL Login

createSqlLoginUserWhoHasCreateUserRights =

The login of the user who has permissions to create a database.

Leave blank for integrated security

SQL Password

createSqlLoginPasswordWhoHasRights =

The password of the user who has permissions to create SQL Logins

Leave blank for integrated security

Database to create

createDatabaseName =

The name of the database to create

Command timeout

createCommandTimeout = 30

Number of seconds before throwing a timeout error.

Azure database edition

createAzureEdition =

Defines the database edition for Azure SQL Databases, leave blank if not using Azure.

Azure Backup Storage Redundacy

createAzureBackupStorageRedundancy =

Defines the Azure database backup storage redundancy. The default option is GRS when not specified. Leave blank if not using Azure.

Note: GZRS is only available in a subset of Azure regions that have the current requirements: 

  • Database cannot be a Basic edition.
  • Have a geo-paired region 
  • Have multiple availability zones within both data centers (primary and secondary). 

Script body

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

# Initialize variables
$connectionString = ""
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection

# Determine authentication method
switch ($createAuthenticationMethod)
{
	"AzureADManaged"
    {
    	Write-Host "Using Azure Managed Identity authentication ..."
        $connectionString = "Server=$createSqlServer;Database=master;"
        
        $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
        $content = $response.Content | ConvertFrom-Json
        $AccessToken = $content.access_token
        
        $sqlConnection.AccessToken = $AccessToken
        break
    }
    "SqlAuthentication"
    {
    	Write-Host "Using Sql account authentication ..."
        $connectionString = "Server=$createSqlServer;Database=master;User ID=$createSqlLoginUserWhoHasCreateUserRights;Password=$createSqlLoginPasswordWhoHasRights;"
        break
    }
    "WindowsIntegrated"
    {
    	Write-Host "Using Windows Integrated authentication ..."
        $connectionString = "Server=$createSqlServer;Database=master;integrated security=true;"
        break
    }
}


$sqlConnection.ConnectionString = $connectionString

$command = $sqlConnection.CreateCommand()
$command.CommandType = [System.Data.CommandType]'Text'
$command.CommandTimeout = $createCommandTimeout

Write-Host "Opening the connection to $createSqlServer"
$sqlConnection.Open()

$escapedDatabaseName = $createDatabaseName.Replace("'", "''")

Write-Host "Running the if not exists then create for $createDatabaseName"
$command.CommandText = "IF NOT EXISTS (select Name from sys.databases where Name = '$escapedDatabaseName')
        create database [$createDatabaseName]"
        
if (![string]::IsNullOrWhiteSpace($createAzureEdition))
{
	Write-Verbose "Specifying Azure SqlDb Edition: $($createAzureEdition)"
	$command.CommandText += ("`r`n (EDITION = '{0}')" -f $createAzureEdition)
}

if (![string]::IsNullOrWhiteSpace($createAzureBackupStorageRedundancy))
{
	Write-Verbose "Specifying Azure Backup storage redundancy: $($createAzureBackupStorageRedundancy)"
	$command.CommandText += ("`r`n WITH BACKUP_STORAGE_REDUNDANCY='{0}'" -f $createAzureBackupStorageRedundancy)
}

$command.CommandText += ";"

$command.ExecuteNonQuery()

Write-Host "Successfully created the account $createDatabaseName"
Write-Host "Closing the connection to $createSqlServer"
$sqlConnection.Close()

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": "ba43c3a7-fb77-4377-a1e2-e7918fb6df0b",
  "Name": "SQL - Create Database If Not Exists Enhanced",
  "Description": "Creates a database if the database does not exist without using SMO. ",
  "Version": 3,
  "ExportedAt": "2022-12-15T11:00:58.312Z",
  "ActionType": "Octopus.Script",
  "Author": "harrisonmeister",
  "Packages": [],
  "Parameters": [
    {
      "Id": "4a30febf-479b-4427-a382-04a84183e1ae",
      "Name": "createSqlServer",
      "Label": "SQL Server",
      "HelpText": "The SQL Server to perform the work on",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "9cfe1756-9e7d-4670-af75-1bb4a1899ce1",
      "Name": "createAuthenticationMethod",
      "Label": "Authentication Method",
      "HelpText": "Select the method for authentication to the SQL Server.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "Select",
        "Octopus.SelectOptions": "AzureADManaged|Azure Active Directory Managed Identity\nSqlAuthentication|SQL Authentication\nWindowsIntegrated|Windows Integrated"
      }
    },
    {
      "Id": "ba759a10-c230-4530-855a-2d7e210fe822",
      "Name": "createSqlLoginUserWhoHasCreateUserRights",
      "Label": "SQL Login",
      "HelpText": "The login of the user who has permissions to create a database.\n\nLeave blank for integrated security",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "0519fc45-e342-4982-beea-ab5123cad39b",
      "Name": "createSqlLoginPasswordWhoHasRights",
      "Label": "SQL Password",
      "HelpText": "The password of the user who has permissions to create SQL Logins\n\nLeave blank for integrated security",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "Sensitive"
      }
    },
    {
      "Id": "0662b998-acf3-425d-8fff-abd93a4a038d",
      "Name": "createDatabaseName",
      "Label": "Database to create",
      "HelpText": "The name of the database to create",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "4617d70a-fb52-4b1b-95f1-07929e47e7c0",
      "Name": "createCommandTimeout",
      "Label": "Command timeout",
      "HelpText": "Number of seconds before throwing a timeout error.",
      "DefaultValue": "30",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "7be71f0c-4df5-4f41-9b2f-3a29800a2e00",
      "Name": "createAzureEdition",
      "Label": "Azure database edition",
      "HelpText": "Defines the database edition for Azure SQL Databases, leave blank if not using Azure.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "Select",
        "Octopus.SelectOptions": "basic|Basic Edition\nstandard|Standard Edition\npremium|Premium Edition\ngeneralpurpose|General Purpose Edition\nbusinesscritical|Business Critical Edition\nhyperscale|Hyperscale Edition"
      }
    },
    {
      "Id": "85c8ad9c-2515-45d5-b521-49d3518f2a15",
      "Name": "createAzureBackupStorageRedundancy",
      "Label": "Azure Backup Storage Redundacy",
      "HelpText": "Defines the Azure [database backup storage redundancy](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-database-transact-sql?view=azuresqldb-current&tabs=sqlpool#backup_storage_redundancy). The default option is `GRS` when not specified. Leave blank if not using Azure.\n\nNote: `GZRS` is only available in a subset of Azure regions that have the current requirements: \n\n- Database cannot be a `Basic` edition.\n- Have a geo-paired region \n- Have multiple availability zones within both data centers (primary and secondary). ",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "Select",
        "Octopus.SelectOptions": "LOCAL|Locally redundant storage (LRS)\nZONE|Zone-redundant storage (ZRS)\nGEO|Geo-redundant storage (GRS)\nGEOZONE|Geo-Zone Redundant Storage (GZRS)"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptSource": "Inline",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptBody": "# Initialize variables\n$connectionString = \"\"\n$sqlConnection = New-Object System.Data.SqlClient.SqlConnection\n\n# Determine authentication method\nswitch ($createAuthenticationMethod)\n{\n\t\"AzureADManaged\"\n    {\n    \tWrite-Host \"Using Azure Managed Identity authentication ...\"\n        $connectionString = \"Server=$createSqlServer;Database=master;\"\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        $sqlConnection.AccessToken = $AccessToken\n        break\n    }\n    \"SqlAuthentication\"\n    {\n    \tWrite-Host \"Using Sql account authentication ...\"\n        $connectionString = \"Server=$createSqlServer;Database=master;User ID=$createSqlLoginUserWhoHasCreateUserRights;Password=$createSqlLoginPasswordWhoHasRights;\"\n        break\n    }\n    \"WindowsIntegrated\"\n    {\n    \tWrite-Host \"Using Windows Integrated authentication ...\"\n        $connectionString = \"Server=$createSqlServer;Database=master;integrated security=true;\"\n        break\n    }\n}\n\n\n$sqlConnection.ConnectionString = $connectionString\n\n$command = $sqlConnection.CreateCommand()\n$command.CommandType = [System.Data.CommandType]'Text'\n$command.CommandTimeout = $createCommandTimeout\n\nWrite-Host \"Opening the connection to $createSqlServer\"\n$sqlConnection.Open()\n\n$escapedDatabaseName = $createDatabaseName.Replace(\"'\", \"''\")\n\nWrite-Host \"Running the if not exists then create for $createDatabaseName\"\n$command.CommandText = \"IF NOT EXISTS (select Name from sys.databases where Name = '$escapedDatabaseName')\n        create database [$createDatabaseName]\"\n        \nif (![string]::IsNullOrWhiteSpace($createAzureEdition))\n{\n\tWrite-Verbose \"Specifying Azure SqlDb Edition: $($createAzureEdition)\"\n\t$command.CommandText += (\"`r`n (EDITION = '{0}')\" -f $createAzureEdition)\n}\n\nif (![string]::IsNullOrWhiteSpace($createAzureBackupStorageRedundancy))\n{\n\tWrite-Verbose \"Specifying Azure Backup storage redundancy: $($createAzureBackupStorageRedundancy)\"\n\t$command.CommandText += (\"`r`n WITH BACKUP_STORAGE_REDUNDANCY='{0}'\" -f $createAzureBackupStorageRedundancy)\n}\n\n$command.CommandText += \";\"\n\n$command.ExecuteNonQuery()\n\nWrite-Host \"Successfully created the account $createDatabaseName\"\nWrite-Host \"Closing the connection to $createSqlServer\"\n$sqlConnection.Close()"
  },
  "Category": "SQL Server",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/sql-create-database-enhanced.json",
  "Website": "/step-templates/ba43c3a7-fb77-4377-a1e2-e7918fb6df0b",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZ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4LKI5KCih8q+PH7QxVV0v36pHlX99WMLLaBfmi8D2I5ytOlZYY6ZtXv2rhOztWNghlp1gdvpxgr1ApnR9f/qaFb+0hRqFsh6tjMNmJIo+J9uWvI/nm9vQaUfIb3JQG0imXz2fRsHn5C2K+e2DArH1QsNhvGKuUR462OWhsr/Llbyf4yaEaGR2Yu83gsVaftLgMUtqN4b/hFR4/O69lk1iUsVTTG+VFofbbz+YN73776VFAH99dG1Iu7l09Uh1bdCdf/wqlXxyXHRML5sD/GBD/jpfx/fJsvOttu589vnXv2KhAIBgYQQNfNg//hBdyQcio+vCjxxpks1gLApmqj+rjox0/5G1BgteVfbaPhTjR6Okwl/kAFtl/9PcGyWqpPutEYFW1dM5CAARkcneJlDwLlVP+dVDhMNdHW8mP45TzriBZ7k+Xi4W9kbMS0v5JkDdeD8gD8oA8IA/IA/KAPCAPyAPygDwgD8gD8oA8IA/IA/IXr/8JMAAhf0RDrOWy2QAAAABJRU5ErkJggg==",
  "$Meta": {
    "Type": "ActionTemplate"
  }
}

History

Page updated on Thursday, December 15, 2022