建立 Linux 映像檔,並使用 Azure CLI 將其分發到 Azure Compute Gallery

適用於:✔️ Linux 虛擬機 ✔️ 彈性規模設定

在本文中,你將學習如何使用 Azure VM Image Builder 和 Azure CLI 在 Azure Compute Gallery (前稱 Shared Image Gallery)中建立映像版本,然後將映像檔全球分發。 你也可以使用 Azure PowerShell 建立映像版本。

本文使用範例 JSON 範本來配置影像。 JSON 檔案在 helloImageTemplateforSIG.json

要將影像分發到 Azure Compute Gallery,範本會使用 sharedImage 作為範本區 distribute 段的值。

註冊提供者

要使用 VM Image Builder,你需要註冊提供者。 請執行以下指令檢查您的註冊:

az provider show -n Microsoft.VirtualMachineImages -o json | grep registrationState
az provider show -n Microsoft.KeyVault -o json | grep registrationState
az provider show -n Microsoft.Compute -o json | grep registrationState
az provider show -n Microsoft.Storage -o json | grep registrationState
az provider show -n Microsoft.Network -o json | grep registrationState
az provider show -n Microsoft.ContainerInstance -o json | grep registrationState

如果輸出沒有顯示 已註冊,請執行以下指令:

az provider register -n Microsoft.VirtualMachineImages
az provider register -n Microsoft.Compute
az provider register -n Microsoft.KeyVault
az provider register -n Microsoft.Storage
az provider register -n Microsoft.Network
az provider register -n Microsoft.ContainerInstance

設定變數與權限

因為你會重複使用某些資訊片段,可以建立一些變數來儲存這些資訊。

VM Image Builder 僅支援在與原始碼管理映像檔相同的資源群組中建立自訂映像檔。 以下範例中,將資源群組名稱更新為與你原始碼管理映像相同的資料群組。

# Resource group name - ibLinuxGalleryRG in this example
sigResourceGroup=ibLinuxGalleryRG
# Datacenter location - West US 2 in this example
location=westus2
# Additional region to replicate the image to - East US in this example
additionalregion=eastus
# Name of the Azure Compute Gallery - myGallery in this example
sigName=myIbGallery
# Name of the image definition to be created - myImageDef in this example
imageDefName=myIbImageDef
# Reference name in the image distribution metadata
runOutputName=aibLinuxSIG

建立一個訂閱 ID 變數:

subscriptionID=$(az account show --query id --output tsv)

建立資源小組:

az group create -n $sigResourceGroup -l $location

建立使用者指派的身份,並在資源群組上設定權限

VM Image Builder 會利用所提供的 使用者身份 ,將影像注入 Azure Compute Gallery。 在這個範例中,你建立一個 Azure 角色定義,並包含專門分發映像的動作。 然後此將角色定義指派給使用者身分識別。

以下指令的成功取決於 RBAC 傳播,有時可能需要長達 ~ 30 分鐘。 執行指令前大約等 5 分鐘,如果發生錯誤再延遲再試一次。

# Create user-assigned identity for VM Image Builder to access the storage account where the script is stored
identityName=aibBuiUserId$(date +'%s')
az identity create -g $sigResourceGroup -n $identityName

# Get the identity ID
imgBuilderCliId=$(az identity show -g $sigResourceGroup -n $identityName --query clientId -o tsv)

# Get the user identity URI that's needed for the template
imgBuilderId=/subscriptions/$subscriptionID/resourcegroups/$sigResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/$identityName

# Download an Azure role-definition template, and update the template with the parameters that were specified earlier
curl https://raw.githubusercontent.com/Azure/azvmimagebuilder/master/solutions/12_Creating_AIB_Security_Roles/aibRoleImageCreation.json -o aibRoleImageCreation.json

imageRoleDefName="Azure Image Builder Image Def"$(date +'%s')

# Update the definition
sed -i -e "s/<subscriptionID>/$subscriptionID/g" aibRoleImageCreation.json
sed -i -e "s/<rgName>/$sigResourceGroup/g" aibRoleImageCreation.json
sed -i -e "s/Azure Image Builder Service Image Creation Role/$imageRoleDefName/g" aibRoleImageCreation.json

# Create role definitions
az role definition create --role-definition ./aibRoleImageCreation.json

# Grant a role definition to the user-assigned identity. The success of the following command relies on RBAC propagation, which can take up to ~30 minutes.  Wait about 5 minutes before running the command and wait a few more minutes before retrying if you get an error.  

az role assignment create \
    --assignee $imgBuilderCliId \
    --role "$imageRoleDefName" \
    --scope /subscriptions/$subscriptionID/resourceGroups/$sigResourceGroup

要使用 VM Image Builder 搭配 Azure Compute Gallery,你需要有現有的圖庫和圖片定義。 VM Image Builder 不會為您建立資源庫和映像定義。

如果你還沒有圖庫和圖片定義可以用,可以先建立它們。

首先,建立一個畫廊:

az sig create \
    -g $sigResourceGroup \
    --gallery-name $sigName

接著,建立一個影像定義:

az sig image-definition create \
   -g $sigResourceGroup \
   --gallery-name $sigName \
   --gallery-image-definition $imageDefName \
   --publisher myIbPublisher \
   --offer myOffer \
   --sku 20_04-lts-gen2 \
   --os-type Linux \
   --hyper-v-generation V2 \
   --features SecurityType=TrustedLaunchSupported

下載並設定 JSON 檔案

下載 JSON 範本,並用你的變數來配置:

curl https://raw.githubusercontent.com/Azure/azvmimagebuilder/master/quickquickstarts/1_Creating_a_Custom_Linux_Shared_Image_Gallery_Image/helloImageTemplateforSIG.json -o helloImageTemplateforSIG.json
sed -i -e "s/<subscriptionID>/$subscriptionID/g" helloImageTemplateforSIG.json
sed -i -e "s/<rgName>/$sigResourceGroup/g" helloImageTemplateforSIG.json
sed -i -e "s/<imageDefName>/$imageDefName/g" helloImageTemplateforSIG.json
sed -i -e "s/<sharedImageGalName>/$sigName/g" helloImageTemplateforSIG.json
sed -i -e "s/<region1>/$location/g" helloImageTemplateforSIG.json
sed -i -e "s/<region2>/$additionalregion/g" helloImageTemplateforSIG.json
sed -i -e "s/<runOutputName>/$runOutputName/g" helloImageTemplateforSIG.json
sed -i -e "s%<imgBuilderId>%$imgBuilderId%g" helloImageTemplateforSIG.json
sed -i -e "s/sudo mkdir/sleep 300;sudo mkdir/g" helloImageTemplateforSIG.json

建立映像版本

在這個區塊中,你可以在圖庫中建立圖片版本。

將映像設定提交至 Azure VM Image Builder 服務:

az resource create \
    --resource-group $sigResourceGroup \
    --properties @helloImageTemplateforSIG.json \
    --is-full-object \
    --resource-type Microsoft.VirtualMachineImages/imageTemplates \
    -n helloImageTemplateforSIG01

開始建構映像:

az resource invoke-action \
     --resource-group $sigResourceGroup \
     --resource-type  Microsoft.VirtualMachineImages/imageTemplates \
     -n helloImageTemplateforSIG01 \
     --action Run

製作影像並複製到兩個區域可能需要幾分鐘。 等這部分完成後再開始建立虛擬機。

建立 VM

用 VM Image Builder 建立的映像版本建立虛擬機。

az vm create \
  --resource-group $sigResourceGroup \
  --name myAibGalleryVM \
  --admin-username aibuser \
  --location $location \
  --image "/subscriptions/$subscriptionID/resourceGroups/$sigResourceGroup/providers/Microsoft.Compute/galleries/$sigName/images/$imageDefName/versions/latest" \
  --security-type TrustedLaunch \
  --generate-ssh-keys

透過安全殼層(SSH)連接虛擬機:

ssh aibuser@<publicIpAddress>

一旦您的 SSH 連線建立,您應該會看到影像已經自訂了每日訊息

*******************************************************
**            This VM was built from the:            **
**      !! AZURE VM IMAGE BUILDER Custom Image !!    **
**         You have just been Customized :-)         **
*******************************************************

清除資源

備註

如果你現在想嘗試重新自訂映像檔版本以建立同一映像檔的新版本,請 跳過這裡列出的步驟 ,直接到 VM Image Builder 建立另一個影像版本

如果您不再需要依照本文流程建立的資源,可以透過以下步驟刪除它們。

這個過程會刪除你建立的圖片以及所有其他資源檔案。 刪除資源前,務必完成這次部署。

當你刪除畫廊資源時,必須先刪除所有圖片版本,才能刪除用來建立它們的圖片定義。 要刪除圖庫,首先你需要刪除該圖庫中所有的圖片定義。

  1. 刪除 VM Image Builder 範本。

    az resource delete \
        --resource-group $sigResourceGroup \
        --resource-type Microsoft.VirtualMachineImages/imageTemplates \
        -n helloImageTemplateforSIG01
    
  2. 刪除權限、指派、角色和身份。

    az role assignment delete \
        --assignee $imgBuilderCliId \
        --role "$imageRoleDefName" \
        --scope /subscriptions/$subscriptionID/resourceGroups/$sigResourceGroup
    
    az role definition delete --name "$imageRoleDefName"
    
    az identity delete --ids $imgBuilderId
    
  3. 取得由 VM Image Builder 建立的映像檔(它總是以 0.) 開頭,然後刪除它。

    sigDefImgVersion=$(az sig image-version list \
    -g $sigResourceGroup \
    --gallery-name $sigName \
    --gallery-image-definition $imageDefName \
    --subscription $subscriptionID --query [].'name' -o json | grep 0. | tr -d '"')
    az sig image-version delete \
    -g $sigResourceGroup \
    --gallery-image-version $sigDefImgVersion \
    --gallery-name $sigName \
    --gallery-image-definition $imageDefName \
    --subscription $subscriptionID
    
  4. 刪除圖片定義。

    az sig image-definition delete \
    -g $sigResourceGroup \
    --gallery-name $sigName \
    --gallery-image-definition $imageDefName \
    --subscription $subscriptionID
    
  5. 刪除相簿。

    az sig delete -r $sigName -g $sigResourceGroup
    
  6. 刪除資源群組。

    az group delete -n $sigResourceGroup -y
    

下一步

了解更多關於 Azure Compute Gallery 的資訊。