你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
减少 Bicep 文件中共享值的重复。 而是从 Bicep 文件中的共享 JSON 文件加载这些值。 使用数组时,将共享值与 Bicep 代码中与特定部署相关的值连接在一起。
上下文和问题
编写 Bicep 代码时,你可能具有在一组 Bicep 文件中重复使用的常见变量。 每次声明资源时,都可以反复复制这些值,例如在不同的 Bicep 文件之间复制和粘贴这些值。 但是,此方法容易出错,需要进行更改时,需要更新每个资源定义,使其与其他资源保持同步。
此外,使用定义为数组的变量时,可能有多个 Bicep 文件都有一组通用值,并且还需要为要部署的资源添加特定值。 将共享变量与特定于资源的变量混合时,人们很难理解这两类变量之间的区别。
解决方案
创建包含需要共享的变量的 JSON 文件。 使用 loadJsonContent()
函数 加载文件并访问变量。 对于数组变量,使用 concat()
函数 将共享值与特定资源的任何自定义值组合在一起。
示例 1:命名前缀
假设有多个定义资源的 Bicep 文件。 需要为所有资源使用一致的命名前缀。
定义一个 JSON 文件,其中包含跨公司应用的常见命名前缀:
{
"storageAccountPrefix": "stg",
"appServicePrefix": "app"
}
在 Bicep 文件中,声明导入共享命名前缀的变量:
var sharedNamePrefixes = loadJsonContent('./shared-prefixes.json')
定义资源名称时,请使用字符串内插将共享名称前缀与唯一名称后缀连接在一起:
var appServiceAppName = '${sharedNamePrefixes.appServicePrefix}-myapp-${uniqueString(resourceGroup().id)}'
var storageAccountName = '${sharedNamePrefixes.storageAccountPrefix}myapp${uniqueString(resourceGroup().id)}'
示例 2:网络安全组规则
假设有多个 Bicep 文件定义其自己的网络安全组 (NSG)。 你有一组通用的安全规则,这些规则必须应用于每个 NSG,然后必须添加特定于应用程序的规则。
定义一个 JSON 文件,其中包含跨公司应用的常见安全规则:
{
"securityRules": [
{
"name": "Allow_RDP_from_company_IP_address",
"properties": {
"description": "Allow inbound RDP from the company's IP address range.",
"protocol": "Tcp",
"sourceAddressPrefix": "203.0.113.0/24",
"sourcePortRange": "*",
"destinationAddressPrefix": "VirtualNetwork",
"destinationPortRange": "3389",
"access": "Allow",
"priority": 100,
"direction": "Inbound"
}
},
{
"name": "Allow_VirtualNetwork_to_Storage",
"properties": {
"description": "Allow outbound connections to the Azure Storage service tag.",
"protocol": "Tcp",
"sourceAddressPrefix": "VirtualNetwork",
"sourcePortRange": "*",
"destinationAddressPrefix": "Storage",
"destinationPortRange": "*",
"access": "Allow",
"priority": 100,
"direction": "Outbound"
}
}
// other rules here
]
}
在 Bicep 文件中,声明导入共享安全规则的变量:
var sharedRules = loadJsonContent('./shared-rules.json', 'securityRules')
创建一个代表此特定 NSG 的自定义规则的变量数组:
var customRules = [
{
name: 'Allow_Internet_HTTPS_Inbound'
properties: {
description: 'Allow inbound internet connectivity for HTTPS only.'
protocol: 'Tcp'
sourcePortRange: '*'
destinationPortRange: '443'
sourceAddressPrefix: 'Internet'
destinationAddressPrefix: 'VirtualNetwork'
access: 'Allow'
priority: 400
direction: 'Inbound'
}
}
]
定义 NSG 资源。 使用 concat()
函数将两个数组组合在一起并设置 securityRules
属性:
resource nsg 'Microsoft.Network/networkSecurityGroups@2021-08-01' = {
name: nsgName
___location: ___location
properties: {
securityRules: concat(sharedRules, customRules)
}
}
注意事项
- 使用此方法时,JSON 文件将包含在 Bicep 生成的 ARM 模板中。 Bicep 生成的 JSON ARM 模板的文件限制为 4MB,因此请务必避免使用大型共享变量文件。
- 确保共享变量数组不会与每个 Bicep 文件中指定的数组值冲突。 例如,使用配置集模式定义网络安全组时,请确保没有定义相同优先级和方向的多个规则。