教程:将模块添加到 Azure 资源管理器 Bicep 文件Tutorial: Add modules to Azure Resource Manager Bicep file

上一篇教程中,你已学习如何使用参数文件来部署 Bicep 文件。In the previous tutorial, you learned how to use a parameter file to deploy your Bicep file. 本教程将介绍如何使用 Bicep 模块来封装原始资源声明的复杂细节。In this tutorial, you learn how to use Bicep modules to encapsulate complex details of the raw resource declaration. 可以在解决方案内部共享和重用这些模块。The modules can be shared and reused within your solution. 完成该过程需要大约 12 分钟It takes about 12 minutes to complete.

备注

本文包含 Bicep 示例。This article contains Bicep examples. Bicep 目前为预览版。Bicep is currently in preview. 有关详细信息,请参阅 Bicep 项目For more information, see Project Bicep.

先决条件Prerequisites

建议完成有关参数文件的教程,但这不是一项要求。We recommend that you complete the tutorial about parameter file, but it's not required.

必须有包含 Bicep 扩展的 Visual Studio Code,以及 Azure PowerShell 或 Azure CLI。You must have Visual Studio Code with the Bicep extension, and either Azure PowerShell or Azure CLI. 有关详细信息,请参阅 Bicep 工具For more information, see Bicep tools.

查看 Bicep 文件Review Bicep file

在上一篇教程结束时,Bicep 文件包含以下内容:At the end of the previous tutorial, your Bicep file had the following contents:

@minLength(3)
@maxLength(11)
param storagePrefix string

@allowed([
  'Standard_LRS'
  'Standard_GRS'
  'Standard_RAGRS'
  'Premium_LRS'
])
param storageSKU string = 'Standard_LRS'

param location string = resourceGroup().location
param appServicePlanName string = 'exampleplan'

@minLength(2)
@description('Base name of the resource such as web app name and app service plan.')
param webAppName string

@description('The Runtime stack of current web app.')
param linuxFxVersion string = 'php|7.0'

param resourceTags object = {
  Environment: 'Dev'
  Project: 'Tutorial'
}

var uniqueStorageName = '${storagePrefix}${uniqueString(resourceGroup().id)}'
var webAppPortalName = '${webAppName}${uniqueString(resourceGroup().id)}'

resource stg 'Microsoft.Storage/storageAccounts@2019-04-01' = {
  name: uniqueStorageName
  location: location
  tags: resourceTags
  sku: {
    name: storageSKU
  }
  kind: 'StorageV2'
  properties: {
    supportsHttpsTrafficOnly: true
  }
}

resource appPlan 'Microsoft.Web/serverfarms@2016-09-01' = {
  name: appServicePlanName
  location: location
  tags: resourceTags
  sku: {
    name: 'B1'
    tier: 'Basic'
    size: 'B1'
    family: 'B'
    capacity: 1
  }
  kind: 'linux'
  properties: {
    perSiteScaling: false
    reserved: true
    targetWorkerCount: 0
    targetWorkerSizeId: 0
  }
}

resource site 'Microsoft.Web/sites@2016-08-01' = {
  name: webAppPortalName
  location: location
  tags: resourceTags
  kind: 'app'
  properties: {
    serverFarmId: appPlan.id
    siteConfig: {
      linuxFxVersion: linuxFxVersion
    }
  }
}

output storageEndpoint object = stg.properties.primaryEndpoints

此 Bicep 文件可正常运行。This Bicep file works well. 但对于更大的解决方案,需要将 Bicep 文件分解成多个相关模块,以便可以共享和重用这些模块。But for larger solutions, you want to break your Bicep file into many related modules so you can share and reuse these modules. 当前的 Bicep 文件将部署存储帐户、应用服务计划和网站。The current Bicep file deploys a storage account, an app service plan, and a website. 让我们将存储帐户隔离到模块中。Let's separate the storage account into a module.

创建 Bicep 模块Create Bicep module

每个 Bicep 文件都可用作模块,因此在定义模块方面没有特定的语法。Every Bicep file can be consumed as a module, so there is no specific syntax for defining a module. 创建包含以下内容的 storage.bicep 文件:Create a storage.bicep file with the following contents:

@minLength(3)
@maxLength(11)
param storagePrefix string

@allowed([
  'Standard_LRS'
  'Standard_GRS'
  'Standard_RAGRS'
  'Premium_LRS'
])
param storageSKU string = 'Standard_LRS'

param location string
param resourceTags object

var uniqueStorageName = '${storagePrefix}${uniqueString(resourceGroup().id)}'

resource stg 'Microsoft.Storage/storageAccounts@2019-04-01' = {
  name: uniqueStorageName
  location: location
  tags: resourceTags
  sku: {
    name: storageSKU
  }
  kind: 'StorageV2'
  properties: {
    supportsHttpsTrafficOnly: true
  }
}

output storageEndpoint object = stg.properties.primaryEndpoints

此模块包含存储帐户资源以及相关的参数和变量。This module contains the storage account resource and the related parameters and variables. 已删除 location 参数和 resourceTags 参数的值。The values for the location parameter and the resourceTags parameters have been removed. 这些值将从 Bicep 主文件传递。These values will be passed from the main Bicep file.

使用 Bicep 模块Consume Bicep module

将现有 azuredeploy.bicep 中的存储帐户资源定义替换为以下 Bicep 内容:Replace the storage account resource definition in the existing azuredeploy.bicep with the following Bicep contents:

module stg './storage.bicep' = {
  name: 'storageDeploy'
  params: {
    storagePrefix: storagePrefix
    location: location
    resourceTags: resourceTags
  }
}
  • 模块:关键字。module: Keyword.
  • 符号名称 (stg):模块的标识符。symbolic name (stg): This is an identifier for the module.
  • 模块文件:在此示例中,模块的路径是使用相对路径 (./storage.bicep) 指定的。module file: The path to the module in this example is specified using a relative path (./storage.bicep). 必须使用正斜杠 (/) 目录分隔符来指定 Bicep 中的所有路径,以确保跨平台编译时的一致性。All paths in Bicep must be specified using the forward slash (/) directory separator to ensure consistent compilation cross-platform. 不支持 Windows 反斜杠 () 字符。The Windows backslash () character is unsupported.

若要检索存储终结点,请将 azuredeploy.bicep 中的输出更新为以下 Bicep:To retrieve storage endpoint, update the output in azuredeploy.bicep to the following Bicep:

output storageEndpoint object = stg.outputs.storageEndpoint

完成的 azuredeploy.bicep 包含以下内容:The completed azuredeploy.bicep has the following contents:

@minLength(3)
@maxLength(11)
param storagePrefix string

@allowed([
  'Standard_LRS'
  'Standard_GRS'
  'Standard_RAGRS'
  'Premium_LRS'
])
param storageSKU string = 'Standard_LRS'

param location string = resourceGroup().location
param appServicePlanName string = 'exampleplan'
param webAppName string {
  minLength: 2
  metadata: {
    description: 'Base name of the resource such as web app name and app service plan '
  }
}
param linuxFxVersion string {
  metadata: {
    description: 'The Runtime stack of current web app'
  }
  default: 'php|7.0'
}
param resourceTags object = {
  Environment: 'Dev'
  Project: 'Tutorial'
}

var uniqueStorageName = '${storagePrefix}${uniqueString(resourceGroup().id)}'
var webAppPortalName = '${webAppName}${uniqueString(resourceGroup().id)}'

module stg './storage.bicep' = {
  name: 'storageDeploy'
  params: {
    storagePrefix: storagePrefix
    location: location
    resourceTags: resourceTags
  }
}

resource appPlan 'Microsoft.Web/serverfarms@2016-09-01' = {
  name: appServicePlanName
  location: location
  tags: resourceTags
  sku: {
    name: 'B1'
    tier: 'Basic'
    size: 'B1'
    family: 'B'
    capacity: 1
  }
  kind: 'linux'
  properties: {
    perSiteScaling: false
    reserved: true
    targetWorkerCount: 0
    targetWorkerSizeId: 0
  }
}

resource site 'Microsoft.Web/sites@2016-08-01' = {
  name: webAppPortalName
  location: location
  tags: resourceTags
  kind: 'app'
  properties: {
    serverFarmId: appPlan.id
    siteConfig: {
      linuxFxVersion: linuxFxVersion
    }
  }
}

output storageEndpoint object = stg.outputs.storageEndpoint

部署模板Deploy template

使用 Azure CLI 或 Azure PowerShell 来部署模板。Use either Azure CLI or Azure PowerShell to deploy the template.

如果尚未创建资源组,请参阅创建资源组If you haven't created the resource group, see Create resource group. 此示例假定你已按第一篇教程所述将 bicepFile 变量设置为 Bicep 文件的路径。The example assumes you've set the bicepFile variable to the path to the Bicep file, as shown in the first tutorial.

若要运行此部署 cmdlet,你必须具有 Azure PowerShell 的最新版本To run this deployment cmdlet, you must have the latest version of Azure PowerShell.

New-AzResourceGroupDeployment `
  -Name addmodule `
  -ResourceGroupName myResourceGroup `
  -TemplateFile $bicepFile `
  -storagePrefix "store" `
  -storageSKU Standard_LRS `
  -webAppName demoapp

备注

如果部署失败,请使用 verbose 开关获取有关正在创建的资源的信息。If the deployment failed, use the verbose switch to get information about the resources being created. 使用 debug 开关获取调试的详细信息。Use the debug switch to get more information for debugging.

验证部署Verify deployment

可以通过在 Azure 门户中浏览资源组来验证部署。You can verify the deployment by exploring the resource groups from the Azure portal.

  1. 登录 Azure 门户Sign in to the Azure portal.
  2. 在左侧菜单中选择“资源组”。 From the left menu, select Resource groups.
  3. 你会看到在本教程中部署的新资源组。You will see the new resource group you deployed in this tutorial.
  4. 选择该资源组,查看部署的资源。Select the resource group and view the deployed resources. 请注意,这些资源与我们在模板文件中指定的值匹配。Notice that they match the values you specified in your template file.

清理资源Clean up resources

  1. 在 Azure 门户上的左侧菜单中选择“资源组” 。From the Azure portal, select Resource group from the left menu.
  2. 在“按名称筛选”字段中输入资源组名称。Enter the resource group name in the Filter by name field. 如果已完成此系列,则需删除三个资源组:myResourceGroup、myResourceGroupDev 和 myResourceGroupProd 。If you've completed this series, you have three resource groups to delete - myResourceGroup, myResourceGroupDev, and myResourceGroupProd.
  3. 选择资源组名称。Select the resource group name.
  4. 在顶部菜单中选择“删除资源组”。Select Delete resource group from the top menu.

后续步骤Next steps

恭喜!你已完成本简介文章,知道如何将 Bicep 文件部署到 Azure 了。Congratulations, you've finished this introduction to deploying Bicep files to Azure. 如果你有任何意见和建议,请在反馈部分告知我们。Let us know if you have any comments and suggestions in the feedback section. 谢谢!Thanks!

下一个教程系列将详细介绍如何部署模板。The next tutorial series goes into more detail about deploying templates.