练习 - 使用 Azure 资源管理器变量存储表达式
在本练习中,你将 Azure 存储帐户名称表达式存储在 Azure 资源管理器(ARM)模板变量中。 然后,使用该变量指定要创建的存储帐户的名称。
在本练习中,我们使用 适用于 Visual Studio Code 的 Azure 资源管理器工具。 请务必在 Visual Studio Code 中安装此扩展。
注释
本练习为选做练习。 若要完成本练习,则需要在开始之前创建 Azure 订阅。 如果没有 Azure 帐户或不想暂时创建一个帐户,可以通读说明,以便了解所显示的信息。
注释
在本单元中,你将使用 Azure Cloud Shell 作为终端。 可以通过 Azure 门户 或 Cloud Shell 登录访问 Cloud Shell。 无需在电脑或笔记本电脑上安装任何内容即可使用它。
添加变量
添加变量以将存储帐户名称表达式存储在模板中的一个位置。
- 在 Visual Studio Code 的 azuredeploy.json 文件中,将光标放在变量块 - "variables":{}中的大括号之间,然后按 Enter。
- 在大括号内键入 var 。 你将看到相关代码片段的列表。 选择 arm-variable:   
- 变量部分类似于以下代码: - "variables": {"variable1": "value"},
- 将变量的名称更改为 uniqueStorageName,并将值更改为“[toLower(concat(parameters('storagePrefix'),uniqueString(resourceGroup(.id)]]”。 变量部分类似于以下代码: - "variables": { "uniqueStorageName": "[toLower(concat(parameters('storagePrefix'),uniqueString(resourceGroup().id)))]" },- 请注意,在 - storagePrefix表达式中使用参数而不是文本字符串。 否则,此表达式与上一单元中学到的表达式相同。
- 使用资源部分中的变量。 将 - name:和- displayName属性的值更改为“[variables('uniqueStorageName')]”
- 整个文件如以下示例所示: - { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "storagePrefix": { "type": "string", "minLength": 3, "maxLength": 11 }, "storageSKU": { "type": "string", "defaultValue": "Standard_LRS", "allowedValues": [ "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS", "Premium_ZRS", "Standard_GZRS", "Standard_RAGZRS" ] } }, "functions": [], "variables": { "uniqueStorageName": "[toLower(concat(parameters('storagePrefix'),uniqueString(resourceGroup().id)))]" }, "resources": [{ "name": "[variables('uniqueStorageName')]", "type": "Microsoft.Storage/storageAccounts", "apiVersion": "2019-06-01", "tags": { "displayName": "[variables('uniqueStorageName')]" }, "location": "[resourceGroup().location]", "kind": "StorageV2", "sku": { "name": "[parameters('storageSKU')]" } }], "outputs": {} }
(可选)部署模板
更新后的模板对部署的资源没有任何更改,因此部署此模板不会对 Azure 环境进行任何更改。
如果要部署模板以查看它是否成功,请使用以下 Azure CLI 命令。 请务必使用上一个部署中使用的相同 storagePrefix 参数值。
templateFile="azuredeploy.json"
today=$(date +"%d-%b-%Y")
DeploymentName="addVariable-"$today
az deployment group create \
  --name $DeploymentName \
  --template-file $templateFile \
  --parameters storagePrefix={your-Prefix}
如果要部署模板以查看它是否成功,请使用以下 Azure PowerShell 命令。 请务必使用上一个部署中使用的相同 storagePrefix 参数值。
$templateFile = "azuredeploy.json"
$today=Get-Date -Format "MM-dd-yyyy"
$deploymentName="addVariable-"+"$today"
New-AzResourceGroupDeployment `
  -Name $deploymentName `
  -TemplateFile $templateFile `
  -storagePrefix {your-Prefix}