Usare PowerShell per aggiungere un database a un gruppo di failoverUse PowerShell to add a database to a failover group

SI APPLICA A: Database SQL di Azure

Questo esempio di script di PowerShell crea un database singolo nel database SQL di Azure, crea un gruppo di failover, aggiunge il database al gruppo di failover e testa il failover.This PowerShell script example creates a single database in Azure SQL Database, creates a failover group, adds the database to it, and tests failover.

Se non si ha una sottoscrizione di Azure, creare un account gratuito prima di iniziare.If you don't have an Azure subscription, create a free account before you begin.

Nota

Questo articolo è stato aggiornato per usare il nuovo modulo Az di Azure PowerShell.This article has been updated to use the new Azure PowerShell Az module. È comunque possibile usare il modulo AzureRM, che continuerà a ricevere correzioni di bug almeno fino a dicembre 2020.You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. Per altre informazioni sul nuovo modulo Az e sulla compatibilità di AzureRM, vedere Introduzione del nuovo modulo Az di Azure PowerShell.To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. Per istruzioni sull'installazione del modulo Az, vedere Installare Azure PowerShell.For Az module installation instructions, see Install Azure PowerShell.

Usare Azure Cloud ShellUse Azure Cloud Shell

Azure Cloud Shell è un ambiente di shell interattivo ospitato in Azure e usato tramite il browser.Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. È possibile usare Bash o PowerShell con Cloud Shell per usare i servizi di Azure.You can use either Bash or PowerShell with Cloud Shell to work with Azure services. È possibile usare i comandi preinstallati di Cloud Shell per eseguire il codice contenuto in questo articolo senza dover installare strumenti nell'ambiente locale.You can use the Cloud Shell preinstalled commands to run the code in this article without having to install anything on your local environment.

Per avviare Azure Cloud Shell:To start Azure Cloud Shell:

OpzioneOption Esempio/CollegamentoExample/Link
Selezionare Prova nell'angolo superiore destro di un blocco di codice.Select Try It in the upper-right corner of a code block. La selezione di Prova non comporta la copia automatica del codice in Cloud Shell.Selecting Try It doesn't automatically copy the code to Cloud Shell. Esempio di Prova per Azure Cloud Shell
Passare a https://shell.azure.com o selezionare il pulsante Avvia Cloud Shell per aprire Cloud Shell nel browser.Go to https://shell.azure.com, or select the Launch Cloud Shell button to open Cloud Shell in your browser. Avviare Cloud Shell in una nuova finestraLaunch Cloud Shell in a new window
Selezionare il pulsante Cloud Shell nella barra dei menu nell'angolo in alto a destra del portale di Azure.Select the Cloud Shell button on the menu bar at the upper right in the Azure portal. Pulsante Cloud Shell nel portale di Azure

Per eseguire il codice di questo articolo in Azure Cloud Shell:To run the code in this article in Azure Cloud Shell:

  1. Avviare Cloud Shell.Start Cloud Shell.

  2. Selezionare il pulsante Copia in un blocco di codice per copiare il codice.Select the Copy button on a code block to copy the code.

  3. Incollare il codice nella sessione di Cloud Shell premendo CTRL+MAIUSC+V in Windows e Linux o CMD+MAIUSC+V in macOS.Paste the code into the Cloud Shell session by selecting Ctrl+Shift+V on Windows and Linux or by selecting Cmd+Shift+V on macOS.

  4. Premere INVIO per eseguire il codice.Select Enter to run the code.

Se si sceglie di installare e usare PowerShell in locale, per questa esercitazione è necessario Az PowerShell 1.4.0 o versione successiva.If you choose to install and use PowerShell locally, this tutorial requires Az PowerShell 1.4.0 or later. Se è necessario eseguire l'aggiornamento, vedere Installare e configurare Azure PowerShell.If you need to upgrade, see Install Azure PowerShell module. Se si esegue PowerShell in locale, è anche necessario eseguire Connect-AzAccount per creare una connessione con Azure.If you are running PowerShell locally, you also need to run Connect-AzAccount to create a connection with Azure.

Script di esempioSample scripts

# Set variables for your server and database
$subscriptionId = '<SubscriptionID>'
$randomIdentifier = $(Get-Random)
$resourceGroupName = "myResourceGroup-$randomIdentifier"
$location = "West US 2"
$adminLogin = "azureuser"
$password = "PWD27!"+(New-Guid).Guid
$serverName = "mysqlserver-$randomIdentifier"
$databaseName = "mySampleDatabase"
$drLocation = "East US 2"
$drServerName = "mysqlsecondary-$randomIdentifier"
$failoverGroupName = "failovergrouptutorial-$randomIdentifier"


# The ip address range that you want to allow to access your server 
# Leaving at 0.0.0.0 will prevent outside-of-azure connections
$startIp = "0.0.0.0"
$endIp = "0.0.0.0"

# Show randomized variables
Write-host "Resource group name is" $resourceGroupName 
Write-host "Password is" $password  
Write-host "Server name is" $serverName 
Write-host "DR Server name is" $drServerName 
Write-host "Failover group name is" $failoverGroupName

# Set subscription ID
Set-AzContext -SubscriptionId $subscriptionId

# Create a resource group
Write-host "Creating resource group..."
$resourceGroup = New-AzResourceGroup -Name $resourceGroupName -Location $location -Tag @{Owner="SQLDB-Samples"}
$resourceGroup


# Create a server with a system wide unique server name
Write-host "Creating primary logical server..."
$server = New-AzSqlServer -ResourceGroupName $resourceGroupName `
   -ServerName $serverName `
   -Location $location `
   -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential `
   -ArgumentList $adminLogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force))
$server

# Create a server firewall rule that allows access from the specified IP range
Write-host "Configuring firewall for primary logical server..."
$serverFirewallRule = New-AzSqlServerFirewallRule -ResourceGroupName $resourceGroupName `
   -ServerName $serverName `
   -FirewallRuleName "AllowedIPs" -StartIpAddress $startIp -EndIpAddress $endIp
$serverFirewallRule

# Create General Purpose Gen5 database with 2 vCore
Write-host "Creating a gen5 2 vCore database..."
$database = New-AzSqlDatabase  -ResourceGroupName $resourceGroupName `
   -ServerName $serverName `
   -DatabaseName $databaseName `
   -Edition GeneralPurpose `
   -VCore 2 `
   -ComputeGeneration Gen5 `
   -MinimumCapacity 2 `
   -SampleName "AdventureWorksLT"
$database

# Create a secondary server in the failover region
Write-host "Creating a secondary logical server in the failover region..."
$drServer = New-AzSqlServer -ResourceGroupName $resourceGroupName `
   -ServerName $drServerName `
   -Location $drLocation `
   -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential `
      -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force))
$drServer


# Create a failover group between the servers
$failovergroup = Write-host "Creating a failover group between the primary and secondary server..."
New-AzSqlDatabaseFailoverGroup `
   –ResourceGroupName $resourceGroupName `
   -ServerName $serverName `
   -PartnerServerName $drServerName  `
   –FailoverGroupName $failoverGroupName `
   –FailoverPolicy Automatic `
   -GracePeriodWithDataLossHours 2
$failovergroup

# Add the database to the failover group
Write-host "Adding the database to the failover group..." 
Get-AzSqlDatabase `
   -ResourceGroupName $resourceGroupName `
   -ServerName $serverName `
   -DatabaseName $databaseName | `
Add-AzSqlDatabaseToFailoverGroup `
   -ResourceGroupName $resourceGroupName `
   -ServerName $serverName `
   -FailoverGroupName $failoverGroupName
Write-host "Successfully added the database to the failover group..." 

# Check role of secondary replica
Write-host "Confirming the secondary replica is secondary...." 
(Get-AzSqlDatabaseFailoverGroup `
   -FailoverGroupName $failoverGroupName `
   -ResourceGroupName $resourceGroupName `
   -ServerName $drServerName).ReplicationRole

# Failover to secondary server
Write-host "Failing over failover group to the secondary..." 
Switch-AzSqlDatabaseFailoverGroup `
   -ResourceGroupName $resourceGroupName `
   -ServerName $drServerName `
   -FailoverGroupName $failoverGroupName
Write-host "Failed failover group successfully to" $drServerName 



# Revert failover to primary server
Write-host "Failing over failover group to the primary...." 
Switch-AzSqlDatabaseFailoverGroup `
   -ResourceGroupName $resourceGroupName `
   -ServerName $serverName `
   -FailoverGroupName $failoverGroupName
Write-host "Failed failover group successfully back to" $serverName


# Show randomized variables
Write-host "Resource group name is" $resourceGroupName 
Write-host "Password is" $password  
Write-host "Server name is" $serverName 
Write-host "DR Server name is" $drServerName 
Write-host "Failover group name is" $failoverGroupName

# Clean up resources by removing the resource group
# Write-host "Removing resource group..."
# Remove-AzResourceGroup -ResourceGroupName $resourceGroupName
# Write-host "Resource group removed =" $resourceGroupName

Pulire la distribuzioneClean up deployment

Usare il comando seguente per rimuovere il gruppo di risorse e tutte le risorse correlate.Use the following command to remove the resource group and all resources associated with it.

Remove-AzResourceGroup -ResourceGroupName $resourceGroupName

Spiegazione dello scriptScript explanation

Questo script usa i comandi seguenti.This script uses the following commands. Ogni comando della tabella include collegamenti alla documentazione specifica del comando.Each command in the table links to command specific documentation.

ComandoCommand NoteNotes
New-AzResourceGroupNew-AzResourceGroup Consente di creare un gruppo di risorse in cui sono archiviate tutte le risorse.Creates a resource group in which all resources are stored.
New-AzSqlServerNew-AzSqlServer Crea un server.Creates a server.
New-AzSqlServerFirewallRuleNew-AzSqlServerFirewallRule Crea una regola del firewall a livello di server per un server.Creates a server-level firewall rule for a server.
New-AzSqlDatabaseNew-AzSqlDatabase Crea un nuovo database.Creates a new database.
New-AzSqlDatabaseFailoverGroupNew-AzSqlDatabaseFailoverGroup Crea un nuovo gruppo di failover.Creates a new failover group.
Get-AzSqlDatabaseGet-AzSqlDatabase Ottiene uno o più database.Gets one or more databases.
Add-AzSqlDatabaseToFailoverGroupAdd-AzSqlDatabaseToFailoverGroup Aggiunge uno o più database a un gruppo di failover.Adds one or more databases to a failover group.
Get-AzSqlDatabaseFailoverGroupGet-AzSqlDatabaseFailoverGroup Ottiene o elenca i gruppi di failover.Gets or lists failover groups.
Switch-AzSqlDatabaseFailoverGroupSwitch-AzSqlDatabaseFailoverGroup Esegue il failover di un gruppo di failover.Executes a failover of a failover group.
Remove-AzResourceGroupRemove-AzResourceGroup Rimuove un gruppo di risorseRemoves a resource group

Passaggi successiviNext steps

Per altre informazioni su Azure PowerShell, vedere la documentazione di Azure PowerShell.For more information on Azure PowerShell, see Azure PowerShell documentation.

Per altri esempi, vedere tra gli script di PowerShell per database SQL di Azure.Additional SQL Database PowerShell script samples can be found in the Azure SQL Database PowerShell scripts.