教程:保护 Azure 资源管理器模板部署中的项目Tutorial: Secure artifacts in Azure Resource Manager template deployments

了解如何使用 Azure 存储帐户和共享访问签名 (SAS) 保护 Azure 资源管理器模板中使用的项目。Learn how to secure the artifacts used in your Azure Resource Manager templates by using an Azure Storage account with shared access signatures (SAS). 部署项目是指完成部署所需的任何文件以及主模板文件。Deployment artifacts are any files, in addition to the main template file, that are needed to complete a deployment. 例如,在教程:使用 Azure 资源管理器模板导入 SQL BACPAC 文件,主模板可创建 Azure SQL 数据库实例。For example, in Tutorial: Import SQL BACPAC files with Azure Resource Manager templates, the main template creates an Azure SQL Database instance. 它还调用 BACPAC 文件来创建表和插入数据。It also calls a BACPAC file to create tables and insert data. BACPAC 文件是一个项目,存储在 Azure 存储帐户中。The BACPAC file is an artifact and is stored in an Azure Storage account. 存储帐户密钥用于访问该项目。A storage account key was used to access the artifact.

在本教程中,你将使用 SAS 来授予对自己 Azure 存储帐户中 BACPAC 文件的有限访问权限。In this tutorial, you use SAS to grant limited access to the BACPAC file in your own Azure Storage account. 有关 SAS 的详细信息,请参阅使用共享访问签名 (SAS)For more information about SAS, see Using shared access signatures (SAS).

若要了解如何保护链接的模板,请参阅教程:创建链接的 Azure 资源管理器模板To learn how to secure a linked template, see Tutorial: Create linked Azure Resource Manager templates.

本教程涵盖以下任务:This tutorial covers the following tasks:

  • 准备 BACPAC 文件。Prepare a BACPAC file.
  • 打开现有模板。Open an existing template.
  • 编辑模板。Edit the template.
  • 部署模板。Deploy the template.
  • 验证部署。Verify the deployment.

如果没有 Azure 订阅,请在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

先决条件Prerequisites

若要完成本文,需要做好以下准备:To complete this article, you need:

准备 BACPAC 文件Prepare a BACPAC file

在本部分准备 BACPAC 文件,以便在部署资源管理器模板时可以安全访问该文件。In this section, you prepare the BACPAC file so that the file is accessible securely when you deploy the Resource Manager template. 本部分包括五个过程:There are five procedures in this section:

  • 下载 BACPAC 文件。Download the BACPAC file.
  • 创建 Azure 存储帐户。Create an Azure Storage account.
  • 创建存储帐户 Blob 容器。Create a storage account blob container.
  • 将 BACPAC 文件上传到该容器。Upload the BACPAC file to the container.
  • 检索 BACPAC 文件的 SAS 令牌。Retrieve the SAS token of the BACPAC file.
  1. 用管理特权打开 PowerShell 控制台。Open the PowerShell console with administration priviledge. 然后将以下 PowerShell 脚本粘贴到 Shell 窗口中。Then paste the following PowerShell script into the shell window.

    $projectName = Read-Host -Prompt "Enter a project name"   # This name is used to generate names for Azure resources, such as storage account name.
    $location = Read-Host -Prompt "Enter a location (i.e. chinaeast)"
    
    $resourceGroupName = $projectName + "rg"
    $storageAccountName = $projectName + "store"
    $containerName = "bacpacfile" # The name of the Blob container to be created.
    
    $bacpacURL = "https://github.com/Azure/azure-docs-json-samples/raw/master/tutorial-sql-extension/SQLDatabaseExtension.bacpac"
    $bacpacFileName = "SQLDatabaseExtension.bacpac" # A file name used for downloading and uploading the BACPAC file.
    
    # Download the bacpac file
    Invoke-WebRequest -Uri $bacpacURL -OutFile "$home/$bacpacFileName"
    
    # Create a resource group
    New-AzResourceGroup -Name $resourceGroupName -Location $location
    
    # Create a storage account
    $storageAccount = New-AzStorageAccount `
        -ResourceGroupName $resourceGroupName `
        -Name $storageAccountName `
        -Location $location `
        -SkuName "Standard_LRS"
    
    $context = $storageAccount.Context
    
    # Create a container
    New-AzStorageContainer -Name $containerName -Context $context
    
    # Upload the bacpac file
    Set-AzStorageBlobContent `
        -Container $containerName `
        -File "$home/$bacpacFileName" `
        -Blob $bacpacFileName `
        -Context $context
    
    # Generate a SAS token
    $bacpacURI = New-AzStorageBlobSASToken `
        -Context $context `
        -Container $containerName `
        -Blob $bacpacFileName `
        -Permission r `
        -ExpiryTime (Get-Date).AddHours(8.0) `
        -FullUri
    
    $str = $bacpacURI.split("?")
    
    Write-Host "You need the blob url and the SAS token later in the tutorial:"
    Write-Host $str[0]
    Write-Host (-join ("?", $str[1]))
    
    Write-Host "Press [ENTER] to continue ..."
    
  2. 请记下 BACPAC 文件 URL 和 SAS 令牌。Write down the BACPAC file URL and the SAS token. 部署模板时需要这些值。You need these values when you deploy the template.

打开现有模板Open an existing template

在此会话中,修改在教程:使用 Azure 资源管理器模板导入 SQL BACPAC 文件,以通过 SAS 令牌调用 BACPAC 文件。In this session, you modify the template you created in Tutorial: Import SQL BACPAC files with Azure Resource Manager templates to call the BACPAC file with an SAS token. SQL 扩展教程中开发的模板将在 GitHub 中共享。The template developed in the SQL extension tutorial is shared in GitHub.

  1. 在 Visual Studio Code 中,选择“文件” > “打开文件”。 From Visual Studio Code, select File > Open File.

  2. 在“文件名”中粘贴以下 URL: In File name, paste the following URL:

    https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/tutorial-sql-extension/azuredeploy2.json
    
  3. 选择“打开”以打开该文件。 Select Open to open the file.

    该模板中定义了四个资源:There are four resources defined in the template:

    • Microsoft.Sql/serversMicrosoft.Sql/servers.

    • Microsoft.SQL/servers/filewallRulesMicrosoft.SQL/servers/filewallRules.

    • Microsoft.SQL/servers/databasesMicrosoft.SQL/servers/databases.

    • Microsoft.SQL/server/databases/extensionsMicrosoft.SQL/server/databases/extensions.

      在自定义模板之前,不妨对其进行一些基本的了解。It's helpful to get some basic understanding of the template before you customize it.

  4. 选择“文件” > “另存为”,将该文件的副本保存到名为 azuredeploy.json 的本地计算机。 Select File > Save As to save a copy of the file to your local computer with the name azuredeploy.json.

编辑模板Edit the template

  1. 将 storageAccountKey 参数定义替换为以下参数定义:Replace the storageAccountKey parameter definition with the following parameter definition:

        "_artifactsLocationSasToken": {
          "type": "securestring",
          "metadata": {
            "description": "Specifies the SAS token required to access the artifact location."
          }
        },
    

    资源管理器教程安全项目参数

  2. 更新 SQL 扩展资源的以下三个元素值:Update the value of the following three elements of the SQL extension resource:

    "storageKeyType": "SharedAccessKey",
    "storageKey": "[parameters('_artifactsLocationSasToken')]",
    "storageUri": "[parameters('bacpacUrl')]",
    

完成的模板如下所示:The completed template looks like:

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "databaseServerName": {
      "type": "string",
      "defaultValue": "[concat('server-', uniqueString(resourceGroup().id, deployment().name))]",
      "metadata": {
        "description": "Specifies the name for the SQL server"
      }
    },
    "databaseName": {
      "type": "string",
      "defaultValue": "[concat('db-', uniqueString(resourceGroup().id, deployment().name), '-1')]",
      "metadata": {
        "description": "Specifies the name for the SQL database under the SQL server"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Specifies the location for server and database"
      }
    },
    "adminUser": {
      "type": "string",
      "metadata": {
        "description": "Specifies the username for admin"
      }
    },
    "adminPassword": {
      "type": "securestring",
      "metadata": {
        "description": "Specifies the password for admin"
      }
    },
    "_artifactsLocationSasToken": {
      "type": "securestring",
      "metadata": {
        "description": "Specifies the SAS token required to access the artifact location."
      }
    },
    "bacpacUrl": {
      "type": "string",
      "metadata": {
        "description": "Specifies the URL of the BACPAC file."
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.Sql/servers",
      "apiVersion": "2015-05-01-preview",
      "name": "[parameters('databaseServerName')]",
      "location": "[parameters('location')]",
      "properties": {
        "administratorLogin": "[parameters('adminUser')]",
        "administratorLoginPassword": "[parameters('adminPassword')]",
        "version": "12.0"
      },
      "resources": [
        {
          "type": "firewallrules",
          "apiVersion": "2015-05-01-preview",
          "name": "AllowAllAzureIps",
          "location": "[parameters('location')]",
          "dependsOn": [
            "[parameters('databaseServerName')]"
          ],
          "properties": {
            "startIpAddress": "0.0.0.0",
            "endIpAddress": "0.0.0.0"
          }
        }
      ]
    },
    {
      "type": "Microsoft.Sql/servers/databases",
      "apiVersion": "2017-10-01-preview",
      "name": "[concat(string(parameters('databaseServerName')), '/', string(parameters('databaseName')))]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[concat('Microsoft.Sql/servers/', parameters('databaseServerName'))]"
      ],
      "resources": [
        {
          "type": "extensions",
          "apiVersion": "2014-04-01",
          "name": "Import",
          "dependsOn": [
            "[resourceId('Microsoft.Sql/servers/databases', parameters('databaseServerName'), parameters('databaseName'))]"
          ],
          "properties": {
            "storageKeyType": "SharedAccessKey",
            "storageKey": "[parameters('_artifactsLocationSasToken')]",
            "storageUri": "[parameters('bacpacUrl')]",
            "administratorLogin": "[parameters('adminUser')]",
            "administratorLoginPassword": "[parameters('adminPassword')]",
            "operationMode": "Import"
          }
        }
      ]
    }
  ]
}

部署模板Deploy the template

Note

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

有关部署过程,请参阅部署模板部分。See the Deploy the template section for the deployment procedure. 改用以下 PowerShell 部署脚本。Use the following PowerShell deployment script instead.

$projectName = Read-Host -Prompt "Enter the project name that is used earlier"   # This name is used to generate names for Azure resources, such as storage account name.
$location = Read-Host -Prompt "Enter a location (i.e. chinaeast)"
$adminUsername = Read-Host -Prompt "Enter the sql database admin username"
$adminPassword = Read-Host -Prompt "Enter the admin password" -AsSecureString
$bacpacUrl = Read-Host -Prompt "Enter the BACPAC url"
$artifactsLocationSasToken = Read-Host -Prompt "Enter the artifacts location SAS token" -AsSecureString

$resourceGroupName = $projectName + "rg"

New-AzResourceGroup -Name $resourceGroupName -Location $location
New-AzResourceGroupDeployment `
    -ResourceGroupName $resourceGroupName `
    -adminUser $adminUsername `
    -adminPassword $adminPassword `
    -_artifactsLocationSasToken $artifactsLocationSasToken `
    -bacpacUrl $bacpacUrl `
    -TemplateFile "$HOME/azuredeploy.json"

Write-Host "Press [ENTER] to continue ..."

使用生成的密码。Use a generated password. 请参阅先决条件See Prerequisites. 有关 _artifactsLocation、_artifactsLocationSasToken 和 bacpacFileName 的值,请参阅准备 BACPAC 文件For the values of _artifactsLocation, _artifactsLocationSasToken, and bacpacFileName, see Prepare a BACPAC file.

验证部署Verify the deployment

在门户中,从新部署的资源组中选择 SQL 数据库。In the portal, select the SQL database from the newly deployed resource group. 选择“查询编辑器(预览)”,然后输入管理员凭据。 Select Query editor (preview), and then enter the administrator credentials. 此时会看到两个表导入到数据库中。You'll see two tables imported into the database.

查询编辑器(预览版)

清理资源Clean up resources

不再需要 Azure 资源时,请通过删除资源组来清理部署的资源。When the Azure resources are no longer needed, clean up the resources you deployed by deleting the resource group.

  1. 在 Azure 门户上的左侧菜单中选择“资源组” 。In the Azure portal, select Resource group from the left menu.
  2. 在“按名称筛选”字段中输入资源组名称。 Enter the resource group name in the Filter by name field.
  3. 选择资源组名称。Select the resource group name. 应会看到,该资源组中总共有六个资源。You'll see a total of six resources in the resource group.
  4. 在顶部菜单中选择“删除资源组”。 Select Delete resource group from the top menu.

后续步骤Next steps

在本教程中,你已部署 SQL Server 和 SQL 数据库,并已使用 SAS 令牌导入 BACPAC 文件。In this tutorial, you deployed a SQL server and a SQL database and imported a BACPAC file by using an SAS token. 若要了解如何创建 Azure 管道以持续开发和部署资源管理器模板,请参阅:To learn how to create an Azure pipeline to continuously develop and deploy Resource Manager templates, see: