Script de PowerShell para habilitar el cifrado de datos transparente mediante una clave propia

Se aplica a:Azure SQL Managed Instance

Este ejemplo de script de PowerShell configura el cifrado de datos transparente (TDE) en Azure SQL Managed Instance con una clave administrada por el cliente de Azure Key Vault. Con frecuencia esto se denomina escenario de Bring Your Own Key para TDE. Para más información, consulte Cifrado de datos transparente de Azure SQL con una clave administrada por el cliente.

Requisitos previos

Si no tiene una suscripción a Azure, cree una cuenta gratuita de Azure antes de empezar.

Nota:

En este artículo se usa el módulo Az de PowerShell, que es el módulo de PowerShell que se recomienda para interactuar con Azure. Para empezar a trabajar con el módulo Az de PowerShell, consulte Instalación de Azure PowerShell. Para más información sobre cómo migrar al módulo Az de PowerShell, consulte Migración de Azure PowerShell de AzureRM a Az.

Uso de Azure Cloud Shell

En Azure se hospeda Azure Cloud Shell, un entorno de shell interactivo que puede utilizar mediante el explorador. Puede usar Bash o PowerShell con Cloud Shell para trabajar con los servicios de Azure. Puede usar los comandos preinstalados de Cloud Shell para ejecutar el código de este artículo sin tener que instalar nada en su entorno local.

Para iniciar Azure Cloud Shell:

Opción Ejemplo o vínculo
Seleccione Pruébelo en la esquina superior derecha de un bloque de código. Solo con seleccionar Pruébelo no se copia automáticamente el código en Cloud Shell. Screenshot that shows an example of Try It for Azure Cloud Shell.
Vaya a https://shell.azure.com o seleccione el botón Iniciar Cloud Shell para abrir Cloud Shell en el explorador. Screenshot that shows how to launch Cloud Shell in a new window.
Seleccione el botón Cloud Shell en la barra de menús de la esquina superior derecha de Azure Portal. Screenshot that shows the Cloud Shell button in the Azure portal

Para ejecutar el código de este artículo en Azure Cloud Shell:

  1. Inicie Cloud Shell.

  2. Seleccione el botón Copiar de un bloque de código para copiar el código.

  3. Pegue el código en la sesión de Cloud Shell. Para ello, seleccione CTRL+Mayús+V en Windows y Linux, o bien seleccione Cmd+Mayús+V en macOS.

  4. Seleccione Entrar para ejecutar el código.

Tanto el uso local de PowerShell como el de Azure Cloud Shell requieren Azure PowerShell 2.3.2 o una versión posterior. Si necesita realizar la actualización, consulte Instalación del módulo de Azure PowerShell o ejecute el script de ejemplo siguiente para instalar el módulo en el usuario actual:

Install-Module -Name Az -AllowClobber -Scope CurrentUser

Si PowerShell se ejecuta localmente, también debe ejecutar Connect-AzAccount para crear una conexión con Azure.

Muestras de 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 Az.Sql PowerShell package if you are running this PowerShell locally (uncomment below):
# Install-Module -Name Az.Sql

# 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

# 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

# Allow access from your client IP address(es) to be able to complete remaining steps: 
Update-AzKeyVaultNetworkRuleSet -VaultName $vaultname -IpAddressRange "xxx.xxx.xxx.xxx/xx"

# 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)

# First, give yourself necessary permissions on the AKV, (specify your account instead of contoso.com):
Set-AzKeyVaultAccessPolicy -VaultName $vaultname -UserPrincipalName "myaccount@contoso.com" -PermissionsToKeys create,import,get,list

# 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

Pasos siguientes

Para más información sobre Azure PowerShell, consulte la documentación de Azure PowerShell.

Puede encontrar más ejemplos de scripts de PowerShell para Instancia administrada de SQL en Scripts de PowerShell de Instancia administrada de Azure SQL.