次の方法で共有


Azure VM Image Builder を使用して開発ボックス イメージを作成する

この記事では、Azure VM Image Builder テンプレートを使用して、Azure コンピューティング ギャラリーでカスタマイズされた VM イメージを作成し、グローバルに配布する方法について説明します。 その後、このイメージを使用して、Microsoft Dev Box で開発ボックスを作成できます。

標準化された VM イメージは、定義済みのセキュリティ、構成、およびソフトウェアを含めることで、一貫した開発ボックスデプロイを保証するのに役立ちます。 ただし、イメージング パイプラインを手動で設定するのは時間がかかり、複雑であり、カスタム仮想マシン (VM) イメージの作成は困難で信頼性が低い場合があります。

Azure VM Image Builder は、開発ボックス用の VM イメージの作成とビルドのプロセスを簡略化する HashiCorp Packer に基づくマネージド サービスです。 この記事の Image Builder テンプレートには、Visual Studio Code と Chocolatey をインストールするカスタマイズ手順が含まれています。

VM イメージ ビルダーでは、次のことができます。

  • 手動の手順または複雑なツールとプロセスを抽象化し、Azure 固有のニーズを隠します。 たとえば、 sysprep を実行してイメージを一般化しますが、上級ユーザーがオーバーライドできるようにします。
  • 既存のイメージ ビルド パイプラインを操作します。 パイプラインから VM Image Builder を呼び出すか、Azure Pipelines で Azure VM Image Builder サービス タスクを使用できます。
  • さまざまなソースからカスタマイズ データを収集するため、自分で収集する必要はありません。
  • Azure Compute Gallery と統合して、グローバル分散、レプリケーション、バージョン管理、スケーリングのためのイメージ管理システムを作成します。 イメージを再構築せずに、仮想ハード ディスクとマネージド イメージの両方として配布できます。

重要

Microsoft Dev Box では、 信頼できる起動 セキュリティの種類を使用するイメージのみがサポートされます。

前提条件

この記事の例では、Azure PowerShell を使用します。 Azure CLI を使用することもできます。

カテゴリ Requirements
ツールとアクセス許可 所有者または共同作成者のアクセス許可を持つ Azure リソース グループ。
Tools Azure PowerShell 6.0 以降がインストールされています。 手順については、「 Windows に Azure PowerShell をインストールする」を参照してください。

ツールとロールを設定する

ツールとロールを設定するには、次の手順を実行します。

  1. 必要な Azure PowerShell モジュールをインストールします。
  2. 複数回使用する情報の変数を設定します。
  3. 必要な Azure リソース プロバイダーを登録します。
  4. リソース グループのユーザー ID を作成し、イメージの配布を許可するロールを割り当てます。

PowerShell モジュールをインストールする

次のコマンドを実行して、必要な PowerShell モジュールをインストールします。

'Az.ImageBuilder', 'Az.ManagedServiceIdentity' | ForEach-Object {Install-Module -Name $_ -AllowPrerelease}

信頼されていないリポジトリに関するプロンプトに Y を応答します。

変数を設定する

複数回使用する情報を格納する変数を作成します。 次のコードを実行し、 <resource-group> をリソース グループ名に置き換え、 <location> を使用する Azure リージョンに置き換えます。

# Get existing context 
$currentAzContext = Get-AzContext

# Get your current subscription ID  
$subscriptionID=$currentAzContext.Subscription.Id

# Destination image resource group  
$imageResourceGroup="<resource-group>"

# Location
$location="<location>"

# Image distribution metadata reference name  
$runOutputName="aibCustWinManImg01"

# Image template name  
$imageTemplateName="vscodeWinTemplate"  

Azure リソース プロバイダーを登録する

VM Image Builder を使用するには、次の Azure リソース プロバイダーを登録する必要があります。

  • Microsoft.VirtualMachineImages
  • Microsoft.Compute
  • Microsoft.Network
  • Microsoft.Storage
  • Microsoft.KeyVault
  • Microsoft.ContainerInstance
  1. 次のコマンドを実行して、プロバイダーの登録を確認します。

      Get-AzResourceProvider -ProviderNamespace "Microsoft.VirtualMachineImages", "Microsoft.Compute", "Microsoft.Network", "Microsoft.Storage", "Microsoft.KeyVault", "Microsoft.ContainerInstance" | Format-table -Property ProviderNamespace,RegistrationState
    
  2. プロバイダー登録のいずれかが Registeredを返さない場合は、 Register-AzResourceProvider コマンドを実行してプロバイダーを登録します。 次の例では、 Microsoft.VirtualMachineImages リソース プロバイダーを登録します。

      Register-AzResourceProvider -ProviderNamespace Microsoft.VirtualMachineImages
    

ユーザー ID を作成して割り当てる

イメージの配布を許可する Azure ロール定義を作成します。 次に、リソース グループのユーザー割り当て ID を作成し、ロールをユーザー ID に割り当てます。 VM Image Builder では、ユーザー ID を使用して Azure コンピューティング ギャラリーにイメージを格納します。

  1. 次のコードを実行して、Azure ロール定義とユーザー ID を作成します。

    # Set up a unique role definition name
    $timeInt=$(get-date -UFormat "%s") 
    $imageRoleDefName="Azure Image Builder Image Def"+$timeInt 
    $identityName="aibIdentity"+$timeInt 
    
    # 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
    
  2. 次のコードを実行して、イメージの配布を許可する Azure ロール定義テンプレートをダウンロードし、パラメーターを使用してテンプレートを更新し、ロールをユーザー ID に割り当てます。

    $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 Image Builder を使用するには、ギャラリーとイメージ定義が必要です。 次の手順では、新しいギャラリーとイメージ定義を作成し、VM Image Builder テンプレートをカスタマイズします。

  1. 次のコマンドを実行して、Windows 365 イメージに必要な信頼された起動セキュリティの種類を持つ新しいギャラリーとイメージ定義を作成します。

    # Gallery name 
    $galleryName= "devboxGallery" 
    
    # Image definition name 
    $imageDefName ="vscodeImageDef" 
    
    # Second 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. VM Image Builder 用の次の Azure Resource Manager テンプレートをコピーして、新しいファイルに貼り付けます。 ファイルを c:\temp\mytemplate.js などの場所に保存し、ファイルを閉じます。

    テンプレートは、適用されるソース イメージとカスタマイズを定義し、Chocolatey と Visual Studio 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 VS Code",
                "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>"
                   ]
                }
             ]
          }
         }
       ]
      }
    
  3. 次のコードを実行して、新しいテンプレートを設定に構成し、 <template-location> をテンプレート ファイルの場所と名前に置き換えます。

    $templateFilePath = "<template-location>"
    
    (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 
    

イメージをビルドして表示する

カスタマイズしたテンプレートを VM Image Builder サービスに送信し、イメージをビルドします。

  1. 次のコマンドを実行して、テンプレートをサービスに送信します。 このコマンドは、スクリプトなどの依存成果物をダウンロードし、 IT_のプレフィックスが付いたステージング リソース グループに格納します。

    New-AzResourceGroupDeployment  -ResourceGroupName $imageResourceGroup  -TemplateFile $templateFilePath  -Api-Version "2020-02-14"  -imageTemplateName $imageTemplateName  -svclocation $location 
    
  2. テンプレートで Run アクションを呼び出して、イメージをビルドします。 確認プロンプトで、Yes」と入力します。

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

重要

イメージを作成して 2 つのリージョンにレプリケートするには、しばらく時間がかかる場合があります。 PowerShell と Azure portal の間で、異なる進行状況レポートが表示される場合があります。 プロセスが完了するまで待ってから、イメージから開発ボックス定義の作成を開始します。

画像に関する情報を取得する

次のコマンドを実行して、実行状態やプロビジョニング状態など、新しくビルドされたイメージに関する情報を取得します。

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

サンプル出力:

Name              LastRunStatusRunState LastRunStatusMessage ProvisioningState
----              --------------------- -------------------- -----------------
vscodeWinTemplate Running                                    Succeeded

Azure portal でイメージのプロビジョニング状態を確認することもできます。 ギャラリーに移動して、イメージ定義を表示します。

カスタマイズされたイメージ バージョンのプロビジョニング状態を示すスクリーンショット。

カスタム イメージがギャラリーに格納されたら、Microsoft Dev Box デベロッパー センターでそのイメージを使用するようにギャラリーを構成できます。 詳細については、「 Azure Compute Gallery for Microsoft Dev Box の構成」を参照してください。

デベロッパー センターでギャラリー イメージを使用できるようにするには、カスタム イメージを開発ボックス プロジェクトにアタッチし、それを使用して開発ボックスを作成します。 詳細については、「クイックスタート: Microsoft Dev Box を構成する」を参照してください。