使用 Azure VM Image Builder 和 Microsoft Dev Box 設定開發方塊

在本文中,您會使用 Azure VM Image Builder,使用範本在 Microsoft Dev Box 中建立自定義的開發方塊。 範本包含安裝 Visual Studio Code (VS Code) 的自定義步驟。

當您的組織使用標準化的虛擬機 (VM) 映射時,它可以更輕鬆地移轉至雲端,並協助確保部署中的一致性。 映像通常包括預先定義的安全性、組態設定,以及任何必要的軟體。 設定您自己的映射管線需要時間、基礎結構和其他許多詳細數據。 使用 Azure VM 映射產生器,您可以建立描述映像的組態。 服務接著會建置映像,並將其提交至開發方塊專案。

雖然您可以手動或使用其他工具來建立自定義 VM 映像,但程式可能很麻煩且不可靠。 VM 映射產生器建置在 HashiCorp Packer 上,可提供受控服務的優點。

若要降低建立 VM 映射的複雜性,VM 映射產生器:

  • 拿掉使用複雜工具、程式和手動步驟來建立 VM 映像的需求。 VM 映射產生器會擷取所有這些詳細數據,並隱藏 Azure 特定需求,例如需要一般化映像 (Sysprep)。 它可讓更進階的使用者覆寫這類需求。

  • 使用現有的映射建置管線,以取得隨選即用體驗。 您可以從管線呼叫 VM 映射產生器,或使用 Azure VM 映射產生器服務 DevOps 工作。

  • 從各種來源擷取自定義數據,以移除從一個位置收集所有自定義數據的需求。

  • 與 Azure 計算資源庫整合,其會建立映像管理系統,以全域散發、復寫、版本設定和調整映像。 此外,您可以將產生的映像散發為虛擬硬碟或一或多個受控映像,而不需要從頭重建它們。

重要

Microsoft Dev Box 僅支援使用已啟用信任啟動安全性類型的映像。

必要條件

若要布建您使用 VM 映射產生器建立的自訂映像,您需要:

  • Azure PowerShell 6.0 或更新版本。 如果您沒有安裝 PowerShell,請遵循在 Windows 上安裝 Azure PowerShell 中的步驟。
  • Azure 訂用帳戶或特定資源群組的擁有者或參與者許可權。
  • 資源群組。
  • 具有連結網路連線的開發人員中心。 如果您沒有開發人員方塊中的步驟,請設定網路連線,以遵循 連線 開發方塊中的步驟。

第一個步驟是使用 Azure VM 映射產生器與 Azure PowerShell 在 Azure 計算資源庫中建立映像版本,然後全域散發映像。 您也可以使用 Azure CLI 來執行這項工作。

  1. 若要使用 VM 映射產生器,您需要註冊功能。

    檢查您的提供者註冊。 請確定每個指令都會針對指定的功能傳 Registered 回 。

       Get-AzResourceProvider -ProviderNamespace Microsoft.VirtualMachineImages | Format-table -Property ResourceTypes,RegistrationState 
       Get-AzResourceProvider -ProviderNamespace Microsoft.Storage | Format-table -Property ResourceTypes,RegistrationState  
       Get-AzResourceProvider -ProviderNamespace Microsoft.Compute | Format-table -Property ResourceTypes,RegistrationState 
       Get-AzResourceProvider -ProviderNamespace Microsoft.KeyVault | Format-table -Property ResourceTypes,RegistrationState 
       Get-AzResourceProvider -ProviderNamespace Microsoft.Network | Format-table -Property ResourceTypes,RegistrationState 
    

    如果提供者註冊未傳回 Registered,請執行下列命令來註冊提供者:

       Register-AzResourceProvider -ProviderNamespace Microsoft.VirtualMachineImages  
       Register-AzResourceProvider -ProviderNamespace Microsoft.Storage  
       Register-AzResourceProvider -ProviderNamespace Microsoft.Compute  
       Register-AzResourceProvider -ProviderNamespace Microsoft.KeyVault  
       Register-AzResourceProvider -ProviderNamespace Microsoft.Network 
    
  2. 安裝 PowerShell 模組:

    'Az.ImageBuilder', 'Az.ManagedServiceIdentity' | ForEach-Object {Install-Module -Name $_ -AllowPrerelease}
    
  3. 建立變數來儲存您多次使用的資訊。

    1. 複製下列範例程序代碼。
    2. 將取代 <Resource group> 為您用來建立開發人員中心的資源群組。
    3. 在 PowerShell 中執行更新的程式代碼。
    # Get existing context 
    $currentAzContext = Get-AzContext
    
    # Get your current subscription ID  
    $subscriptionID=$currentAzContext.Subscription.Id
    
    # Destination image resource group  
    $imageResourceGroup="<Resource group>"
    
    # Location  
    $location="eastus2"
    
    # Image distribution metadata reference name  
    $runOutputName="aibCustWinManImg01"
    
    # Image template name  
    $imageTemplateName="vscodeWinTemplate"  
    
  4. 在 PowerShell 中執行下列程式代碼,以建立使用者指派的身分識別,並設定資源群組的許可權。

    VM 映射產生器會使用所提供的使用者身分識別,將映像插入 Azure 計算資源庫。 下列範例會建立具有散發映像的特定動作的 Azure 角色定義。 然後,角色定義會指派給使用者身分識別。

    # Set up role definition names, which need to be unique 
    $timeInt=$(get-date -UFormat "%s") 
    $imageRoleDefName="Azure Image Builder Image Def"+$timeInt 
    $identityName="aibIdentity"+$timeInt 
    
    # Add an Azure PowerShell module to support AzUserAssignedIdentity 
    Install-Module -Name Az.ManagedServiceIdentity 
    
    # Create an identity 
    New-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName -Location $location
    
    $identityNameResourceId=$(Get-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName).Id 
    $identityNamePrincipalId=$(Get-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName).PrincipalId
    
  5. 指派身分識別的許可權以散發映像。

    使用此指令來下載 Azure 角色定義樣本,然後使用先前指定的參數加以更新:

    $aibRoleImageCreationUrl="https://raw.githubusercontent.com/azure/azvmimagebuilder/master/solutions/12_Creating_AIB_Security_Roles/aibRoleImageCreation.json" 
    $aibRoleImageCreationPath = "aibRoleImageCreation.json" 
    
    # Download the configuration 
    Invoke-WebRequest -Uri $aibRoleImageCreationUrl -OutFile $aibRoleImageCreationPath -UseBasicParsing 
    ((Get-Content -path $aibRoleImageCreationPath -Raw) -replace '<subscriptionID>',$subscriptionID) | Set-Content -Path $aibRoleImageCreationPath 
    ((Get-Content -path $aibRoleImageCreationPath -Raw) -replace '<rgName>', $imageResourceGroup) | Set-Content -Path $aibRoleImageCreationPath 
    ((Get-Content -path $aibRoleImageCreationPath -Raw) -replace 'Azure Image Builder Service Image Creation Role', $imageRoleDefName) | Set-Content -Path $aibRoleImageCreationPath 
    
    # Create a role definition 
    New-AzRoleDefinition -InputFile  ./aibRoleImageCreation.json
    
    # Grant the role definition to the VM Image Builder service principal 
    New-AzRoleAssignment -ObjectId $identityNamePrincipalId -RoleDefinitionName $imageRoleDefName -Scope "/subscriptions/$subscriptionID/resourceGroups/$imageResourceGroup" 
    

若要搭配 Azure 計算資源庫使用 VM 映射產生器,您需要有現有的資源庫和映像定義。 VM 映射產生器不會為您建立資源庫和映像定義。

  1. 執行下列命令來建立新的資源庫和映像定義。

    此程式代碼會建立具有 受信任啟動 安全性類型的定義,並符合 Windows 365 映像需求。

    # Gallery name 
    $galleryName= "devboxGallery" 
    
    # Image definition name 
    $imageDefName ="vscodeImageDef" 
    
    # Additional replication region 
    $replRegion2="eastus" 
    
    # Create the gallery 
    New-AzGallery -GalleryName $galleryName -ResourceGroupName $imageResourceGroup -Location $location 
    
    $SecurityType = @{Name='SecurityType';Value='TrustedLaunch'} 
    $features = @($SecurityType) 
    
    # Create the image definition
    New-AzGalleryImageDefinition -GalleryName $galleryName -ResourceGroupName $imageResourceGroup -Location $location -Name $imageDefName -OsState generalized -OsType Windows -Publisher 'myCompany' -Offer 'vscodebox' -Sku '1-0-0' -Feature $features -HyperVGeneration "V2" 
    
  2. 建立檔案來儲存範本定義,例如 c:/temp/mytemplate.txt。

  3. 將 VM Image Builder 的下列 Azure Resource Manger 範本複製到新的範本檔案中。

    此範本會指出已套用的來源映像和自定義。 它會安裝 Choco 和 VS Code,也會指出映像發佈位置。

    {
       "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
       "contentVersion": "1.0.0.0",
       "parameters": {
         "imageTemplateName": {
          "type": "string"
         },
         "api-version": {
          "type": "string"
         },
         "svclocation": {
          "type": "string"
         }
       },
       "variables": {},
       "resources": [
         {
          "name": "[parameters('imageTemplateName')]",
          "type": "Microsoft.VirtualMachineImages/imageTemplates",
          "apiVersion": "[parameters('api-version')]",
          "location": "[parameters('svclocation')]",
          "dependsOn": [],
          "tags": {
            "imagebuilderTemplate": "win11multi",
            "userIdentity": "enabled"
          },
          "identity": {
            "type": "UserAssigned",
            "userAssignedIdentities": {
             "<imgBuilderId>": {}
            }
          },
          "properties": {
            "buildTimeoutInMinutes": 100,
            "vmProfile": {
             "vmSize": "Standard_DS2_v2",
             "osDiskSizeGB": 127
            },
          "source": {
             "type": "PlatformImage",
             "publisher": "MicrosoftWindowsDesktop",
             "offer": "Windows-11",
             "sku": "win11-21h2-ent",
             "version": "latest"
          },
            "customize": [
             {
                "type": "PowerShell",
                "name": "Install Choco and Vscode",
                "inline": [
                   "Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))",
                   "choco install -y vscode"
                ]
             }
            ],
             "distribute": 
             [
                {   
                   "type": "SharedImage",
                   "galleryImageId": "/subscriptions/<subscriptionID>/resourceGroups/<rgName>/providers/Microsoft.Compute/galleries/<sharedImageGalName>/images/<imageDefName>",
                   "runOutputName": "<runOutputName>",
                   "artifactTags": {
                      "source": "azureVmImageBuilder",
                      "baseosimg": "win11multi"
                   },
                   "replicationRegions": [
                     "<region1>",
                     "<region2>"
                   ]
                }
             ]
          }
         }
       ]
      }
    

    在繼續進行下一個步驟之前,請先關閉範本檔案。

  4. 使用變數設定新的範本。

    <Template Path>取代為樣本檔案的位置,例如 c:/temp/mytemplate

    $templateFilePath = <Template Path>
    
    (Get-Content -path $templateFilePath -Raw ) -replace '<subscriptionID>',$subscriptionID | Set-Content -Path $templateFilePath 
    (Get-Content -path $templateFilePath -Raw ) -replace '<rgName>',$imageResourceGroup | Set-Content -Path $templateFilePath 
    (Get-Content -path $templateFilePath -Raw ) -replace '<runOutputName>',$runOutputName | Set-Content -Path $templateFilePath  
    (Get-Content -path $templateFilePath -Raw ) -replace '<imageDefName>',$imageDefName | Set-Content -Path $templateFilePath  
    (Get-Content -path $templateFilePath -Raw ) -replace '<sharedImageGalName>',$galleryName| Set-Content -Path $templateFilePath  
    (Get-Content -path $templateFilePath -Raw ) -replace '<region1>',$location | Set-Content -Path $templateFilePath  
    (Get-Content -path $templateFilePath -Raw ) -replace '<region2>',$replRegion2 | Set-Content -Path $templateFilePath  
    ((Get-Content -path $templateFilePath -Raw) -replace '<imgBuilderId>',$identityNameResourceId) | Set-Content -Path $templateFilePath 
    
  5. 將您的範本提交至服務。

    下列命令會下載任何相依成品,例如腳本,並將其儲存在預備資源群組中。 預備資源群組前面會加上 IT_

    New-AzResourceGroupDeployment  -ResourceGroupName $imageResourceGroup  -TemplateFile $templateFilePath  -Api-Version "2020-02-14"  -imageTemplateName $imageTemplateName  -svclocation $location 
    
  6. 在樣本上叫用 Run 命令來建置映像:

    在確認執行程式的提示中,輸入 [是]。

    Invoke-AzResourceAction  -ResourceName $imageTemplateName  -ResourceGroupName $imageResourceGroup  -ResourceType Microsoft.VirtualMachineImages/imageTemplates  -ApiVersion "2020-02-14"  -Action Run
    

    重要

    建立映像並將其復寫至這兩個區域可能需要一些時間。 您可能會在 PowerShell 與 Azure 入口網站 之間看到進行中報告的差異。 開始建立開發方塊定義之前,請等候程式完成。

  7. 取得新建置映像的相關信息,包括執行狀態和布建狀態。

    Get-AzImageBuilderTemplate -ImageTemplateName $imageTemplateName -ResourceGroupName $imageResourceGroup | Select-Object -Property Name, LastRunStatusRunState, LastRunStatusMessage, ProvisioningState 
    

    範例輸出:

    Name                 LastRunStatusRunState    LastRunStatusMessage   ProvisioningState
    ---------------------------------------------------------------------------------------
    vscodeWinTemplate                                                    Creating
    

    您也可以在 Azure 入口網站 中檢視映射的布建狀態。 移至您的資源庫並檢視影像定義。

    Screenshot that shows the provisioning state of the customized image version.

在資源庫中布建自定義映射之後,您可以將資源庫設定為使用開發人員中心中的映像。 如需詳細資訊,請參閱 設定 Azure 計算資源庫

使用自定義映像設定 Microsoft Dev Box

在開發人員中心提供資源庫映射之後,您可以搭配 Microsoft Dev Box 使用自定義映射。 如需詳細資訊,請參閱 快速入門:設定 Microsoft Dev Box