Gerenciar Transparent Data Encryption em um Instância Gerenciada usando sua própria chave de Azure Key Vault (versão prévia)Manage Transparent Data Encryption in a Managed Instance using your own key from Azure Key Vault (Preview)

Este exemplo de script do PowerShell configura Transparent Data Encryption (TDE) no cenário Bring Your Own Key (versão prévia) para Instância Gerenciada do SQL do Azure, usando uma chave de Azure Key Vault.This PowerShell script example configures Transparent Data Encryption (TDE) in Bring Your Own Key (preview) scenario for Azure SQL Managed Instance, using a key from Azure Key Vault. Para saber mais sobre a TDE com suporte BYOK (Bring Your Own Key), visite TDE com Bring Your Own Key para SQL do Azure.To learn more about the TDE with Bring Your Own Key (BYOK) Support, see TDE Bring Your Own Key to Azure SQL.

Pré-requisitosPrerequisites

Se você não tiver uma assinatura do Azure, crie uma conta gratuita antes de começar.If you don't have an Azure subscription, create a free account before you begin.

Observação

Este artigo foi atualizado para usar o novo módulo Az do Azure PowerShell.This article has been updated to use the new Azure PowerShell Az module. Você ainda pode usar o módulo AzureRM, que continuará a receber as correções de bugs até pelo menos dezembro de 2020.You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. Para saber mais sobre o novo módulo Az e a compatibilidade com o AzureRM, confira Apresentação do novo módulo Az do Azure PowerShell.To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. Para obter instruções de instalação do módulo Az, confira Instalar o Azure PowerShell.For Az module installation instructions, see Install Azure PowerShell.

Usar o Azure Cloud ShellUse Azure Cloud Shell

O Azure hospeda o Azure Cloud Shell, um ambiente de shell interativo que pode ser usado por meio do navegador.Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. O Cloud Shell permite usar bash ou PowerShell para trabalhar com serviços do Azure.Cloud Shell lets you use either bash or PowerShell to work with Azure services. É possível usar os comandos pré-instalados do Cloud Shell para executar o código neste artigo sem precisar instalar nada no seu ambiente local.You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

Para iniciar o Azure Cloud Shell:To launch Azure Cloud Shell:

OpçãoOption Exemplo/LinkExample/Link
Selecione Experimente no canto superior direito de um bloco de código.Select Try It in the upper-right corner of a code block. Selecionar Experimente não copia automaticamente o código para o Cloud Shell.Selecting Try It doesn't automatically copy the code to Cloud Shell. Exemplo de “Experimente” no Azure Cloud Shell
Acesse https://shell.azure.com ou clique no botão Iniciar o Cloud Shell para abri-lo no navegador.Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. Inicie o Cloud Shell em uma nova janelaLaunch Cloud Shell in a new window
Clique no botão Cloud Shell na barra de menus no canto superior direito do portal do Azure.Select the Cloud Shell button on the top-right menu bar in the Azure portal. Botão Cloud Shell no portal do Azure

Para executar o código neste artigo no Azure Cloud Shell:To run the code in this article in Azure Cloud Shell:

  1. Inicie o Cloud Shell.Launch Cloud Shell.

  2. Clique no botão Copiar no bloco de código para copiá-lo.Select the Copy button on a code block to copy the code.

  3. Cole o código na sessão do Cloud Shell com Ctrl+Shift+V no Windows e no Linux ou Cmd+Shift+V no macOS.Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.

  4. Pressione Enter para executar o código.Press Enter to run the code.

Usar o PowerShell localmente ou usando Azure Cloud Shell requer AZ PowerShell 1.1.1-Preview ou uma versão de visualização posterior.Using both PowerShell locally or using Azure Cloud Shell requires AZ PowerShell 1.1.1-preview or a later preview version. Se você precisar atualizar, consulte instalar Azure PowerShell móduloou execute o script de exemplo abaixo para instalar o módulo.If you need to upgrade, see Install Azure PowerShell module, or run the below sample script to install the module.

Install-Module -Name Az.Sql -RequiredVersion 1.1.1-preview -AllowPrerelease -Force

Se você estiver executando o PowerShell localmente, também precisará executar o Connect-AzAccount para criar uma conexão com o Azure.If you are running PowerShell locally, you also need to run Connect-AzAccount to create a connection with Azure.

Scripts de exemploSample scripts

# You will need an existing Managed Instance as a prerequisite for completing this script.
# See https://docs.microsoft.com/en-us/azure/sql-database/scripts/sql-database-create-configure-managed-instance-powershell

# Log in to your Azure account:
Connect-AzAccount

# If there are multiple subscriptions, choose the one where AKV is created: 
Set-AzContext -SubscriptionId "subscription ID"

# Install the preview version of Az.Sql PowerShell package 1.1.1-preview if you are running this PowerShell locally (uncomment below):
# Install-Module -Name Az.Sql -RequiredVersion 1.1.1-preview -AllowPrerelease -Force

# 1. Create Resource and setup Azure Key Vault (skip if already done)

# Create Resource group (name the resource and specify the location)
$location = "westus2" # specify the location
$resourcegroup = "MyRG" # specify a new RG name
New-AzResourceGroup -Name $resourcegroup -Location $location

# Create new Azure Key Vault with a globally unique VaultName and soft-delete option turned on:
$vaultname = "MyKeyVault" # specify a globally unique VaultName
New-AzKeyVault -VaultName $vaultname -ResourceGroupName $resourcegroup -Location $location -EnableSoftDelete

# Authorize Managed Instance to use the AKV (wrap/unwrap key and get public part of key, if public part exists): 
$objectid = (Set-AzSqlInstance -ResourceGroupName $resourcegroup -Name "MyManagedInstance" -AssignIdentity).Identity.PrincipalId
Set-AzKeyVaultAccessPolicy -BypassObjectIdValidation -VaultName $vaultname -ObjectId $objectid -PermissionsToKeys get,wrapKey,unwrapKey

# Allow access from trusted Azure services: 
Update-AzKeyVaultNetworkRuleSet -VaultName $vaultname -Bypass AzureServices

# Turn the network rules ON by setting the default action to Deny: 
Update-AzKeyVaultNetworkRuleSet -VaultName $vaultname -DefaultAction Deny


# 2. Provide TDE Protector key (skip if already done)

# The recommended way is to import an existing key from a .pfx file. Replace "<PFX private key password>" with the actual password below:
$keypath = "c:\some_path\mytdekey.pfx" # Supply your .pfx path and name
$securepfxpwd = ConvertTo-SecureString -String "<PFX private key password>" -AsPlainText -Force 
$key = Add-AzKeyVaultKey -VaultName $vaultname -Name "MyTDEKey" -KeyFilePath $keypath -KeyFilePassword $securepfxpwd

# ...or get an existing key from the vault:
# $key = Get-AzKeyVaultKey -VaultName $vaultname -Name "MyTDEKey"

# Alternatively, generate a new key directly in Azure Key Vault (recommended for test purposes only - uncomment below):
# $key = Add-AzureKeyVaultKey -VaultName $vaultname -Name MyTDEKey -Destination Software -Size 2048

# 3. Set up BYOK TDE on Managed Instance:

# Assign the key to the Managed Instance:
# $key = 'https://contoso.vault.azure.net/keys/contosokey/01234567890123456789012345678901'
Add-AzSqlInstanceKeyVaultKey -KeyId $key.id -InstanceName "MyManagedInstance" -ResourceGroupName $resourcegroup

# Set TDE operation mode to BYOK: 
Set-AzSqlInstanceTransparentDataEncryptionProtector -Type AzureKeyVault -InstanceName "MyManagedInstance" -ResourceGroup $resourcegroup -KeyId $key.id

Próximas etapasNext steps

Para obter mais informações sobre o Azure PowerShell, confira Documentação do Azure PowerShell.For more information on the Azure PowerShell, see Azure PowerShell documentation.

Outros exemplos de script do PowerShell para Banco de Dados SQL podem ser encontrados nos scripts do PowerShell para Banco de Dados SQL do Azure.Additional SQL Database PowerShell script samples can be found in the Azure SQL Database PowerShell scripts.