Usar o PowerShell para adicionar uma instância gerenciada a um grupo de failover
Aplica-se a:Instância Gerenciada SQL do Azure
Este exemplo de script do PowerShell cria duas instâncias gerenciadas, adiciona-as a um grupo de failover e testa o failover da instância gerenciada primária para a instância gerenciada secundária.
Se não tiver uma subscrição do Azure, crie uma conta gratuita do Azure antes de começar.
Nota
Este artigo usa o módulo Azure Az PowerShell, que é o módulo PowerShell recomendado para interagir com o Azure. Para começar a utilizar o módulo Azure PowerShell, veja Instalar o Azure PowerShell. Para saber como migrar para o módulo do Az PowerShell, veja Migrar o Azure PowerShell do AzureRM para o Az.
Utilizar o Azure Cloud Shell
O Azure aloja o Azure Cloud Shell, um ambiente de shell interativo que pode utilizar através do seu browser. Pode utilizar o Bash ou o PowerShell com o Cloud Shell para trabalhar com os serviços do Azure. Você pode usar os comandos pré-instalados do Cloud Shell para executar o código neste artigo, sem precisar instalar nada em seu ambiente local.
Para iniciar o Azure Cloud Shell:
Opção | Exemplo/Ligação |
---|---|
Selecione Experimentar no canto superior direito de um bloco de código. A seleção de Experimente não copia automaticamente o código para o Cloud Shell. | |
Aceda a https://shell.azure.com ou selecione o botão Iniciar Cloud Shell para abrir o Cloud Shell no browser. | |
Selecione o botão Cloud Shell na barra de menus, na parte direita do portal do Azure. |
Para executar o código neste artigo no Azure Cloud Shell:
Inicie o Cloud Shell.
Selecione o botão Copiar num bloco de código para copiar o código.
Cole o código na sessão do Cloud Shell selecionando Ctrl+Shift V no Windows e Linux ou selecionando Cmd+Shift++V no macOS.
Selecione Introduzir para executar o código.
Se você optar por instalar e usar o PowerShell localmente, este tutorial exigirá o Azure PowerShell 1.4.0 ou posterior. Se precisar de atualizar, veja Install Azure PowerShell module (Instalar o módulo do Azure PowerShell). Se você estiver executando o PowerShell localmente, também precisará executar Connect-AzAccount
para criar uma conexão com o Azure.
Definir suas variáveis
# The SubscriptionId in which to create these objects
$SubscriptionId = ''
# Create a random identifier to use as subscript for the different resource names
$randomIdentifier = $(Get-Random)
# Set the resource group name and location for SQL Managed Instance
$resourceGroupName = "myResourceGroup-$randomIdentifier"
$location = "eastus"
$drLocation = "southcentralus"
# Set the networking values for your primary managed instance
$primaryVNet = "primaryVNet-$randomIdentifier"
$primaryAddressPrefix = "10.0.0.0/16"
$primaryDefaultSubnet = "primaryDefaultSubnet-$randomIdentifier"
$primaryDefaultSubnetAddress = "10.0.0.0/24"
$primaryMiSubnetName = "primaryMISubnet-$randomIdentifier"
$primaryMiSubnetAddress = "10.0.0.0/24"
$primaryMiGwSubnetAddress = "10.0.255.0/27"
$primaryGWName = "primaryGateway-$randomIdentifier"
$primaryGWPublicIPAddress = $primaryGWName + "-ip"
$primaryGWIPConfig = $primaryGWName + "-ipc"
$primaryGWAsn = 61000
$primaryGWConnection = $primaryGWName + "-connection"
# Set the networking values for your secondary managed instance
$secondaryVNet = "secondaryVNet-$randomIdentifier"
$secondaryAddressPrefix = "10.128.0.0/16"
$secondaryDefaultSubnet = "secondaryDefaultSubnet-$randomIdentifier"
$secondaryDefaultSubnetAddress = "10.128.0.0/24"
$secondaryMiSubnetName = "secondaryMISubnet-$randomIdentifier"
$secondaryMiSubnetAddress = "10.128.0.0/24"
$secondaryMiGwSubnetAddress = "10.128.255.0/27"
$secondaryGWName = "secondaryGateway-$randomIdentifier"
$secondaryGWPublicIPAddress = $secondaryGWName + "-IP"
$secondaryGWIPConfig = $secondaryGWName + "-ipc"
$secondaryGWAsn = 62000
$secondaryGWConnection = $secondaryGWName + "-connection"
# Set the SQL Managed Instance name for the new managed instances
$primaryInstance = "primary-mi-$randomIdentifier"
$secondaryInstance = "secondary-mi-$randomIdentifier"
# Set the admin login and password for SQL Managed Instance
$secpasswd = "PWD27!"+(New-Guid).Guid | ConvertTo-SecureString -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("azureuser", $secpasswd)
# Set the SQL Managed Instance service tier, compute level, and license mode
$edition = "General Purpose"
$vCores = 8
$maxStorage = 256
$computeGeneration = "Gen5"
$license = "LicenseIncluded" #"BasePrice" or LicenseIncluded if you have don't have SQL Server license that can be used for AHB discount
# Set failover group details
$vpnSharedKey = "mi1mi2psk"
$failoverGroupName = "failovergroup-$randomIdentifier"
# Show randomized variables
Write-host "Resource group name is" $resourceGroupName
Write-host "Password is" $secpasswd
Write-host "Primary Virtual Network name is" $primaryVNet
Write-host "Primary default subnet name is" $primaryDefaultSubnet
Write-host "Primary SQL Managed Instance subnet name is" $primaryMiSubnetName
Write-host "Secondary Virtual Network name is" $secondaryVNet
Write-host "Secondary default subnet name is" $secondaryDefaultSubnet
Write-host "Secondary SQL Managed Instance subnet name is" $secondaryMiSubnetName
Write-host "Primary SQL Managed Instance name is" $primaryInstance
Write-host "Secondary SQL Managed Instance name is" $secondaryInstance
Write-host "Failover group name is" $failoverGroupName
Definir subscrição e criar grupo de recursos
# Suppress networking breaking changes warning (https://aka.ms/azps-changewarnings
Set-Item Env:\SuppressAzurePowerShellBreakingChangeWarnings "true"
# Set the subscription context
Set-AzContext -SubscriptionId $subscriptionId
# Create the resource group
Write-host "Creating resource group..."
$resourceGroup = New-AzResourceGroup -Name $resourceGroupName -Location $location -Tag @{Owner="SQLDB-Samples"}
$resourceGroup
Comando | Notas |
---|---|
1. Connect-AzAccount | Conecte-se ao Azure. |
2. Set-AzContext | Defina o contexto da assinatura. |
3. New-AzResourceGroup | Criar um grupo de recursos do Azure. |
Criar ambas as instâncias gerenciadas
Primeiro, crie a instância gerenciada primária:
# Configure the primary virtual network
Write-host "Creating primary virtual network..."
$primarySubnetDelegation = New-AzDelegation -Name "ManagedInstance" -ServiceName "Microsoft.Sql/managedInstances"
$primaryVirtualNetwork = New-AzVirtualNetwork `
-ResourceGroupName $resourceGroupName `
-Location $location `
-Name $primaryVNet `
-AddressPrefix $primaryAddressPrefix
Add-AzVirtualNetworkSubnetConfig `
-Name $primaryMiSubnetName `
-VirtualNetwork $primaryVirtualNetwork `
-AddressPrefix $PrimaryMiSubnetAddress `
-Delegation $primarySubnetDelegation `
| Set-AzVirtualNetwork
$primaryVirtualNetwork
Write-host "Primary virtual network created successfully."
# Configure the primary managed instance subnet
Write-host "Configuring primary MI subnet..."
$primaryVirtualNetwork = Get-AzVirtualNetwork -Name $primaryVNet -ResourceGroupName $resourceGroupName
$primaryMiSubnetConfig = Get-AzVirtualNetworkSubnetConfig `
-Name $primaryMiSubnetName `
-VirtualNetwork $primaryVirtualNetwork
$primaryMiSubnetConfig
Write-host "Primary MI subnet configured successfully."
# Configure the network security group management service
Write-host "Configuring primary MI network security group..."
$primaryMiSubnetConfigId = $primaryMiSubnetConfig.Id
$primaryNSGMiManagementService = New-AzNetworkSecurityGroup `
-Name 'primaryNSGMiManagementService' `
-ResourceGroupName $resourceGroupName `
-location $location
$primaryNSGMiManagementService
Write-host "Primary MI network security group configured successfully."
# Configure the route table management service
Write-host "Configuring primary MI route table management service..."
$primaryRouteTableMiManagementService = New-AzRouteTable `
-Name 'primaryRouteTableMiManagementService' `
-ResourceGroupName $resourceGroupName `
-location $location
$primaryRouteTableMiManagementService
Write-host "Primary MI route table management service configured successfully."
# Configure the primary network security group
Write-host "Configuring primary network security group..."
Set-AzVirtualNetworkSubnetConfig `
-VirtualNetwork $primaryVirtualNetwork `
-Name $primaryMiSubnetName `
-AddressPrefix $PrimaryMiSubnetAddress `
-NetworkSecurityGroup $primaryNSGMiManagementService `
-RouteTable $primaryRouteTableMiManagementService `
-Delegation $primarySubnetDelegation `
| Set-AzVirtualNetwork
Get-AzNetworkSecurityGroup `
-ResourceGroupName $resourceGroupName `
-Name "primaryNSGMiManagementService" `
| Add-AzNetworkSecurityRuleConfig `
-Priority 100 `
-Name "allow_management_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange 9000,9003,1438,1440,1452 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 200 `
-Name "allow_misubnet_inbound" `
-Access Allow `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix $PrimaryMiSubnetAddress `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 300 `
-Name "allow_health_probe_inbound" `
-Access Allow `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix AzureLoadBalancer `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1000 `
-Name "allow_tds_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 1433 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1100 `
-Name "allow_redirect_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 11000-11999 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1200 `
-Name "allow_geodr_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 5022 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 4096 `
-Name "deny_all_inbound" `
-Access Deny `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 100 `
-Name "allow_management_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange 80,443,12000 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 200 `
-Name "allow_misubnet_outbound" `
-Access Allow `
-Protocol * `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix $PrimaryMiSubnetAddress `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1100 `
-Name "allow_redirect_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 11000-11999 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1200 `
-Name "allow_geodr_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 5022 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 4096 `
-Name "deny_all_outbound" `
-Access Deny `
-Protocol * `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Set-AzNetworkSecurityGroup
Write-host "Primary network security group configured successfully."
# Configure the primary network route table
Write-host "Configuring primary network route table..."
Get-AzRouteTable `
-ResourceGroupName $resourceGroupName `
-Name "primaryRouteTableMiManagementService" `
| Add-AzRouteConfig `
-Name "primaryToMIManagementService" `
-AddressPrefix 0.0.0.0/0 `
-NextHopType Internet `
| Add-AzRouteConfig `
-Name "ToLocalClusterNode" `
-AddressPrefix $PrimaryMiSubnetAddress `
-NextHopType VnetLocal `
| Set-AzRouteTable
Write-host "Primary network route table configured successfully."
# Create the primary managed instance
Write-host "Creating primary SQL Managed Instance..."
Write-host "This will take some time, see https://learn.microsoft.com/azure/azure-sql/managed-instance/management-operations-overview for more information."
New-AzSqlInstance -Name $primaryInstance `
-ResourceGroupName $resourceGroupName `
-Location $location `
-SubnetId $primaryMiSubnetConfigId `
-AdministratorCredential $mycreds `
-StorageSizeInGB $maxStorage `
-VCore $vCores `
-Edition $edition `
-ComputeGeneration $computeGeneration `
-LicenseType $license
$primaryInstance
Write-host "Primary SQL Managed Instance created successfully."
Em seguida, crie a instância gerenciada secundária:
# Configure the secondary virtual network
Write-host "Configuring secondary virtual network..."
$secondarySubnetDelegation = New-AzDelegation -Name "ManagedInstance" -ServiceName "Microsoft.Sql/managedInstances"
$SecondaryVirtualNetwork = New-AzVirtualNetwork `
-ResourceGroupName $resourceGroupName `
-Location $drlocation `
-Name $secondaryVNet `
-AddressPrefix $secondaryAddressPrefix
Add-AzVirtualNetworkSubnetConfig `
-Name $secondaryMiSubnetName `
-VirtualNetwork $SecondaryVirtualNetwork `
-AddressPrefix $secondaryMiSubnetAddress `
-Delegation $secondarySubnetDelegation `
| Set-AzVirtualNetwork
$SecondaryVirtualNetwork
Write-host "Secondary virtual network configured successfully."
# Configure the secondary managed instance subnet
Write-host "Configuring secondary MI subnet..."
$SecondaryVirtualNetwork = Get-AzVirtualNetwork -Name $secondaryVNet `
-ResourceGroupName $resourceGroupName
$secondaryMiSubnetConfig = Get-AzVirtualNetworkSubnetConfig `
-Name $secondaryMiSubnetName `
-VirtualNetwork $SecondaryVirtualNetwork
$secondaryMiSubnetConfig
Write-host "Secondary MI subnet configured successfully."
# Configure the secondary network security group management service
Write-host "Configuring secondary network security group management service..."
$secondaryMiSubnetConfigId = $secondaryMiSubnetConfig.Id
$secondaryNSGMiManagementService = New-AzNetworkSecurityGroup `
-Name 'secondaryToMIManagementService' `
-ResourceGroupName $resourceGroupName `
-location $drlocation
$secondaryNSGMiManagementService
Write-host "Secondary network security group management service configured successfully."
# Configure the secondary route table MI management service
Write-host "Configuring secondary route table MI management service..."
$secondaryRouteTableMiManagementService = New-AzRouteTable `
-Name 'secondaryRouteTableMiManagementService' `
-ResourceGroupName $resourceGroupName `
-location $drlocation
$secondaryRouteTableMiManagementService
Write-host "Secondary route table MI management service configured successfully."
# Configure the secondary network security group
Write-host "Configuring secondary network security group..."
Set-AzVirtualNetworkSubnetConfig `
-VirtualNetwork $SecondaryVirtualNetwork `
-Name $secondaryMiSubnetName `
-AddressPrefix $secondaryMiSubnetAddress `
-NetworkSecurityGroup $secondaryNSGMiManagementService `
-RouteTable $secondaryRouteTableMiManagementService `
-Delegation $secondarySubnetDelegation `
| Set-AzVirtualNetwork
Get-AzNetworkSecurityGroup `
-ResourceGroupName $resourceGroupName `
-Name "secondaryToMIManagementService" `
| Add-AzNetworkSecurityRuleConfig `
-Priority 100 `
-Name "allow_management_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange 9000,9003,1438,1440,1452 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 200 `
-Name "allow_misubnet_inbound" `
-Access Allow `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix $secondaryMiSubnetAddress `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 300 `
-Name "allow_health_probe_inbound" `
-Access Allow `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix AzureLoadBalancer `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1000 `
-Name "allow_tds_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 1433 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1100 `
-Name "allow_redirect_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 11000-11999 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1200 `
-Name "allow_geodr_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 5022 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 4096 `
-Name "deny_all_inbound" `
-Access Deny `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 100 `
-Name "allow_management_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange 80,443,12000 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 200 `
-Name "allow_misubnet_outbound" `
-Access Allow `
-Protocol * `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix $secondaryMiSubnetAddress `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1100 `
-Name "allow_redirect_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 11000-11999 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1200 `
-Name "allow_geodr_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 5022 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 4096 `
-Name "deny_all_outbound" `
-Access Deny `
-Protocol * `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Set-AzNetworkSecurityGroup
Write-host "Secondary network security group configured successfully."
# Configure the secondary network route table
Write-host "Configuring secondary network route table..."
Get-AzRouteTable `
-ResourceGroupName $resourceGroupName `
-Name "secondaryRouteTableMiManagementService" `
| Add-AzRouteConfig `
-Name "secondaryToMIManagementService" `
-AddressPrefix 0.0.0.0/0 `
-NextHopType Internet `
| Add-AzRouteConfig `
-Name "ToLocalClusterNode" `
-AddressPrefix $secondaryMiSubnetAddress `
-NextHopType VnetLocal `
| Set-AzRouteTable
Write-host "Secondary network route table configured successfully."
# Create the secondary managed instance
$primaryManagedInstanceId = Get-AzSqlInstance -Name $primaryInstance -ResourceGroupName $resourceGroupName | Select-Object Id
Write-host "Creating secondary SQL Managed Instance..."
Write-host "This will take some time, see https://learn.microsoft.com/azure/azure-sql/managed-instance/management-operations-overview for more information."
New-AzSqlInstance -Name $secondaryInstance `
-ResourceGroupName $resourceGroupName `
-Location $drLocation `
-SubnetId $secondaryMiSubnetConfigId `
-AdministratorCredential $mycreds `
-StorageSizeInGB $maxStorage `
-VCore $vCores `
-Edition $edition `
-ComputeGeneration $computeGeneration `
-LicenseType $license `
-DnsZonePartner $primaryManagedInstanceId.Id
Write-host "Secondary SQL Managed Instance created successfully."
Comando | Notas |
---|---|
1. New-AzVirtualNetwork | Crie uma rede virtual. |
2. Add-AzVirtualNetworkSubnetConfig | Adicione uma configuração de sub-rede a uma rede virtual. |
3. Set-AzVirtualNetwork | Atualiza uma rede virtual. |
4. Get-AzVirtualNetwork | Obtenha uma rede virtual em um grupo de recursos. |
5. Get-AzVirtualNetworkSubnetConfig | Obtenha uma sub-rede em uma rede virtual. |
6. New-AzNetworkSecurityGroup | Criar um grupo de segurança de rede. |
7. New-AzRouteTable | Crie uma tabela de rotas. |
8. Set-AzVirtualNetworkSubnetConfig | Atualize uma configuração de sub-rede para uma rede virtual. |
9. Set-AzVirtualNetwork | Atualize uma rede virtual. |
10. Get-AzNetworkSecurityGroup | Obtenha um grupo de segurança de rede. |
11. Add-AzNetworkSecurityRuleConfig | Adicione uma configuração de regra de segurança de rede a um grupo de segurança de rede. |
12. Set-AzNetworkSecurityGroup | Atualizar um grupo de segurança de rede. |
13. Get-AzRouteTable | Obtém tabelas de rotas. |
14. Add-AzRouteConfig | Adicione uma rota a uma tabela de rotas. |
15. Set-AzRouteTable | Atualize uma tabela de rotas. |
16. New-AzSqlInstance | Crie uma instância gerenciada. Ao criar a instância secundária, certifique-se de fornecer o -DnsZonePartner para vincular a instância secundária à sua instância primária. |
Configurar emparelhamento de rede virtual
Configure o emparelhamento de rede virtual global entre as redes virtuais das instâncias gerenciadas primária e secundária:
# Create global virtual network peering
$primaryVirtualNetwork = Get-AzVirtualNetwork `
-Name $primaryVNet `
-ResourceGroupName $resourceGroupName
$secondaryVirtualNetwork = Get-AzVirtualNetwork `
-Name $secondaryVNet `
-ResourceGroupName $resourceGroupName
Write-host "Peering primary VNet to secondary VNet..."
Add-AzVirtualNetworkPeering `
-Name primaryVnet-secondaryVNet1 `
-VirtualNetwork $primaryVirtualNetwork `
-RemoteVirtualNetworkId $secondaryVirtualNetwork.Id
Write-host "Primary VNet peered to secondary VNet successfully."
Write-host "Peering secondary VNet to primary VNet..."
Add-AzVirtualNetworkPeering `
-Name secondaryVNet-primaryVNet `
-VirtualNetwork $secondaryVirtualNetwork `
-RemoteVirtualNetworkId $primaryVirtualNetwork.Id
Write-host "Secondary VNet peered to primary VNet successfully."
Write-host "Checking peering state on the primary virtual network..."
Get-AzVirtualNetworkPeering `
-ResourceGroupName $resourceGroupName `
-VirtualNetworkName $primaryVNet `
| Select PeeringState
Write-host "Checking peering state on the secondary virtual network..."
Get-AzVirtualNetworkPeering `
-ResourceGroupName $resourceGroupName `
-VirtualNetworkName $secondaryVNet `
| Select PeeringState
Comando | Notas |
---|---|
1. Get-AzVirtualNetwork | Obtém uma rede virtual num grupo de recursos. |
2. Add-AzVirtualNetworkPeering | Adiciona um emparelhamento a uma rede virtual. |
3. Get-AzVirtualNetworkPeering | Obtém um emparelhamento para uma rede virtual. |
Criar o grupo de failover
Crie o grupo de failover:
# Create failover group
Write-host "Creating the failover group..."
$failoverGroup = New-AzSqlDatabaseInstanceFailoverGroup -Name $failoverGroupName `
-Location $location -ResourceGroupName $resourceGroupName -PrimaryManagedInstanceName $primaryInstance `
-PartnerRegion $drLocation -PartnerManagedInstanceName $secondaryInstance `
-FailoverPolicy Manual -GracePeriodWithDataLossHours 1
$failoverGroup
Comando | Notas |
---|---|
New-AzSqlDatabaseInstanceFailoverGroup | Cria um novo grupo de failover da Instância Gerenciada SQL do Azure. |
Testar failover planejado
Teste o failover planejado fazendo failover na réplica secundária e, em seguida, fazendo failback.
Comando | Notas |
---|---|
1. Get-AzSqlDatabaseInstanceFailoverGroup | Obtém ou lista grupos de failover de Instância Gerenciada SQL. |
2. Switch-AzSqlDatabaseInstanceFailoverGroup | Executa um failover de um grupo de failover de Instância Gerenciada SQL. |
Verifique as funções de cada servidor
Use o comando Get-AzSqlDatabaseInstanceFailoverGroup para confirmar as funções de cada servidor:
# Verify the current primary role
Get-AzSqlDatabaseInstanceFailoverGroup -ResourceGroupName $resourceGroupName `
-Location $location -Name $failoverGroupName
Failover para o servidor secundário
Use o Switch-AzSqlDatabaseInstanceFailoverGroup para fazer failover para o servidor secundário.
# Failover the primary managed instance to the secondary role
Write-host "Failing primary over to the secondary location"
Get-AzSqlDatabaseInstanceFailoverGroup -ResourceGroupName $resourceGroupName `
-Location $drLocation -Name $failoverGroupName | Switch-AzSqlDatabaseInstanceFailoverGroup
Write-host "Successfully failed failover group to secondary location"
# Verify the current primary role
Get-AzSqlDatabaseInstanceFailoverGroup -ResourceGroupName $resourceGroupName `
-Location $drLocation -Name $failoverGroupName
Reverter o grupo de failover de volta para o servidor primário
Use o comando Switch-AzSqlDatabaseInstanceFailoverGroup para fazer failover no servidor primário.
# Fail primary managed instance back to primary role
Write-host "Failing primary back to primary role"
Get-AzSqlDatabaseInstanceFailoverGroup -ResourceGroupName $resourceGroupName `
-Location $location -Name $failoverGroupName | Switch-AzSqlDatabaseInstanceFailoverGroup
Write-host "Successfully failed failover group to primary location"
# Verify the current primary role
Get-AzSqlDatabaseInstanceFailoverGroup -ResourceGroupName $resourceGroupName `
-Location $location -Name $failoverGroupName
Limpar a implementação
Use o comando a seguir para remover o grupo de recursos e todos os recursos associados a ele. Você precisará remover o grupo de recursos duas vezes. Remover o grupo de recursos pela primeira vez removerá a instância gerenciada e os clusters virtuais, mas falhará com a mensagem Remove-AzResourceGroup : Long running operation failed with status 'Conflict'
de erro . Execute o comando Remove-AzResourceGroup uma segunda vez para remover quaisquer recursos residuais, bem como o grupo de recursos.
Remove-AzResourceGroup -ResourceGroupName $resourceGroupName
Script completo
O seguinte trecho é o script completo:
# Add SQL Managed Instance to a failover group
<#
Due to SQL Managed Instance deployment times, plan for a full day to complete the entire script.
You can monitor deployment progress in the activity log within the Azure portal.
For more information on deployment times, see https://learn.microsoft.com/azure/azure-sql/managed-instance/management-operations-overview.
Closing the session will result in an incomplete deployment. To continue progress, you will
need to determine what the random modifier is and manually replace the random variable with
the previously-assigned value.
#>
<#
=============================================================================================
The following sets all the parameters for the two SQL managed instances, and failover group.
============================================================================================
#>
# The SubscriptionId in which to create these objects
$SubscriptionId = ''
# Create a random identifier to use as subscript for the different resource names
$randomIdentifier = $(Get-Random)
# Set the resource group name and location for SQL Managed Instance
$resourceGroupName = "myResourceGroup-$randomIdentifier"
$location = "eastus"
$drLocation = "southcentralus"
# Set the networking values for your primary managed instance
$primaryVNet = "primaryVNet-$randomIdentifier"
$primaryAddressPrefix = "10.0.0.0/16"
$primaryDefaultSubnet = "primaryDefaultSubnet-$randomIdentifier"
$primaryDefaultSubnetAddress = "10.0.0.0/24"
$primaryMiSubnetName = "primaryMISubnet-$randomIdentifier"
$primaryMiSubnetAddress = "10.0.0.0/24"
$primaryMiGwSubnetAddress = "10.0.255.0/27"
$primaryGWName = "primaryGateway-$randomIdentifier"
$primaryGWPublicIPAddress = $primaryGWName + "-ip"
$primaryGWIPConfig = $primaryGWName + "-ipc"
$primaryGWAsn = 61000
$primaryGWConnection = $primaryGWName + "-connection"
# Set the networking values for your secondary managed instance
$secondaryVNet = "secondaryVNet-$randomIdentifier"
$secondaryAddressPrefix = "10.128.0.0/16"
$secondaryDefaultSubnet = "secondaryDefaultSubnet-$randomIdentifier"
$secondaryDefaultSubnetAddress = "10.128.0.0/24"
$secondaryMiSubnetName = "secondaryMISubnet-$randomIdentifier"
$secondaryMiSubnetAddress = "10.128.0.0/24"
$secondaryMiGwSubnetAddress = "10.128.255.0/27"
$secondaryGWName = "secondaryGateway-$randomIdentifier"
$secondaryGWPublicIPAddress = $secondaryGWName + "-IP"
$secondaryGWIPConfig = $secondaryGWName + "-ipc"
$secondaryGWAsn = 62000
$secondaryGWConnection = $secondaryGWName + "-connection"
# Set the SQL Managed Instance name for the new managed instances
$primaryInstance = "primary-mi-$randomIdentifier"
$secondaryInstance = "secondary-mi-$randomIdentifier"
# Set the admin login and password for SQL Managed Instance
$secpasswd = "PWD27!"+(New-Guid).Guid | ConvertTo-SecureString -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("azureuser", $secpasswd)
# Set the SQL Managed Instance service tier, compute level, and license mode
$edition = "General Purpose"
$vCores = 8
$maxStorage = 256
$computeGeneration = "Gen5"
$license = "LicenseIncluded" #"BasePrice" or LicenseIncluded if you have don't have SQL Server license that can be used for AHB discount
# Set failover group details
$vpnSharedKey = "mi1mi2psk"
$failoverGroupName = "failovergroup-$randomIdentifier"
# Show randomized variables
Write-host "Resource group name is" $resourceGroupName
Write-host "Password is" $secpasswd
Write-host "Primary Virtual Network name is" $primaryVNet
Write-host "Primary default subnet name is" $primaryDefaultSubnet
Write-host "Primary SQL Managed Instance subnet name is" $primaryMiSubnetName
Write-host "Secondary Virtual Network name is" $secondaryVNet
Write-host "Secondary default subnet name is" $secondaryDefaultSubnet
Write-host "Secondary SQL Managed Instance subnet name is" $secondaryMiSubnetName
Write-host "Primary SQL Managed Instance name is" $primaryInstance
Write-host "Secondary SQL Managed Instance name is" $secondaryInstance
Write-host "Failover group name is" $failoverGroupName
<#===========================================================================
The following sets your subscription context and creates the resource group
==========================================================================#>
# Suppress networking breaking changes warning (https://aka.ms/azps-changewarnings
Set-Item Env:\SuppressAzurePowerShellBreakingChangeWarnings "true"
# Set the subscription context
Set-AzContext -SubscriptionId $subscriptionId
# Create the resource group
Write-host "Creating resource group..."
$resourceGroup = New-AzResourceGroup -Name $resourceGroupName -Location $location -Tag @{Owner="SQLDB-Samples"}
$resourceGroup
<#===========================================================================
The following configures resources for the primary SQL Managed Instance
===========================================================================#>
# Configure the primary virtual network
Write-host "Creating primary virtual network..."
$primarySubnetDelegation = New-AzDelegation -Name "ManagedInstance" -ServiceName "Microsoft.Sql/managedInstances"
$primaryVirtualNetwork = New-AzVirtualNetwork `
-ResourceGroupName $resourceGroupName `
-Location $location `
-Name $primaryVNet `
-AddressPrefix $primaryAddressPrefix
Add-AzVirtualNetworkSubnetConfig `
-Name $primaryMiSubnetName `
-VirtualNetwork $primaryVirtualNetwork `
-AddressPrefix $PrimaryMiSubnetAddress `
-Delegation $primarySubnetDelegation `
| Set-AzVirtualNetwork
$primaryVirtualNetwork
Write-host "Primary virtual network created successfully."
# Configure the primary managed instance subnet
Write-host "Configuring primary MI subnet..."
$primaryVirtualNetwork = Get-AzVirtualNetwork -Name $primaryVNet -ResourceGroupName $resourceGroupName
$primaryMiSubnetConfig = Get-AzVirtualNetworkSubnetConfig `
-Name $primaryMiSubnetName `
-VirtualNetwork $primaryVirtualNetwork
$primaryMiSubnetConfig
Write-host "Primary MI subnet configured successfully."
# Configure the network security group management service
Write-host "Configuring primary MI network security group..."
$primaryMiSubnetConfigId = $primaryMiSubnetConfig.Id
$primaryNSGMiManagementService = New-AzNetworkSecurityGroup `
-Name 'primaryNSGMiManagementService' `
-ResourceGroupName $resourceGroupName `
-location $location
$primaryNSGMiManagementService
Write-host "Primary MI network security group configured successfully."
# Configure the route table management service
Write-host "Configuring primary MI route table management service..."
$primaryRouteTableMiManagementService = New-AzRouteTable `
-Name 'primaryRouteTableMiManagementService' `
-ResourceGroupName $resourceGroupName `
-location $location
$primaryRouteTableMiManagementService
Write-host "Primary MI route table management service configured successfully."
# Configure the primary network security group
Write-host "Configuring primary network security group..."
Set-AzVirtualNetworkSubnetConfig `
-VirtualNetwork $primaryVirtualNetwork `
-Name $primaryMiSubnetName `
-AddressPrefix $PrimaryMiSubnetAddress `
-NetworkSecurityGroup $primaryNSGMiManagementService `
-RouteTable $primaryRouteTableMiManagementService `
-Delegation $primarySubnetDelegation `
| Set-AzVirtualNetwork
Get-AzNetworkSecurityGroup `
-ResourceGroupName $resourceGroupName `
-Name "primaryNSGMiManagementService" `
| Add-AzNetworkSecurityRuleConfig `
-Priority 100 `
-Name "allow_management_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange 9000,9003,1438,1440,1452 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 200 `
-Name "allow_misubnet_inbound" `
-Access Allow `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix $PrimaryMiSubnetAddress `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 300 `
-Name "allow_health_probe_inbound" `
-Access Allow `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix AzureLoadBalancer `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1000 `
-Name "allow_tds_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 1433 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1100 `
-Name "allow_redirect_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 11000-11999 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1200 `
-Name "allow_geodr_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 5022 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 4096 `
-Name "deny_all_inbound" `
-Access Deny `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 100 `
-Name "allow_management_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange 80,443,12000 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 200 `
-Name "allow_misubnet_outbound" `
-Access Allow `
-Protocol * `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix $PrimaryMiSubnetAddress `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1100 `
-Name "allow_redirect_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 11000-11999 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1200 `
-Name "allow_geodr_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 5022 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 4096 `
-Name "deny_all_outbound" `
-Access Deny `
-Protocol * `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Set-AzNetworkSecurityGroup
Write-host "Primary network security group configured successfully."
# Configure the primary network route table
Write-host "Configuring primary network route table..."
Get-AzRouteTable `
-ResourceGroupName $resourceGroupName `
-Name "primaryRouteTableMiManagementService" `
| Add-AzRouteConfig `
-Name "primaryToMIManagementService" `
-AddressPrefix 0.0.0.0/0 `
-NextHopType Internet `
| Add-AzRouteConfig `
-Name "ToLocalClusterNode" `
-AddressPrefix $PrimaryMiSubnetAddress `
-NextHopType VnetLocal `
| Set-AzRouteTable
Write-host "Primary network route table configured successfully."
# Create the primary managed instance
Write-host "Creating primary SQL Managed Instance..."
Write-host "This will take some time, see https://learn.microsoft.com/azure/azure-sql/managed-instance/management-operations-overview for more information."
New-AzSqlInstance -Name $primaryInstance `
-ResourceGroupName $resourceGroupName `
-Location $location `
-SubnetId $primaryMiSubnetConfigId `
-AdministratorCredential $mycreds `
-StorageSizeInGB $maxStorage `
-VCore $vCores `
-Edition $edition `
-ComputeGeneration $computeGeneration `
-LicenseType $license
$primaryInstance
Write-host "Primary SQL Managed Instance created successfully."
<#===========================================================================
The following configures resources for the secondary SQL Managed Instance
===========================================================================#>
# Configure the secondary virtual network
Write-host "Configuring secondary virtual network..."
$secondarySubnetDelegation = New-AzDelegation -Name "ManagedInstance" -ServiceName "Microsoft.Sql/managedInstances"
$SecondaryVirtualNetwork = New-AzVirtualNetwork `
-ResourceGroupName $resourceGroupName `
-Location $drlocation `
-Name $secondaryVNet `
-AddressPrefix $secondaryAddressPrefix
Add-AzVirtualNetworkSubnetConfig `
-Name $secondaryMiSubnetName `
-VirtualNetwork $SecondaryVirtualNetwork `
-AddressPrefix $secondaryMiSubnetAddress `
-Delegation $secondarySubnetDelegation `
| Set-AzVirtualNetwork
$SecondaryVirtualNetwork
Write-host "Secondary virtual network configured successfully."
# Configure the secondary managed instance subnet
Write-host "Configuring secondary MI subnet..."
$SecondaryVirtualNetwork = Get-AzVirtualNetwork -Name $secondaryVNet `
-ResourceGroupName $resourceGroupName
$secondaryMiSubnetConfig = Get-AzVirtualNetworkSubnetConfig `
-Name $secondaryMiSubnetName `
-VirtualNetwork $SecondaryVirtualNetwork
$secondaryMiSubnetConfig
Write-host "Secondary MI subnet configured successfully."
# Configure the secondary network security group management service
Write-host "Configuring secondary network security group management service..."
$secondaryMiSubnetConfigId = $secondaryMiSubnetConfig.Id
$secondaryNSGMiManagementService = New-AzNetworkSecurityGroup `
-Name 'secondaryToMIManagementService' `
-ResourceGroupName $resourceGroupName `
-location $drlocation
$secondaryNSGMiManagementService
Write-host "Secondary network security group management service configured successfully."
# Configure the secondary route table MI management service
Write-host "Configuring secondary route table MI management service..."
$secondaryRouteTableMiManagementService = New-AzRouteTable `
-Name 'secondaryRouteTableMiManagementService' `
-ResourceGroupName $resourceGroupName `
-location $drlocation
$secondaryRouteTableMiManagementService
Write-host "Secondary route table MI management service configured successfully."
# Configure the secondary network security group
Write-host "Configuring secondary network security group..."
Set-AzVirtualNetworkSubnetConfig `
-VirtualNetwork $SecondaryVirtualNetwork `
-Name $secondaryMiSubnetName `
-AddressPrefix $secondaryMiSubnetAddress `
-NetworkSecurityGroup $secondaryNSGMiManagementService `
-RouteTable $secondaryRouteTableMiManagementService `
-Delegation $secondarySubnetDelegation `
| Set-AzVirtualNetwork
Get-AzNetworkSecurityGroup `
-ResourceGroupName $resourceGroupName `
-Name "secondaryToMIManagementService" `
| Add-AzNetworkSecurityRuleConfig `
-Priority 100 `
-Name "allow_management_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange 9000,9003,1438,1440,1452 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 200 `
-Name "allow_misubnet_inbound" `
-Access Allow `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix $secondaryMiSubnetAddress `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 300 `
-Name "allow_health_probe_inbound" `
-Access Allow `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix AzureLoadBalancer `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1000 `
-Name "allow_tds_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 1433 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1100 `
-Name "allow_redirect_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 11000-11999 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1200 `
-Name "allow_geodr_inbound" `
-Access Allow `
-Protocol Tcp `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 5022 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 4096 `
-Name "deny_all_inbound" `
-Access Deny `
-Protocol * `
-Direction Inbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 100 `
-Name "allow_management_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange 80,443,12000 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 200 `
-Name "allow_misubnet_outbound" `
-Access Allow `
-Protocol * `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix $secondaryMiSubnetAddress `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1100 `
-Name "allow_redirect_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 11000-11999 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 1200 `
-Name "allow_geodr_outbound" `
-Access Allow `
-Protocol Tcp `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix VirtualNetwork `
-DestinationPortRange 5022 `
-DestinationAddressPrefix * `
| Add-AzNetworkSecurityRuleConfig `
-Priority 4096 `
-Name "deny_all_outbound" `
-Access Deny `
-Protocol * `
-Direction Outbound `
-SourcePortRange * `
-SourceAddressPrefix * `
-DestinationPortRange * `
-DestinationAddressPrefix * `
| Set-AzNetworkSecurityGroup
Write-host "Secondary network security group configured successfully."
# Configure the secondary network route table
Write-host "Configuring secondary network route table..."
Get-AzRouteTable `
-ResourceGroupName $resourceGroupName `
-Name "secondaryRouteTableMiManagementService" `
| Add-AzRouteConfig `
-Name "secondaryToMIManagementService" `
-AddressPrefix 0.0.0.0/0 `
-NextHopType Internet `
| Add-AzRouteConfig `
-Name "ToLocalClusterNode" `
-AddressPrefix $secondaryMiSubnetAddress `
-NextHopType VnetLocal `
| Set-AzRouteTable
Write-host "Secondary network route table configured successfully."
# Create the secondary managed instance
$primaryManagedInstanceId = Get-AzSqlInstance -Name $primaryInstance -ResourceGroupName $resourceGroupName | Select-Object Id
Write-host "Creating secondary SQL Managed Instance..."
Write-host "This will take some time, see https://learn.microsoft.com/azure/azure-sql/managed-instance/management-operations-overview for more information."
New-AzSqlInstance -Name $secondaryInstance `
-ResourceGroupName $resourceGroupName `
-Location $drLocation `
-SubnetId $secondaryMiSubnetConfigId `
-AdministratorCredential $mycreds `
-StorageSizeInGB $maxStorage `
-VCore $vCores `
-Edition $edition `
-ComputeGeneration $computeGeneration `
-LicenseType $license `
-DnsZonePartner $primaryManagedInstanceId.Id
Write-host "Secondary SQL Managed Instance created successfully."
<#===========================================================================
The following configures the failover group
===========================================================================#>
# Create global virtual network peering
$primaryVirtualNetwork = Get-AzVirtualNetwork `
-Name $primaryVNet `
-ResourceGroupName $resourceGroupName
$secondaryVirtualNetwork = Get-AzVirtualNetwork `
-Name $secondaryVNet `
-ResourceGroupName $resourceGroupName
Write-host "Peering primary VNet to secondary VNet..."
Add-AzVirtualNetworkPeering `
-Name primaryVnet-secondaryVNet1 `
-VirtualNetwork $primaryVirtualNetwork `
-RemoteVirtualNetworkId $secondaryVirtualNetwork.Id
Write-host "Primary VNet peered to secondary VNet successfully."
Write-host "Peering secondary VNet to primary VNet..."
Add-AzVirtualNetworkPeering `
-Name secondaryVNet-primaryVNet `
-VirtualNetwork $secondaryVirtualNetwork `
-RemoteVirtualNetworkId $primaryVirtualNetwork.Id
Write-host "Secondary VNet peered to primary VNet successfully."
Write-host "Checking peering state on the primary virtual network..."
Get-AzVirtualNetworkPeering `
-ResourceGroupName $resourceGroupName `
-VirtualNetworkName $primaryVNet `
| Select PeeringState
Write-host "Checking peering state on the secondary virtual network..."
Get-AzVirtualNetworkPeering `
-ResourceGroupName $resourceGroupName `
-VirtualNetworkName $secondaryVNet `
| Select PeeringState
# Create failover group
Write-host "Creating the failover group..."
$failoverGroup = New-AzSqlDatabaseInstanceFailoverGroup -Name $failoverGroupName `
-Location $location -ResourceGroupName $resourceGroupName -PrimaryManagedInstanceName $primaryInstance `
-PartnerRegion $drLocation -PartnerManagedInstanceName $secondaryInstance `
-FailoverPolicy Manual -GracePeriodWithDataLossHours 1
$failoverGroup
# Verify the current primary role
Get-AzSqlDatabaseInstanceFailoverGroup -ResourceGroupName $resourceGroupName `
-Location $location -Name $failoverGroupName
# Failover the primary managed instance to the secondary role
Write-host "Failing primary over to the secondary location"
Get-AzSqlDatabaseInstanceFailoverGroup -ResourceGroupName $resourceGroupName `
-Location $drLocation -Name $failoverGroupName | Switch-AzSqlDatabaseInstanceFailoverGroup
Write-host "Successfully failed failover group to secondary location"
# Verify the current primary role
Get-AzSqlDatabaseInstanceFailoverGroup -ResourceGroupName $resourceGroupName `
-Location $drLocation -Name $failoverGroupName
# Fail primary managed instance back to primary role
Write-host "Failing primary back to primary role"
Get-AzSqlDatabaseInstanceFailoverGroup -ResourceGroupName $resourceGroupName `
-Location $location -Name $failoverGroupName | Switch-AzSqlDatabaseInstanceFailoverGroup
Write-host "Successfully failed failover group to primary location"
# Verify the current primary role
Get-AzSqlDatabaseInstanceFailoverGroup -ResourceGroupName $resourceGroupName `
-Location $location -Name $failoverGroupName
# Clean up deployment
<# You will need to remove the resource group twice. Removing the resource group the first time will remove the managed instance and virtual clusters but will then fail with the error message `Remove-AzResourceGroup : Long running operation failed with status 'Conflict'.`. Run the Remove-AzResourceGroup command a second time to remove any residual resources as well as the resource group. #>
# Remove-AzResourceGroup -ResourceGroupName $resourceGroupName
# Write-host "Removing managed instance and virtual cluster..."
# Remove-AzResourceGroup -ResourceGroupName $resourceGroupName
# Write-host "Removing residual resources and resource group..."
# Show randomized variables
Write-host "Resource group name is" $resourceGroupName
Write-host "Password is" $secpasswd
Write-host "Primary Virtual Network name is" $primaryVNet
Write-host "Primary default subnet name is" $primaryDefaultSubnet
Write-host "Primary managed instance subnet name is" $primaryMiSubnetName
Write-host "Secondary Virtual Network name is" $secondaryVNet
Write-host "Secondary default subnet name is" $secondaryDefaultSubnet
Write-host "Secondary managed instance subnet name is" $secondaryMiSubnetName
Write-host "Primary managed instance name is" $primaryInstance
Write-host "Secondary managed instance name is" $secondaryInstance
Write-host "Failover group name is" $failoverGroupName
Este script utiliza os seguintes comandos. Cada comando na tabela liga à documentação específica do comando.
Comando | Notas |
---|---|
New-AzResourceGroup | Cria um grupo de recursos do Azure. |
Novo-AzVirtualNetwork | Cria uma rede virtual. |
Add-AzVirtualNetworkSubnetConfig | Adiciona uma configuração de sub-rede a uma rede virtual. |
Get-AzVirtualNetwork | Obtém uma rede virtual num grupo de recursos. |
Get-AzVirtualNetworkSubnetConfig | Obtém uma sub-rede em uma rede virtual. |
New-AzNetworkSecurityGroup | Cria um grupo de segurança de rede. |
New-AzRouteTable | Cria uma tabela de rotas. |
Set-AzVirtualNetworkSubnetConfig | Atualiza uma configuração de sub-rede para uma rede virtual. |
Set-AzVirtualNetwork | Atualiza uma rede virtual. |
Get-AzNetworkSecurityGroup | Obtém um grupo de segurança de rede. |
Add-AzNetworkSecurityRuleConfig | Adiciona uma configuração de regra de segurança de rede a um grupo de segurança de rede. |
Set-AzNetworkSecurityGroup | Atualiza um grupo de segurança de rede. |
Add-AzRouteConfig | Adiciona uma rota a uma tabela de rotas. |
Set-AzRouteTable | Atualiza uma tabela de rotas. |
New-AzSqlInstance | Cria uma instância gerenciada. |
Get-AzSqlInstance | Retorna informações sobre a Instância Gerenciada SQL do Azure. |
New-AzPublicIpAddress | Cria um endereço IP público. |
New-AzVirtualNetworkGatewayIpConfig | Cria uma configuração IP para um gateway de rede virtual |
New-AzVirtualNetworkGateway | Cria um gateway de rede virtual |
New-AzVirtualNetworkGatewayConnection | Cria uma conexão entre os dois gateways de rede virtual. |
New-AzSqlDatabaseInstanceFailoverGroup | Cria um novo grupo de failover da Instância Gerenciada SQL do Azure. |
Get-AzSqlDatabaseInstanceFailoverGroup | Obtém ou lista grupos de failover de Instância Gerenciada SQL. |
Switch-AzSqlDatabaseInstanceFailoverGroup | Executa um failover de um grupo de failover de Instância Gerenciada SQL. |
Remove-AzResourceGroup | Remove um grupo de recursos. |
Próximos passos
Para obter mais informações sobre o Azure PowerShell, consulte a documentação do Azure PowerShell.
Exemplos de script adicionais do PowerShell para Instância Gerenciada SQL podem ser encontrados em scripts PowerShell da Instância Gerenciada SQL do Azure.