使用 PowerShell 透過 VM Image Builder 建立 Windows VM

適用於:✔️ Windows VM

本文示範如何使用 Azure Image Builder PowerShell 模組來建立自訂的 Windows VM 映像。

必要條件

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

如果您選擇在本機使用 PowerShell,本文會要求您安裝 Azure PowerShell 模組,並使用 Connect-AzAccount Cmdlet 連線到您的 Azure 帳戶。 如需詳細資訊,請參閱安裝 Azure PowerShell (英文)。

某些步驟需要 Az.ImageBuilder 模組中的 Cmdlet。 使用下列命令個別安裝。

Install-Module -Name Az.ImageBuilder

Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。 您可以使用 Bash 或 PowerShell 搭配 Cloud Shell,與 Azure 服務共同使用。 您可以使用 Cloud Shell 預先安裝的命令,執行本文提到的程式碼,而不必在本機環境上安裝任何工具。

要啟動 Azure Cloud Shell:

選項 範例/連結
選取程式碼或命令區塊右上角的 [試試看]。 選取 [試試看] 並不會自動將程式碼或命令複製到 Cloud Shell 中。 Azure Cloud Shell 的「試試看」範例螢幕擷取畫面。
請前往 https://shell.azure.com,或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。 啟動 Azure Cloud Shell 的按鈕。
選取 Azure 入口網站右上方功能表列上的 [Cloud Shell] 按鈕。 顯示 Azure 入口網站中 Cloud Shell 按鈕的螢幕擷取畫面

若要使用 Azure Cloud Shell:

  1. 啟動 Cloud Shell。

  2. 選取程式碼區塊 (或命令區塊) 上的 [複製] 按鈕以複製程式碼或命令。

  3. 透過在 Windows 和 Linux 上選取 Ctrl+Shift+V;或在 macOS 上選取 Cmd+Shift+V,將程式碼或命令貼到 Cloud Shell 工作階段中。

  4. 選取 Enter 鍵執行程式碼或命令。

如果您有多個 Azure 訂用帳戶,請選擇資源計費的適當訂用帳戶。 使用 Set-AzContext Cmdlet 來選取特定的訂用帳戶。

Set-AzContext -SubscriptionId 00000000-0000-0000-0000-000000000000

註冊提供者

如果您尚未這麼做,請註冊下列資源提供者以搭配您的 Azure 訂用帳戶使用:

  • Microsoft.Compute
  • Microsoft.KeyVault
  • Microsoft.Storage
  • Microsoft.Network
  • Microsoft.VirtualMachineImages
  • Microsoft.ManagedIdentity
  • Microsoft.ContainerInstance
Get-AzResourceProvider -ProviderNamespace Microsoft.Compute, Microsoft.KeyVault, Microsoft.Storage, Microsoft.VirtualMachineImages, Microsoft.Network, Microsoft.ManagedIdentity |
  Where-Object RegistrationState -ne Registered |
    Register-AzResourceProvider

定義變數

由於您會重複使用某些資訊,因此請建立一些變數來儲存這些資訊:

# Destination image resource group name
$imageResourceGroup = 'myWinImgBuilderRG'

# Azure region
$location = 'WestUS2'

# Name of the image to be created
$imageTemplateName = 'myWinImage'

# Distribution properties of the managed image upon completion
$runOutputName = 'myDistResults'

為您的 Azure 訂用帳戶識別碼建立變數。 若要確認 subscriptionID 變數包含您的訂用帳戶識別碼,您可以執行下列範例中的第二行:

# Your Azure Subscription ID
$subscriptionID = (Get-AzContext).Subscription.Id
Write-Output $subscriptionID

建立資源群組

使用 New-AzResourceGroup Cmdlet 來建立 Azure 資源群組。 Azure 資源群組是在其中將 Azure 資源當作群組部署及管理的邏輯容器。

下列範例會根據您在 $location 變數所指定區域的 $imageResourceGroup 變數中的名稱,建立資源群組。 此資源群組用來儲存映像組態範本成品和映像。

New-AzResourceGroup -Name $imageResourceGroup -Location $location

建立使用者身分識別並設定角色權限

使用下列範例,授與 Azure Image Builder 權限,以在指定的資源群組中建立映像。 如果沒有此權限,映像建置程序將無法順利完成。

  1. 建立角色定義和身分識別名稱的變數。 這些值不得重複。

    [int]$timeInt = $(Get-Date -UFormat '%s')
    $imageRoleDefName = "Azure Image Builder Image Def $timeInt"
    $identityName = "myIdentity$timeInt"
    
  2. 建立使用者身分識別。

    New-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName -Location $location
    
  3. 將身分識別資源和主體識別碼儲存在變數中。

    $identityNameResourceId = (Get-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName).Id
    $identityNamePrincipalId = (Get-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName).PrincipalId
    

為身分識別指派權限以散發映像

  1. 下載 JSON 組態檔,然後根據本文中定義的設定加以修改。

    $myRoleImageCreationUrl = 'https://raw.githubusercontent.com/azure/azvmimagebuilder/master/solutions/12_Creating_AIB_Security_Roles/aibRoleImageCreation.json'
    $myRoleImageCreationPath = "myRoleImageCreation.json"
    
    Invoke-WebRequest -Uri $myRoleImageCreationUrl -OutFile $myRoleImageCreationPath -UseBasicParsing
    
    $Content = Get-Content -Path $myRoleImageCreationPath -Raw
    $Content = $Content -replace '<subscriptionID>', $subscriptionID
    $Content = $Content -replace '<rgName>', $imageResourceGroup
    $Content = $Content -replace 'Azure Image Builder Service Image Creation Role', $imageRoleDefName
    $Content | Out-File -FilePath $myRoleImageCreationPath -Force
    
  2. 建立角色定義。

    New-AzRoleDefinition -InputFile $myRoleImageCreationPath
    
  3. 將角色定義授予 VM Image Builder 服務主體。

    $RoleAssignParams = @{
      ObjectId = $identityNamePrincipalId
      RoleDefinitionName = $imageRoleDefName
      Scope = "/subscriptions/$subscriptionID/resourceGroups/$imageResourceGroup"
    }
    New-AzRoleAssignment @RoleAssignParams
    

注意

如果您收到錯誤「New-AzRoleDefinition:已超出角色定義限制。 無法建立更多角色定義」,請參閱針對 Azure RBAC (角色型存取控制) 進行疑難排解

  1. 建立資源庫。

    $myGalleryName = 'myImageGallery'
    $imageDefName = 'winSvrImages'
    
    New-AzGallery -GalleryName $myGalleryName -ResourceGroupName $imageResourceGroup -Location $location
    
  2. 建立資源庫定義。

    $GalleryParams = @{
      GalleryName = $myGalleryName
      ResourceGroupName = $imageResourceGroup
      Location = $location
      Name = $imageDefName
      OsState = 'generalized'
      OsType = 'Windows'
      Publisher = 'myCo'
      Offer = 'Windows'
      Sku = 'Win2019'
    }
    New-AzGalleryImageDefinition @GalleryParams
    

建立映像

  1. 建立 VM Image Builder 來源物件。 如需有效的參數值,請參閱透過 Azure PowerShell 在 Azure Marketplace 中尋找 Windows VM 映像

    $SrcObjParams = @{
      PlatformImageSource = $true
      Publisher = 'MicrosoftWindowsServer'
      Offer = 'WindowsServer'
      Sku = '2019-Datacenter'
      Version = 'latest'
    }
    $srcPlatform = New-AzImageBuilderTemplateSourceObject @SrcObjParams
    
  2. 建立 VM Image Builder 散發者物件。

    $disObjParams = @{
      SharedImageDistributor = $true
      ArtifactTag = @{tag='dis-share'}
      GalleryImageId = "/subscriptions/$subscriptionID/resourceGroups/$imageResourceGroup/providers/Microsoft.Compute/galleries/$myGalleryName/images/$imageDefName"
      ReplicationRegion = $location
      RunOutputName = $runOutputName
      ExcludeFromLatest = $false
    }
    $disSharedImg = New-AzImageBuilderTemplateDistributorObject @disObjParams
    
  3. 建立 VM Image Builder 自訂物件。

    $ImgCustomParams01 = @{
      PowerShellCustomizer = $true
      Name = 'settingUpMgmtAgtPath'
      RunElevated = $false
      Inline = @("mkdir c:\\buildActions", "mkdir c:\\buildArtifacts", "echo Azure-Image-Builder-Was-Here  > c:\\buildActions\\buildActionsOutput.txt")
    }
    $Customizer01 = New-AzImageBuilderTemplateCustomizerObject @ImgCustomParams01
    
  4. 建立第二個 VM Image Builder 自訂物件。

    $ImgCustomParams02 = @{
      FileCustomizer = $true
      Name = 'downloadBuildArtifacts'
      Destination = 'c:\\buildArtifacts\\index.html'
      SourceUri = 'https://raw.githubusercontent.com/azure/azvmimagebuilder/master/quickquickstarts/exampleArtifacts/buildArtifacts/index.html'
    }
    $Customizer02 = New-AzImageBuilderTemplateCustomizerObject @ImgCustomParams02
    
  5. 建立 VM Image Builder 範本。

    $ImgTemplateParams = @{
      ImageTemplateName = $imageTemplateName
      ResourceGroupName = $imageResourceGroup
      Source = $srcPlatform
      Distribute = $disSharedImg
      Customize = $Customizer01, $Customizer02
      Location = $location
      UserAssignedIdentityId = $identityNameResourceId
    }
    New-AzImageBuilderTemplate @ImgTemplateParams
    

建立範本後,系統會傳回訊息,並在 $imageResourceGroup 中建立 VM Image Builder 組態範本。

若要判斷範本建立程序是否成功,請使用下列範例:

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

VM Image Builder 也會在背景中為您的訂閱建立暫存資源群組。 此資源群組會用於映像組建。 其格式為 IT_<DestinationResourceGroup>_<TemplateName>

警告

請勿直接刪除暫存資源群組。 若要致使暫存資源群組遭到刪除,請刪除映像範本成品。

如果服務在映像設定範本提交時回報失敗,請執行下列動作:

啟動映像建置

執行下列命令,將映像設定提交至 VM Image Builder 服務:

Start-AzImageBuilderTemplate -ResourceGroupName $imageResourceGroup -Name $imageTemplateName

等候映像建置程序完成,這可能需要一小時的時間。

如果您遇到錯誤,請檢閱針對 Azure VM Image Builder 失敗進行疑難排解

建立 VM

  1. 將 VM 登入認證儲存在變數中。 必須使用複雜密碼。

    $Cred = Get-Credential
    
  2. 使用您建立的映像建立 VM。

    $ArtifactId = (Get-AzImageBuilderTemplateRunOutput -ImageTemplateName $imageTemplateName -ResourceGroupName $imageResourceGroup).ArtifactId
    
    New-AzVM -ResourceGroupName $imageResourceGroup -Image $ArtifactId -Name myWinVM01 -Credential $Cred
    

確認自訂項目

  1. 使用您在建立 VM 時所設定的使用者名稱與密碼,建立與該 VM 的遠端桌面連線。

  2. 在 VM 內,開啟 PowerShell 並執行 Get-Content,如下列範例所示:

    Get-Content -Path C:\buildActions\buildActionsOutput.txt
    

    輸出是以在映像自訂過程中所建立的檔案內容為基礎。

    Azure-Image-Builder-Was-Here
    
  3. 從相同的 PowerShell 工作階段中,檢查 c:\buildArtifacts\index.html 是否存在,以確認第二個自訂已順利完成,如下列範例所示:

    Get-ChildItem c:\buildArtifacts\
    

    結果應該是目錄清單,其中顯示映像自訂流程中下載的檔案。

        Directory: C:\buildArtifacts
    
    Mode                 LastWriteTime         Length Name
    ----                 -------------         ------ ----
    -a---          29/01/2021    10:04            276 index.html
    

清除資源

如果您不再需要在此流程中建立的資源,您可執行下列動作予以刪除:

  1. 刪除 VM Image Builder 範本。

    Remove-AzImageBuilderTemplate -ResourceGroupName $imageResourceGroup -Name $imageTemplateName
    
  2. 刪除映像資源群組。

    警告

    下列範例會刪除指定的資源群組和其中包含的所有資源。 如果本文範圍以外的資源存在於資源群組中,則也會一併刪除。

    Remove-AzResourceGroup -Name $imageResourceGroup
    

下一步

若要深入了解本文中使用的 JSON 檔案元件,請參閱 VM Image Builder 範本參考