PowerShell: tworzenie punktu końcowego usługi wirtualnej i reguły sieci wirtualnej dla usługi Azure SQL Database

Dotyczy:Azure SQL Database

Reguły sieci wirtualnej to jedna funkcja zabezpieczeń zapory, która kontroluje, czy logiczny serwer SQL dla baz danych usługi Azure SQL Database , pul elastycznych lub baz danych w usłudze Azure Synapse akceptuje komunikację wysyłaną z określonych podsieci w sieciach wirtualnych.

Ważne

Ten artykuł dotyczy usługi Azure SQL Database, w tym usługi Azure Synapse (dawniej SQL DW). Dla uproszczenia termin Azure SQL Database w tym artykule dotyczy baz danych należących do usługi Azure SQL Database lub Azure Synapse. Ten artykuł nie dotyczy usługi Azure SQL Managed Instance, ponieważ nie ma skojarzonego z nim punktu końcowego usługi.

W tym artykule przedstawiono skrypt programu PowerShell, który wykonuje następujące akcje:

  1. Tworzy punkt końcowy usługi wirtualnej platformy Microsoft Azure w podsieci.
  2. Dodaje punkt końcowy do zapory serwera, aby utworzyć regułę sieci wirtualnej.

Aby uzyskać więcej informacji, zobacz Punkty końcowe usługi wirtualnej dla usługi Azure SQL Database.

Napiwek

Jeśli wszystko, czego potrzebujesz, to ocenić lub dodać nazwę typu punktu końcowego usługi wirtualnej dla usługi Azure SQL Database do podsieci, możesz przejść do bardziej bezpośredniego skryptu programu PowerShell.

Uwaga

W tym artykule użyto modułu Azure Az programu PowerShell, który jest zalecanym modułem programu PowerShell do interakcji z platformą Azure. Aby rozpocząć pracę z modułem Azure PowerShell, zobacz Instalowanie programu Azure PowerShell. Aby dowiedzieć się, jak przeprowadzić migrację do modułu Az PowerShell, zobacz Migracja programu Azure PowerShell z modułu AzureRM do modułu Az.

Ważne

Moduł Azure Resource Manager programu PowerShell jest nadal obsługiwany przez usługę Azure SQL Database, ale wszystkie przyszłe programowanie jest przeznaczone dla Az.Sql poleceń cmdlet. Aby zapoznać się ze starszym modułem, zobacz AzureRM.Sql. Argumenty poleceń w module Az i modułach AzureRm są zasadniczo identyczne.

Główne polecenia cmdlet

W tym artykule opisano polecenie cmdlet New-AzSqlServerVirtualNetworkRule, które dodaje punkt końcowy podsieci do listy kontroli dostępu (ACL) serwera, tworząc regułę.

Poniższa lista zawiera sekwencję innych głównych poleceń cmdlet, które należy uruchomić, aby przygotować się do wywołania polecenia New-AzSqlServerVirtualNetworkRule. W tym artykule te wywołania występują w skryscie 3 "Reguła sieci wirtualnej":

  1. New-AzVirtualNetworkSubnetConfig: tworzy obiekt podsieci.
  2. New-AzVirtualNetwork: tworzy sieć wirtualną, nadając jej podsieć.
  3. Set-AzVirtualNetworkSubnetConfig: przypisuje punkt końcowy usługi wirtualnej do podsieci.
  4. Set-AzVirtualNetwork: utrwala aktualizacje wprowadzone w sieci wirtualnej.
  5. New-AzSqlServerVirtualNetworkRule: Po utworzeniu podsieci jest punktem końcowym dodaj podsieć jako regułę sieci wirtualnej do listy ACL serwera.
    • To polecenie cmdlet oferuje parametr -IgnoreMissingVNetServiceEndpoint, począwszy od modułu Azure RM PowerShell w wersji 5.1.1.

Wymagania wstępne dotyczące uruchamiania programu PowerShell

  • Możesz już zalogować się do platformy Azure, na przykład za pośrednictwem witryny Azure Portal.
  • Można już uruchamiać skrypty programu PowerShell.

Uwaga

Upewnij się, że punkty końcowe usługi są włączone dla sieci wirtualnej/podsieci, którą chcesz dodać do serwera, w przeciwnym razie tworzenie reguły zapory sieci wirtualnej zakończy się niepowodzeniem.

Jeden skrypt podzielony na cztery fragmenty

Nasz demonstracyjny skrypt programu PowerShell jest podzielony na sekwencję mniejszych skryptów. Dział ułatwia naukę i zapewnia elastyczność. Skrypty muszą być uruchamiane w wskazanej kolejności. Jeśli nie masz teraz czasu na uruchomienie skryptów, nasze rzeczywiste dane wyjściowe testu są wyświetlane po skryscie 4.

Skrypt 1. Zmienne

Ten pierwszy skrypt programu PowerShell przypisuje wartości do zmiennych. Kolejne skrypty zależą od tych zmiennych.

Ważne

Przed uruchomieniem tego skryptu możesz edytować wartości, jeśli chcesz. Jeśli na przykład masz już grupę zasobów, możesz edytować nazwę grupy zasobów jako przypisaną wartość.

Nazwa subskrypcji powinna być edytowana w skrypcie.

Kod źródłowy skryptu programu PowerShell 1

######### Script 1 ########################################
##   LOG into to your Azure account.                     ##
##   (Needed only one time per powershell.exe session.)  ##
###########################################################

$yesno = Read-Host 'Do you need to log into Azure (only one time per powershell.exe session)?  [yes/no]'
if ('yes' -eq $yesno) { Connect-AzAccount }

###########################################################
##  Assignments to variables used by the later scripts.  ##
###########################################################

# You can edit these values, if necessary.
$SubscriptionName = 'yourSubscriptionName'
Select-AzSubscription -SubscriptionName $SubscriptionName

$ResourceGroupName = 'RG-YourNameHere'
$Region = 'westcentralus'

$VNetName = 'myVNet'
$SubnetName = 'mySubnet'
$VNetAddressPrefix = '10.1.0.0/16'
$SubnetAddressPrefix = '10.1.1.0/24'
$VNetRuleName = 'myFirstVNetRule-ForAcl'

$SqlDbServerName = 'mysqldbserver-forvnet'
$SqlDbAdminLoginName = 'ServerAdmin'
$SqlDbAdminLoginPassword = 'ChangeYourAdminPassword1'

$ServiceEndpointTypeName_SqlDb = 'Microsoft.Sql'  # Official type name.

Write-Host 'Completed script 1, the "Variables".'

Skrypt 2. Wymagania wstępne

Ten skrypt przygotowuje się do następnego skryptu, w którym znajduje się akcja punktu końcowego. Ten skrypt tworzy dla Ciebie następujące elementy wymienione na liście, ale tylko wtedy, gdy jeszcze nie istnieją. Jeśli masz pewność, że te elementy już istnieją, możesz pominąć skrypt 2:

  • Grupa zasobów platformy Azure
  • Logiczny serwer SQL

Kod źródłowy skryptu programu PowerShell 2

######### Script 2 ########################################
##   Ensure your Resource Group already exists.          ##
###########################################################

Write-Host "Check whether your Resource Group already exists."

$gottenResourceGroup = $null
$gottenResourceGroup = Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue

if ($null -eq $gottenResourceGroup) {
    Write-Host "Creating your missing Resource Group - $ResourceGroupName."
    New-AzResourceGroup -Name $ResourceGroupName -Location $Region
} else {
    Write-Host "Good, your Resource Group already exists - $ResourceGroupName."
}

$gottenResourceGroup = $null

###########################################################
## Ensure your server already exists. ##
###########################################################

Write-Host "Check whether your server already exists."

$sqlDbServer = $null
$azSqlParams = @{
    ResourceGroupName = $ResourceGroupName
    ServerName        = $SqlDbServerName
    ErrorAction       = 'SilentlyContinue'
}
$sqlDbServer = Get-AzSqlServer @azSqlParams

if ($null -eq $sqlDbServer) {
    Write-Host "Creating the missing server - $SqlDbServerName."
    Write-Host "Gather the credentials necessary to next create a server."

    $sqlAdministratorCredentials = [pscredential]::new($SqlDbAdminLoginName,(ConvertTo-SecureString -String $SqlDbAdminLoginPassword -AsPlainText -Force))

    if ($null -eq $sqlAdministratorCredentials) {
        Write-Host "ERROR, unable to create SQL administrator credentials.  Now ending."
        return
    }

    Write-Host "Create your server."

    $sqlSrvParams = @{
        ResourceGroupName           = $ResourceGroupName
        ServerName                  = $SqlDbServerName
        Location                    = $Region
        SqlAdministratorCredentials = $sqlAdministratorCredentials
    }
    New-AzSqlServer @sqlSrvParams
} else {
    Write-Host "Good, your server already exists - $SqlDbServerName."
}

$sqlAdministratorCredentials = $null
$sqlDbServer = $null

Write-Host 'Completed script 2, the "Prerequisites".'

Skrypt 3. Tworzenie punktu końcowego i reguły

Ten skrypt tworzy sieć wirtualną z podsiecią. Następnie skrypt przypisuje typ punktu końcowego Microsoft.Sql do podsieci. Na koniec skrypt dodaje podsieć do listy kontroli dostępu (ACL), tworząc regułę.

Kod źródłowy skryptu programu PowerShell 3

######### Script 3 ########################################
##   Create your virtual network, and give it a subnet.  ##
###########################################################

Write-Host "Define a subnet '$SubnetName', to be given soon to a virtual network."

$subnetParams = @{
    Name            = $SubnetName
    AddressPrefix   = $SubnetAddressPrefix
    ServiceEndpoint = $ServiceEndpointTypeName_SqlDb
}
$subnet = New-AzVirtualNetworkSubnetConfig @subnetParams

Write-Host "Create a virtual network '$VNetName'.`nGive the subnet to the virtual network that we created."

$vnetParams = @{
    Name              = $VNetName
    AddressPrefix     = $VNetAddressPrefix
    Subnet            = $subnet
    ResourceGroupName = $ResourceGroupName
    Location          = $Region
}
$vnet = New-AzVirtualNetwork @vnetParams

###########################################################
##   Create a Virtual Service endpoint on the subnet.    ##
###########################################################

Write-Host "Assign a Virtual Service endpoint 'Microsoft.Sql' to the subnet."

$vnetSubParams = @{
    Name            = $SubnetName
    AddressPrefix   = $SubnetAddressPrefix
    VirtualNetwork  = $vnet
    ServiceEndpoint = $ServiceEndpointTypeName_SqlDb
}
$vnet = Set-AzVirtualNetworkSubnetConfig @vnetSubParams

Write-Host "Persist the updates made to the virtual network > subnet."

$vnet = Set-AzVirtualNetwork -VirtualNetwork $vnet

$vnet.Subnets[0].ServiceEndpoints  # Display the first endpoint.

###########################################################
##   Add the Virtual Service endpoint Id as a rule,      ##
##   into SQL Database ACLs.                             ##
###########################################################

Write-Host "Get the subnet object."

$vnet = Get-AzVirtualNetwork -ResourceGroupName $ResourceGroupName -Name $VNetName

$subnet = Get-AzVirtualNetworkSubnetConfig -Name $SubnetName -VirtualNetwork $vnet

Write-Host "Add the subnet .Id as a rule, into the ACLs for your server."

$ruleParams = @{
    ResourceGroupName      = $ResourceGroupName
    ServerName             = $SqlDbServerName
    VirtualNetworkRuleName = $VNetRuleName
    VirtualNetworkSubnetId = $subnet.Id
}
New-AzSqlServerVirtualNetworkRule @ruleParams 

Write-Host "Verify that the rule is in the SQL Database ACL."

$rule2Params = @{
    ResourceGroupName      = $ResourceGroupName
    ServerName             = $SqlDbServerName
    VirtualNetworkRuleName = $VNetRuleName
}
Get-AzSqlServerVirtualNetworkRule @rule2Params

Write-Host 'Completed script 3, the "Virtual-Network-Rule".'

Skrypt 4. Czyszczenie

Ten końcowy skrypt usuwa zasoby utworzone przez poprzednie skrypty na potrzeby pokazu. Jednak skrypt prosi o potwierdzenie przed usunięciem następujących elementów:

  • Logiczny serwer SQL
  • Grupa zasobów platformy Azure

Skrypt można uruchomić 4 w dowolnym momencie po zakończeniu działania skryptu 1.

Kod źródłowy skryptu programu PowerShell 4

######### Script 4 ########################################
##   Clean-up phase A:  Unconditional deletes.           ##
##                                                       ##
##   1. The test rule is deleted from SQL Database ACL.        ##
##   2. The test endpoint is deleted from the subnet.    ##
##   3. The test virtual network is deleted.             ##
###########################################################

Write-Host "Delete the rule from the SQL Database ACL."

$removeParams = @{
    ResourceGroupName      = $ResourceGroupName
    ServerName             = $SqlDbServerName
    VirtualNetworkRuleName = $VNetRuleName
    ErrorAction            = 'SilentlyContinue'
}
Remove-AzSqlServerVirtualNetworkRule @removeParams

Write-Host "Delete the endpoint from the subnet."

$vnet = Get-AzVirtualNetwork -ResourceGroupName $ResourceGroupName -Name $VNetName

Remove-AzVirtualNetworkSubnetConfig -Name $SubnetName -VirtualNetwork $vnet

Write-Host "Delete the virtual network (thus also deletes the subnet)."

$removeParams = @{
    Name              = $VNetName
    ResourceGroupName = $ResourceGroupName
    ErrorAction       = 'SilentlyContinue'
}
Remove-AzVirtualNetwork @removeParams

###########################################################
##   Clean-up phase B:  Conditional deletes.             ##
##                                                       ##
##   These might have already existed, so user might     ##
##   want to keep.                                       ##
##                                                       ##
##   1. Logical SQL server                        ##
##   2. Azure resource group                             ##
###########################################################

$yesno = Read-Host 'CAUTION !: Do you want to DELETE your server AND your resource group?  [yes/no]'
if ('yes' -eq $yesno) {
    Write-Host "Remove the server."

    $removeParams = @{
        ServerName        = $SqlDbServerName
        ResourceGroupName = $ResourceGroupName
        ErrorAction       = 'SilentlyContinue'
    }
    Remove-AzSqlServer @removeParams

    Write-Host "Remove the Azure Resource Group."
    
    Remove-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue
} else {
    Write-Host "Skipped over the DELETE of SQL Database and resource group."
}

Write-Host 'Completed script 4, the "Clean-Up".'

Sprawdź, czy podsieć jest punktem końcowym

Być może masz podsieć, która została już przypisana nazwa typu Microsoft.Sql , co oznacza, że jest to już punkt końcowy usługi wirtualnej. Aby utworzyć regułę sieci wirtualnej z punktu końcowego, możesz użyć witryny Azure Portal .

Możesz też nie mieć pewności, czy podsieć ma nazwę typu Microsoft.Sql . Aby wykonać następujące działania, możesz uruchomić następujący skrypt programu PowerShell:

  1. Sprawdź, czy podsieć ma nazwę typu Microsoft.Sql .
  2. Opcjonalnie przypisz nazwę typu, jeśli jest nieobecna.
    • Skrypt prosi o potwierdzenie, zanim zastosuje on nieobecną nazwę typu.

Fazy skryptu

Oto fazy skryptu programu PowerShell:

  1. Zaloguj się do konta platformy Azure, potrzebne tylko raz na sesję PS. Przypisz zmienne.
  2. Wyszukaj sieć wirtualną, a następnie podsieć.
  3. Czy podsieć jest oznaczona jako typ serwera punktu końcowego Microsoft.Sql ?
  4. Dodaj punkt końcowy usługi wirtualnej o nazwie Typu Microsoft.Sql w podsieci.

Ważne

Przed uruchomieniem tego skryptu należy edytować wartości przypisane do zmienne $-, w górnej części skryptu.

Bezpośredni kod źródłowy programu PowerShell

Ten skrypt programu PowerShell nie aktualizuje niczego, chyba że odpowiesz tak, jeśli zostanie wyświetlony monit o potwierdzenie. Skrypt może dodać nazwę typu Microsoft.Sql do podsieci. Jednak skrypt próbuje dodać tylko wtedy, gdy podsieć nie ma nazwy typu.

### 1. LOG into to your Azure account, needed only once per PS session.  Assign variables.
$yesno = Read-Host 'Do you need to log into Azure (only one time per powershell.exe session)?  [yes/no]'
if ('yes' -eq $yesno) { Connect-AzAccount }

# Assignments to variables used by the later scripts.
# You can EDIT these values, if necessary.

$SubscriptionName = 'yourSubscriptionName'
Select-AzSubscription -SubscriptionName "$SubscriptionName"

$ResourceGroupName = 'yourRGName'
$VNetName = 'yourVNetName'
$SubnetName = 'yourSubnetName'
$SubnetAddressPrefix = 'Obtain this value from the Azure portal.' # Looks roughly like: '10.0.0.0/24'

$ServiceEndpointTypeName_SqlDb = 'Microsoft.Sql'  # Do NOT edit. Is official value.

### 2. Search for your virtual network, and then for your subnet.
# Search for the virtual network.
$vnet = $null
$vnet = Get-AzVirtualNetwork -ResourceGroupName $ResourceGroupName -Name $VNetName

if ($vnet -eq $null) {
    Write-Host "Caution: No virtual network found by the name '$VNetName'."
    return
}

$subnet = $null
for ($nn = 0; $nn -lt $vnet.Subnets.Count; $nn++) {
    $subnet = $vnet.Subnets[$nn]
    if ($subnet.Name -eq $SubnetName) { break }
    $subnet = $null
}

if ($null -eq $subnet) {
    Write-Host "Caution: No subnet found by the name '$SubnetName'"
    Return
}

### 3. Is your subnet tagged as 'Microsoft.Sql' endpoint server type?
$endpointMsSql = $null
for ($nn = 0; $nn -lt $subnet.ServiceEndpoints.Count; $nn++) {
    $endpointMsSql = $subnet.ServiceEndpoints[$nn]
    if ($endpointMsSql.Service -eq $ServiceEndpointTypeName_SqlDb) {
        $endpointMsSql
        break
    }
    $endpointMsSql = $null
}

if ($null -eq $endpointMsSql) {
    Write-Host "Good: Subnet found, and is already tagged as an endpoint of type '$ServiceEndpointTypeName_SqlDb'."
    return
} else {
    Write-Host "Caution: Subnet found, but not yet tagged as an endpoint of type '$ServiceEndpointTypeName_SqlDb'."

    # Ask the user for confirmation.
    $yesno = Read-Host 'Do you want the PS script to apply the endpoint type name to your subnet?  [yes/no]'
    if ('no' -eq $yesno) { return }
}

### 4. Add a Virtual Service endpoint of type name 'Microsoft.Sql', on your subnet.
$setParams = @{
    Name            = $SubnetName
    AddressPrefix   = $SubnetAddressPrefix
    VirtualNetwork  = $vnet
    ServiceEndpoint = $ServiceEndpointTypeName_SqlDb
}
$vnet = Set-AzVirtualNetworkSubnetConfig @setParams

# Persist the subnet update.
$vnet = Set-AzVirtualNetwork -VirtualNetwork $vnet

for ($nn = 0; $nn -lt $vnet.Subnets.Count; $nn++) {
    $vnet.Subnets[0].ServiceEndpoints # Display.
}