你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

用于通过你自己的密钥启用透明数据加密的 Azure CLI 脚本

适用于:Azure SQL 托管实例

此 Azure CLI 脚本示例使用 Azure Key Vault 中的客户管理的密钥在 Azure SQL 托管实例中配置透明数据加密 (TDE)。 这通常称为 TDE 的创建自己的密钥 (BYOK) 方案。 若要详细了解使用客户管理的密钥的 TDE,请参阅适用于 Azure SQL 的支持“创建自己的密钥”的 TDE

此示例需要现有的托管实例,请参阅使用 Azure CLI 创建 Azure SQL 托管实例

如果没有 Azure 订阅,请在开始之前创建一个 Azure 免费帐户

先决条件

示例脚本

对于此脚本,请在本地使用 Azure CLI,因为在 Cloud Shell 中运行所花费的时间较长。

登录 Azure

使用以下脚本和特定订阅进行登录。

subscription="<subscriptionId>" # add subscription here

az account set -s $subscription # ...or use 'az login'

有关详细信息,请参阅设置有效的订阅以交互方式登录

运行脚本

# Manage Transparent Data Encryption in a Managed Instance using your own key from Azure Key Vault

# Run this script after the script in https://docs.microsoft.com/en-us/azure/azure-sql/managed-instance/scripts/create-configure-managed-instance-cli creates a managed instance.
# You can use the same variables in both scripts/
# If running this script against a different existing instance, uncomment and add appropriate values to next 3 lines of code
# let "randomIdentifier=$RANDOM*$RANDOM"
# instance="<msdocs-azuresql-instance>" # add instance here
# resourceGroup="<msdocs-azuresql-rg>" # add resource here

# Variable block
location="East US"
vault="msdocssqlvault$randomIdentifier"
key="msdocs-azuresql-key-$randomIdentifier"

# echo assigning identity to service principal in the instance
az sql mi update --name $instance --resource-group $resourceGroup --assign-identity

echo "Creating $vault..."
az keyvault create --name $vault --resource-group $resourceGroup --location "$location"

echo "Getting service principal id and setting policy on $vault..."
instanceId=$(az sql mi show --name $instance --resource-group $resourceGroup --query identity.principalId --output tsv)

echo $instanceId
az keyvault set-policy --name $vault --object-id $instanceId --key-permissions get unwrapKey wrapKey

echo "Creating $key..."
az keyvault key create --name $key --vault-name $vault --size 2048 

# keyPath="C:\yourFolder\yourCert.pfx"
# keyPassword="yourPassword" 
# az keyvault certificate import --file $keyPath --name $key --vault-name $vault --password $keyPassword

echo "Setting security on $instance with $key..."
keyId=$(az keyvault key show --name $key --vault-name $vault -o json --query key.kid | tr -d '"')

az sql mi key create --kid $keyId --managed-instance $instance --resource-group $resourceGroup
az sql mi tde-key set --server-key-type AzureKeyVault --kid $keyId --managed-instance $instance --resource-group $resourceGroup

清理资源

使用 az group delete 命令删除资源组以及与其关联的所有资源 - 除非你持续需要这些资源。 其中一些资源在创建和删除时可能要稍等片刻。

az group delete --name $resourceGroup

示例参考

此脚本使用以下命令。 表中的每条命令均链接到特定于命令的文档。

命令 描述
az sql db 数据库命令。
az sql failover-group 故障转移组命令。

后续步骤

有关 Azure CLI 的详细信息,请参阅 Azure CLI 文档

其他 SQL 数据库 CLI 脚本示例可以在 Azure SQL 数据库文档中找到。