共用方式為


使用 Azure VM Image Builder 和 Microsoft 開發箱設定開發箱

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

如果您的組織使用標準化虛擬機器 (VM) 映像,則可以更輕鬆地移轉至雲端,並協助確保部署中的一致性。 映像通常包含預先定義的安全性、組態設定,以及任何必要的軟體。 安裝屬於您的映像管線需要時間、基礎結構和許多其他詳細資料。 使用 Azure VM Image Builder,您可以建立描述映像的組態。 服務接著會建置映像,並將其提交至開發箱專案。

雖然您可以藉由手動或使用其他工具建立自訂 VM 映像,但整個流程可能相當繁瑣且不可靠。 組建在 HashiCorp Packer 上的 VM Image Builder 則提供了受控服務特有的優點。

為了減少建立 VM 映像的複雜性,VM Image Builder:

  • 免除使用複雜工具、流程和手動步驟建立 VM 映像的必要性。 VM Image Builder 會將這些詳細資料全部抽象化,並隱藏 Azure 特定需求,例如將映像一般化 (Sysprep) 的需求。 並且能讓更進階的使用者覆寫這類需求。

  • 使用現有的映像組建管線,達成隨選即用的體驗。 可以從管線呼叫 VM Image Builder,或使用 Azure VM Image Builder 服務 DevOps 工作。

  • 從各種來源擷取自訂資料,便無須從單一位置收集自訂資料。

  • 與 Azure Compute Gallery 整合,這會建立映像管理系統,以全域散發、復寫、版本設定和調整映像。 此外,您可以將相同的產生映像作為虛擬硬碟,或是作為一個或多個受控映像散發,而無須從頭重建。

重要

Microsoft 開發箱僅支援使用已啟用 [可信啟動] 安全性類型的映像。

必要條件

若要布建您使用 VM Image Builder 建立的自訂映像,您需要:

第一個步驟是使用 Azure VM Image Builder 與 Azure PowerShell 在 Azure Compute Gallery 中建立映像版本,然後全域散發映像。 您也可以使用 Azure CLI 來執行此工作。

  1. 若要使用 VM Image Builder,您必須註冊該功能。

    檢查您的提供者註冊。 請確定每個指令都會針對指定功能傳回 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 Image Builder 會使用所提供的使用者身分識別,將映像插入 Azure Compute Gallery。 下列範例會建立具有特定動作的 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 Compute Gallery 和 VM Image Builder,您需要有現有的資源庫和映像定義。 VM Image Builder 不會為您建立資源庫和映像定義。

  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 命令來建置映像:

    在確認執行程式的提示字元中,輸入「Yes」。

    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 Compute Gallery

使用自訂映像設定 Microsoft 開發箱

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