練習 - 將部署指令碼新增至 ARM 範本

已完成

重要

您需要自己的 Azure 訂用帳戶才能完成此練習,而且可能會產生費用。 如果您還沒有 Azure 訂用帳戶,請在開始之前建立免費帳戶

在小組的應用程式部署過程中,您需要建立儲存體帳戶,並將檔案暫存在 Blob 儲存體中,供應用程式讀取。 到目前為止,您每次設定新的環境時,都會手動複製檔案。 您決定使用部署指令碼,在環境建立過程中將此步驟自動化。

在此練習中,您會採用現有的 Azure Resource Manager (ARM) 範本,並新增部署腳本。

在此過程中,您會:

  • 建立起始範本。
  • 新增部署指令碼的必要條件,包括使用者指派的受控識別和角色指派。
  • 新增部署指令碼。
  • 部署範本並驗證結果。

此練習使用適用於 Visual Studio Code 的 Azure Resource Manager 工具。 請務必在 Visual Studio Code 中安裝此延伸模組。

此練習使用適用於 Visual Studio Code 的 Bicep 延伸模組。 請務必在 Visual Studio Code 中安裝此延伸模組。

建立起始範本

您會從小組先前使用過的既有範本開始。 此範本會建立儲存體帳戶、設定 Blob 服務且需要 HTTPS,並為您的設定檔建立 Blob 容器。

  1. 開啟 Visual Studio Code。

  2. 建立名為 azuredeploy.json 的新檔案。

  3. 儲存空白檔案,以便 Visual Studio Code 載入 ARM 範本工具。

    您可以選取 [檔案]>[另存新檔],或在 Windows 中選取 Ctrl+S (在 macOS 上為 ⌘+S)。 記得確定您儲存檔案的位置。 例如,建議您建立 [scripts] 資料夾用於儲存檔案。

  4. 將下列起始範本複製到 azuredeploy.json

    {
        "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
        "contentVersion": "1.0.0.1",
        "apiProfile": "",
        "parameters": {},
        "variables": {
            "storageAccountName": "[concat('storage', uniqueString(resourceGroup().id))]",
            "storageBlobContainerName": "config"
        },
        "functions": [],
        "resources": [
            {
                "name": "[variables('storageAccountName')]",
                "type": "Microsoft.Storage/storageAccounts",
                "apiVersion": "2023-01-01",
                "tags": {
                    "displayName": "[variables('storageAccountName')]"
                },
                "location": "[resourceGroup().location]",
                "kind": "StorageV2",
                "sku": {
                    "name": "Standard_LRS",
                    "tier": "Standard"
                },
                "properties": {
                    "allowBlobPublicAccess": true,
                    "encryption": {
                        "services": {
                            "blob": {
                                "enabled": true
                            }
                        },
                        "keySource": "Microsoft.Storage"
                    },
                    "supportsHttpsTrafficOnly": true
                }
            },
            {
                "type": "Microsoft.Storage/storageAccounts/blobServices",
                "apiVersion": "2019-04-01",
                "name": "[concat(variables('storageAccountName'), '/default')]",
                "dependsOn": [
                    "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
                ]
            },
            {
                "type": "Microsoft.Storage/storageAccounts/blobServices/containers",
                "apiVersion": "2019-04-01",
                "name": "[concat(variables('storageAccountName'),'/default/',variables('storageBlobContainerName'))]",
                "dependsOn": [
                    "[resourceId('Microsoft.Storage/storageAccounts/blobServices', variables('storageAccountName'), 'default')]",
                    "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
                ],
                "properties": {
                    "publicAccess": "Blob"
                }
            }
        ]
    }
    
  5. 儲存範本。

  1. 開啟 Visual Studio Code。

  2. 建立名為 main.bicep 的新檔案。

  3. 儲存空白檔案,讓 Visual Studio Code 載入 Bicep 工具。

    您可以選取 [檔案]>[另存新檔],或在 Windows 中選取 Ctrl+S (在 macOS 上為 ⌘+S)。 請務必記住您儲存檔案的位置。 例如,建議您建立 [scripts] 資料夾來儲存檔案。

  4. 將下列起始範本複製到 main.bicep

    var storageAccountName = 'storage${uniqueString(resourceGroup().id)}'
    var storageBlobContainerName = 'config'
    
    resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {
      name: storageAccountName
      tags: {
        displayName: storageAccountName
      }
      location: resourceGroup().location
      kind: 'StorageV2'
      sku: {
        name: 'Standard_LRS'
        tier: 'Standard'
      }
      properties: {
        allowBlobPublicAccess: true
        encryption: {
          services: {
            blob: {
              enabled: true
            }
          }
          keySource: 'Microsoft.Storage'
        }
        supportsHttpsTrafficOnly: true
      }
    
      resource blobService 'blobServices' existing = {
        name: 'default'
      }
    }
    
    resource blobContainer 'Microsoft.Storage/storageAccounts/blobServices/containers@2019-04-01' = {
      parent: storageAccount::blobService
      name: storageBlobContainerName
      properties: {
        publicAccess: 'Blob'
      }
    }
    
  5. 儲存範本。

新增使用者指派的受控識別

接下來,您必須建立使用者指派的受控識別。 透過基礎結構即程式碼的方法,您可以在範本中建立身分識別。

  1. 編輯 variables 區段,以包含:

    "userAssignedIdentityName": "configDeployer",
    
  2. 編輯 resources 區段,以包含:

    {
        "type": "Microsoft.ManagedIdentity/userAssignedIdentities",
        "apiVersion": "2018-11-30",
        "name": "[variables('userAssignedIdentityName')]",
        "location": "[resourceGroup().location]"
    }
    
  3. 儲存範本。

  1. main.bicep 中的變數定義下,新增:

    var userAssignedIdentityName = 'configDeployer'
    
  2. 在資源定義下,新增:

    resource userAssignedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' = {
      name: userAssignedIdentityName
      location: resourceGroup().location
    }
    
  3. 儲存範本。

設定受控識別的參與者角色

既然您已定義受控識別,您可以向其指派具有資源群組權限的角色。 指派參與者角色。 您以角色定義識別碼 (GUID) 來識別角色。 參與者角色已內建於 Azure,因此已記載角色定義識別碼。

角色指派也需要 GUID 名稱。 您可以使用 guid 函式為資源群組和角色名稱建立唯一的 GUID。

  1. 編輯 variables 區段,以包含:

    "roleAssignmentName": "[guid(concat(resourceGroup().id, 'contributor'))]",
    "contributorRoleDefinitionId": "[resourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')]",
    
  2. 編輯 resources 區段,以包含:

    {
        "type": "Microsoft.Authorization/roleAssignments",
        "apiVersion": "2020-04-01-preview",
        "name": "[variables('roleAssignmentName')]",
        "dependsOn": [ "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('userAssignedIdentityName'))]" ],
        "properties": {
            "roleDefinitionId": "[variables('contributorRoleDefinitionId')]",
            "principalId": "[reference(resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('userAssignedIdentityName')), '2015-08-31-preview').principalId]",
            "scope": "[resourceGroup().id]",
            "principalType": "ServicePrincipal"
        }
    }
    
  3. 儲存範本。

  1. main.bicep 中的變數定義下,新增:

    var roleAssignmentName = guid(resourceGroup().id, 'contributor')
    var contributorRoleDefinitionId = resourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')
    
  2. 在資源定義下,新增:

    resource roleAssignment 'Microsoft.Authorization/roleAssignments@2020-04-01-preview' = {
      name: roleAssignmentName
      properties: {
        roleDefinitionId: contributorRoleDefinitionId
        principalId: userAssignedIdentity.properties.principalId
        principalType: 'ServicePrincipal'
      }
    }
    
  3. 儲存範本。

建立部署指令碼

現在,您已具備部署指令碼的所有必要條件。 您可以從部署文稿所需的一般值開始。 有兩個相依性:角色指派和 Blob 儲存體容器。 您的腳本必須先存在這兩個相依性,才能執行。

  1. 編輯 variables 區段,以包含:

    "deploymentScriptName": "CopyConfigScript"
    
  2. 編輯 resources 區段,以包含:

    {
        "type": "Microsoft.Resources/deploymentScripts",
        "apiVersion": "2020-10-01",
        "name": "[variables('deploymentScriptName')]",
        "location": "[resourceGroup().location]",
        "kind": "AzurePowerShell",
        "dependsOn": [
            "[resourceId('Microsoft.Authorization/roleAssignments', variables('roleAssignmentName'))]",
            "[resourceId('Microsoft.Storage/storageAccounts/blobServices/containers', variables('storageAccountName'), 'default', variables('storageBlobContainerName'))]"
        ],
        "identity": {
            "type": "UserAssigned",
            "userAssignedIdentities": {
                "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities',variables('userAssignedIdentityName'))]": {}
            }
        }
    }
    
  3. 請將一個 properties 區段新增至資源中,以定義腳本和其他必要的值。

    "properties": {
        "azPowerShellVersion": "3.0",
        "scriptContent": "
            Invoke-RestMethod -Uri 'https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/mslearn-arm-deploymentscripts-sample/appsettings.json' -OutFile 'appsettings.json'
            $storageAccount = Get-AzStorageAccount -ResourceGroupName 'learndeploymentscript_exercise_1' | Where-Object { $_.StorageAccountName -like 'storage*' }
            $blob = Set-AzStorageBlobContent -File 'appsettings.json' -Container 'config' -Blob 'appsettings.json' -Context $StorageAccount.Context
            $DeploymentScriptOutputs = @{}
            $DeploymentScriptOutputs['Uri'] = $blob.ICloudBlob.Uri
            $DeploymentScriptOutputs['StorageUri'] = $blob.ICloudBlob.StorageUri
        ",
        "retentionInterval": "P1D"
    }
    
  4. 儲存範本。

  1. main.bicep 中的變數定義下,新增:

    var deploymentScriptName = 'CopyConfigScript'
    
  2. 在資源定義下,新增:

    resource deploymentScript 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
      name: deploymentScriptName
      location: resourceGroup().location
      kind: 'AzurePowerShell'
      identity: {
        type: 'UserAssigned'
        userAssignedIdentities: {
          '${userAssignedIdentity.id}': {}
        }
      }
      dependsOn: [
        roleAssignment
        blobContainer
      ]
    }
    
  3. 請將一個 properties 區段新增至資源中,以定義腳本和其他必要的值。

    properties: {
      azPowerShellVersion: '3.0'
      scriptContent: '''
        Invoke-RestMethod -Uri 'https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/mslearn-arm-deploymentscripts-sample/appsettings.json' -OutFile 'appsettings.json'
        $storageAccount = Get-AzStorageAccount -ResourceGroupName 'learndeploymentscript_exercise_1' | Where-Object { $_.StorageAccountName -like 'storage*' }
        $blob = Set-AzStorageBlobContent -File 'appsettings.json' -Container 'config' -Blob 'appsettings.json' -Context $storageAccount.Context
        $DeploymentScriptOutputs = @{}
        $DeploymentScriptOutputs['Uri'] = $blob.ICloudBlob.Uri
        $DeploymentScriptOutputs['StorageUri'] = $blob.ICloudBlob.StorageUri
      '''
      retentionInterval: 'P1D'
    }
    
  4. 儲存範本。

新增範本輸出

既然您有部署指令碼可將檔案上傳至 Azure Blob 儲存體,在稍後的自動化中,您可能需要參考該檔案的位置。 (也許您執行測試來驗證檔案是否位於您認為它該在的位置。)

在 ARM 範本的 resources 區段之後,新增輸出來參考部署指令碼所報告的檔案 URI。

"outputs": {
    "fileUri": {
        "type": "string",
        "value": "[reference(variables('deploymentScriptName')).outputs.Uri]"
    }
}

在檔案底部的資源定義之後,新增輸出來參考部署指令碼所報告的檔案 URI。

output fileUri string = deploymentScript.properties.outputs.Uri

驗證範本

範本看起來應該像這樣:

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.1",
    "apiProfile": "",
    "parameters": {},
    "variables": {
        "storageAccountName": "[concat('storage', uniqueString(resourceGroup().id))]",
        "storageBlobContainerName": "config",
        "userAssignedIdentityName": "configDeployer",
        "roleAssignmentName": "[guid(concat(resourceGroup().id, 'contributor'))]",
        "contributorRoleDefinitionId": "[resourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')]",
        "deploymentScriptName": "CopyConfigScript"
    },
    "functions": [],
    "resources": [
        {
            "name": "[variables('storageAccountName')]",
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2023-01-01",
            "tags": {
                "displayName": "[variables('storageAccountName')]"
            },
            "location": "[resourceGroup().location]",
            "kind": "StorageV2",
            "sku": {
                "name": "Standard_LRS",
                "tier": "Standard"
            },
            "properties": {
                "allowBlobPublicAccess": true,
                "encryption": {
                    "services": {
                        "blob": {
                            "enabled": true
                        }
                    },
                    "keySource": "Microsoft.Storage"
                },
                "supportsHttpsTrafficOnly": true
            }
        },
        {
            "type": "Microsoft.Storage/storageAccounts/blobServices",
            "apiVersion": "2019-04-01",
            "name": "[concat(variables('storageAccountName'), '/default')]",
            "dependsOn": [
                "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
            ]
        },
        {
            "type": "Microsoft.Storage/storageAccounts/blobServices/containers",
            "apiVersion": "2019-04-01",
            "name": "[concat(variables('storageAccountName'),'/default/',variables('storageBlobContainerName'))]",
            "dependsOn": [
                "[resourceId('Microsoft.Storage/storageAccounts/blobServices', variables('storageAccountName'), 'default')]",
                "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
            ],
            "properties": {
                "publicAccess": "Blob"
            }
        },
        {
            "type": "Microsoft.ManagedIdentity/userAssignedIdentities",
            "apiVersion": "2018-11-30",
            "name": "[variables('userAssignedIdentityName')]",
            "location": "[resourceGroup().location]"
        },
        {
            "type": "Microsoft.Authorization/roleAssignments",
            "apiVersion": "2020-04-01-preview",
            "name": "[variables('roleAssignmentName')]",
            "dependsOn": [ "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('userAssignedIdentityName'))]" ],
            "properties": {
                "roleDefinitionId": "[variables('contributorRoleDefinitionId')]",
                "principalId": "[reference(resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', variables('userAssignedIdentityName')), '2015-08-31-preview').principalId]",
                "scope": "[resourceGroup().id]",
                "principalType": "ServicePrincipal"
            }
        },
        {
            "type": "Microsoft.Resources/deploymentScripts",
            "apiVersion": "2020-10-01",
            "name": "[variables('deploymentScriptName')]",
            "location": "[resourceGroup().location]",
            "kind": "AzurePowerShell",
            "dependsOn": [
                "[resourceId('Microsoft.Authorization/roleAssignments', variables('roleAssignmentName'))]",
                "[resourceId('Microsoft.Storage/storageAccounts/blobServices/containers', variables('storageAccountName'), 'default', variables('storageBlobContainerName'))]"
            ],
            "identity": {
                "type": "UserAssigned",
                "userAssignedIdentities": {
                    "[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities',variables('userAssignedIdentityName'))]": {}
                }
            },
            "properties": {
                "azPowerShellVersion": "3.0",
                "scriptContent": "
                    Invoke-RestMethod -Uri 'https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/mslearn-arm-deploymentscripts-sample/appsettings.json' -OutFile 'appsettings.json'
                    $storageAccount = Get-AzStorageAccount -ResourceGroupName 'learndeploymentscript_exercise_1' | Where-Object { $_.StorageAccountName -like 'storage*' }
                    $blob = Set-AzStorageBlobContent -File 'appsettings.json' -Container 'config' -Blob 'appsettings.json' -Context $StorageAccount.Context
                    $DeploymentScriptOutputs = @{}
                    $DeploymentScriptOutputs['Uri'] = $blob.ICloudBlob.Uri
                    $DeploymentScriptOutputs['StorageUri'] = $blob.ICloudBlob.StorageUri
                ",
                "retentionInterval": "P1D"
            }
        }
    ],
    "outputs": {
        "fileUri": {
            "type": "string",
            "value": "[reference(variables('deploymentScriptName')).outputs.Uri]"
        }
    }
}
var storageAccountName = 'storage${uniqueString(resourceGroup().id)}'
var storageBlobContainerName = 'config'
var userAssignedIdentityName = 'configDeployer'
var roleAssignmentName = guid(resourceGroup().id, 'contributor')
var contributorRoleDefinitionId = resourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')
var deploymentScriptName = 'CopyConfigScript'

resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {
  name: storageAccountName
  tags: {
    displayName: storageAccountName
  }
  location: resourceGroup().location
  kind: 'StorageV2'
  sku: {
    name: 'Standard_LRS'
    tier: 'Standard'
  }
  properties: {
    allowBlobPublicAccess: true
    encryption: {
      services: {
        blob: {
          enabled: true
        }
      }
      keySource: 'Microsoft.Storage'
    }
    supportsHttpsTrafficOnly: true
  }

  resource blobService 'blobServices' existing = {
    name: 'default'
  }
}

resource blobContainer 'Microsoft.Storage/storageAccounts/blobServices/containers@2019-04-01' = {
  parent: storageAccount::blobService
  name: storageBlobContainerName
  properties: {
    publicAccess: 'Blob'
  }
}

resource userAssignedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' = {
  name: userAssignedIdentityName
  location: resourceGroup().location
}

resource roleAssignment 'Microsoft.Authorization/roleAssignments@2020-04-01-preview' = {
  name: roleAssignmentName
  properties: {
    roleDefinitionId: contributorRoleDefinitionId
    principalId: userAssignedIdentity.properties.principalId
    principalType: 'ServicePrincipal'
  }
}

resource deploymentScript 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
  name: deploymentScriptName
  location: resourceGroup().location
  kind: 'AzurePowerShell'
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${userAssignedIdentity.id}': {}
    }
  }
  properties: {
    azPowerShellVersion: '3.0'
    scriptContent: '''
      Invoke-RestMethod -Uri 'https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/mslearn-arm-deploymentscripts-sample/appsettings.json' -OutFile 'appsettings.json'
      $storageAccount = Get-AzStorageAccount -ResourceGroupName 'learndeploymentscript_exercise_1' | Where-Object { $_.StorageAccountName -like 'storage*' }
      $blob = Set-AzStorageBlobContent -File 'appsettings.json' -Container 'config' -Blob 'appsettings.json' -Context $storageAccount.Context
      $DeploymentScriptOutputs = @{}
      $DeploymentScriptOutputs['Uri'] = $blob.ICloudBlob.Uri
      $DeploymentScriptOutputs['StorageUri'] = $blob.ICloudBlob.StorageUri
    '''
    retentionInterval: 'P1D'
  }
  dependsOn: [
    roleAssignment
    blobContainer
  ]
}

output fileUri string = deploymentScript.properties.outputs.Uri

如果不是,請複製範例或調整您的範本以符合範例。

部署範本

若要將此範本部署至 Azure,您必須從 Visual Studio Code 終端登入您的 Azure 帳戶。 請確定您已安裝 Azure CLI 工具。

  1. 在 [終端機] 功能表上,選取 [新增終端機]。 終端機視窗通常隨即在畫面的下半部開啟。

  2. 如果終端機視窗在右側顯示 bash,表示已開啟正確的殼層。 或者,如果您在右側看到 Bash 殼層圖示,則可以加以選取來啟動殼層。

    Visual Studio Code 終端機視窗的螢幕擷取畫面,其中顯示 [bash] 選項。

    如果出現 bash 以外的殼層,請選取殼層下拉式清單箭號,然後選取 [Git Bash]

    Visual Studio Code 終端機視窗的螢幕擷取畫面,其中顯示終端機殼層下拉式清單且已選取 [Git Bash (預設)]。

  3. 在終端機中,前往您儲存範本的目錄。 例如,若將範本儲存於 templates 資料夾,則可使用此命令:

    cd templates
    

使用 Azure CLI 登入 Azure

  1. 在 Visual Studio Code 終端中,執行下列命令以登入 Azure:

    az login
    
  2. 在開啟的瀏覽器中,登入您的 Azure 帳戶。

    Visual Studio Code 終端會顯示與此帳戶相關聯的訂用帳戶清單。

  3. 在清單中,尋找您要在此練習中使用的訂用帳戶。

    如果您在登入時錯過此清單,您可以使用下列程式碼片段以再次列出訂用帳戶。

    az account list --output table
    
  4. 針對您在此工作階段中執行的所有 Azure CLI 命令,設定預設訂用帳戶。

    az account set --subscription "Your Subscription Name or ID"
    

若要將此範本部署至 Azure,您必須從 Visual Studio Code 終端登入您的 Azure 帳戶。 請確定您已安裝 Azure CLI 工具。

  1. 在 [終端機] 功能表上,選取 [新增終端機]。 終端機視窗通常隨即在畫面的下半部開啟。

  2. 如果終端機視窗在右側顯示 bash,表示已開啟正確的殼層。 或者,如果您在右側看到 Bash 殼層圖示,則可以加以選取來啟動殼層。

    Visual Studio Code 終端機視窗的螢幕擷取畫面,其中顯示 [bash] 選項。

    如果出現 bash 以外的殼層,請選取殼層下拉式清單箭號,然後選取 [Git Bash]

    Visual Studio Code 終端機視窗的螢幕擷取畫面,其中顯示終端機殼層下拉式清單且已選取 [Git Bash (預設)]。

  3. 在終端機中,前往您儲存範本的目錄。 例如,若將範本儲存於 templates 資料夾,則可使用此命令:

    cd templates
    

安裝 Bicep

執行以下命令,確保您有最新版本 Bicep:

az bicep install && az bicep upgrade

使用 Azure CLI 登入 Azure

  1. 在 Visual Studio Code 終端中,執行下列命令以登入 Azure:

    az login
    
  2. 在開啟的瀏覽器中,登入您的 Azure 帳戶。

    Visual Studio Code 終端會顯示與此帳戶相關聯的訂用帳戶清單。

  3. 在清單中,尋找您要在此練習中使用的訂用帳戶。

    如果您在登入時錯過此清單,您可以使用下列程式碼片段以再次列出訂用帳戶。

    az account list --output table
    
  4. 針對您在此工作階段中執行的所有 Azure CLI 命令,設定預設訂用帳戶。

    az account set --subscription "Your Subscription Name or ID"
    

若要將此範本部署至 Azure,請從 Visual Studio Code 終端登入 Azure 帳戶。 請確定您已安裝 Azure PowerShell,並登入啟動沙箱的相同帳戶。

  1. 在 [終端機] 功能表上,選取 [新增終端機]。 終端機視窗通常隨即在畫面的下半部開啟。

  2. 如果終端視窗在右側顯示 pwshpowershell,表示已開啟正確的殼層。 或者,如果您在右側看到 PowerShell 殼層圖示,則可以加以選取來啟動殼層。

    Visual Studio Code 終端機視窗的螢幕擷取畫面,其中殼層下拉式清單中顯示 [pwsh] 選項。

    如果出現 pwshpowershell 以外的殼層,則請選取殼層下拉式箭頭,然後選取 [PowerShell]

    Visual Studio Code 終端機視窗的螢幕擷取畫面,其中顯示終端機殼層下拉式清單且已選取 [PowerShell]。

  3. 在終端機中,前往您儲存範本的目錄。 例如,若將範本儲存在 templates 資料夾,則可使用此命令:

    Set-Location -Path templates
    

使用 Azure PowerShell 登入 Azure

  1. 在 Visual Studio Code 終端中,執行下列命令以登入 Azure:

    Connect-AzAccount
    
  2. 在開啟的瀏覽器中,登入您的 Azure 帳戶。

  3. 執行下列命令,以取得您要在此練習中使用的訂用帳戶識別碼:

    Get-AzSubscription
    

    訂用帳戶識別碼是第二個資料行。 複製第二個資料行。 它看起來像 aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e

  4. 針對您在此工作階段中執行的所有 Azure PowerShell 命令,設定預設訂用帳戶。

    Set-AzContext -SubscriptionId {Your subscription ID}
    

若要將此範本部署至 Azure,請從 Visual Studio Code 終端登入 Azure 帳戶。 確定您已安裝 Azure PowerShell

  1. 在 [終端機] 功能表上,選取 [新增終端機]。 終端機視窗通常隨即在畫面的下半部開啟。

  2. 如果終端視窗在右側顯示 pwshpowershell,表示已開啟正確的殼層。 或者,如果您在右側看到 PowerShell 殼層圖示,則可以加以選取來啟動殼層。

    Visual Studio Code 終端機視窗的螢幕擷取畫面,其中殼層下拉式清單中顯示 [pwsh] 選項。

    如果出現 pwshpowershell 以外的殼層,則請選取殼層下拉式箭頭,然後選取 [PowerShell]

    Visual Studio Code 終端機視窗的螢幕擷取畫面,其中顯示終端機殼層下拉式清單且已選取 [PowerShell]。

  3. 在終端機中,前往您儲存範本的目錄。 例如,若將範本儲存在 templates 資料夾,則可使用此命令:

    Set-Location -Path templates
    

安裝 Bicep CLI

若要從 Azure PowerShell 使用 Bicep,請安裝 Bicep CLI

使用 Azure PowerShell 登入 Azure

  1. 在 Visual Studio Code 終端中,執行下列命令以登入 Azure:

    Connect-AzAccount
    
  2. 在開啟的瀏覽器中,登入您的 Azure 帳戶。

  3. 執行下列命令,以取得您要在此練習中使用的訂用帳戶識別碼:

    Get-AzSubscription
    

    訂用帳戶識別碼是第二個資料行。 複製第二個資料行。 它看起來像 aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e

  4. 針對您在此工作階段中執行的所有 Azure PowerShell 命令,設定預設訂用帳戶。

    Set-AzContext -SubscriptionId {Your subscription ID}
    

接下來,您必須建立資源群組,以包含您在此練習中建立的資源。 藉由使用新的資源群組,您將會使練習後的清理工作更加輕鬆。

從 Visual Studio Code 中的終端,執行此命令以建立此練習的資源群組:

建立練習的資源群組

resourceGroupName="learndeploymentscript_exercise_1"
az group create --location eastus --name $resourceGroupName
$resourceGroupName = 'learndeploymentscript_exercise_1'
New-AzResourceGroup -Location eastus -Name $resourceGroupName

注意

如果您針對資源群組使用不同的名稱,您必須確定要更新腳本。 在本課程模組稍後,您將瞭解如何避免在腳本中硬式編碼資源組名。

將範本部署至 Azure

下列程式碼會將 ARM 範本部署至 Azure。 您應該會看到成功的部署。

在 Visual Studio Code 終端機使用 Azure CLI 命令來部署範本。

templateFile="azuredeploy.json"
today=$(date +"%d-%b-%Y")
deploymentName="deploymentscript-"$today

az deployment group create \
    --resource-group $resourceGroupName \
    --name $deploymentName \
    --template-file $templateFile

下列程式碼會將 ARM 範本部署至 Azure。 您應該會看到成功的部署。

在 Visual Studio Code 終端機使用 Azure CLI 命令來部署範本。

templateFile="main.bicep"
today=$(date +"%d-%b-%Y")
deploymentName="deploymentscript-"$today

az deployment group create \
    --resource-group $resourceGroupName \
    --name $deploymentName \
    --template-file $templateFile

下列程式碼會將範本部署至 Azure。 您應該會看到成功的部署。

在終端中使用 Azure PowerShell 命令來部署範本。

$templateFile = 'azuredeploy.json'
$today = Get-Date -Format 'MM-dd-yyyy'
$deploymentName = "deploymentscript-$today"
New-AzResourceGroupDeployment `
  -ResourceGroupName $resourceGroupName `
  -Name $deploymentName `
  -TemplateFile $templateFile

下列程式碼會將範本部署至 Azure。 您應該會看到成功的部署。

在終端中使用 Azure PowerShell 命令來部署範本。

$templateFile = 'main.bicep'
$today = Get-Date -Format 'MM-dd-yyyy'
$deploymentName = "deploymentscript-$today"
New-AzResourceGroupDeployment `
  -ResourceGroupName $resourceGroupName `
  -Name $deploymentName `
  -TemplateFile $templateFile

檢閱範本的結果

部署完成後,您會看到一個 URL 指向部署指令碼已複製到 Blob 儲存體的檔案。

  1. 使用範本部署的 URL 輸出來擷取該檔案,以確認部署指令碼正常運作。

    uri=$(az deployment group show --resource-group $resourceGroupName --name $deploymentName --query 'properties.outputs.fileUri.value' --output tsv)
    curl $uri
    

    該命令傳回下列程式碼。

    {
      "environment": "production",
      "hostname": "tailwindtraders.com",
      "Logging": {
        "LogLevel": {
          "Default": "Debug"
        }
      },
      "ApplicationInsights": {
        "InstrumentationKey": ""
      },
      "AllowedHosts": "*",
      "CosmosDb": {
        "Host": "",
        "Key": "",
        "Database": "Products"
      }
    }
    
  2. 從 Azure 入口網站檢閱有關部署的記錄和其他詳細數據。 或者,您可以使用下列命令。

    az deployment-scripts show-log --resource-group $resourceGroupName --name CopyConfigScript
    
  1. 使用範本部署的 URL 輸出來擷取該檔案,以確認部署指令碼正常運作。

    $fileUri = (Get-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -Name $deploymentName).Outputs.fileUri.Value
    Invoke-RestMethod $fileUri
    

    該命令傳回下列程式碼。

    environment         : production
    hostname            : tailwindtraders.com
    Logging             : @{LogLevel=}
    ApplicationInsights : @{InstrumentationKey=}
    AllowedHosts        : *
    CosmosDb            : @{Host=; Key=; Database=Products}
    
  2. 從 Azure 入口網站檢閱有關部署的記錄和其他詳細數據。 或者,您可以使用下列命令。

    Get-AzDeploymentScriptLog -ResourceGroupName $resourceGroupName -Name CopyConfigScript
    

清理資源群組

既然您已使用部署文本成功部署 ARM 範本,您可以移除資源群組,其中包含您建立的所有資源和角色指派。

az group delete --name $resourceGroupName
Remove-AzResourceGroup -Name $resourceGroupName