建立和部署 VM 應用程式

VM Application 是 Azure Compute Gallery 中的一種資源類型,簡化了虛擬機應用程式與腳本的發佈、部署、管理、共享及全球分發。 VM 應用程式支援多種情境,包括大規模部署、低延遲需求、故障韌性、安全的可信部署、全艦隊一致性、微服務架構及部署後管理。 了解更多關於虛擬機應用程式的資訊。

要在 Azure VM 上建立和部署應用程式,首先將應用程式打包並上傳到 Azure Storage 帳戶,作為儲存 blob。 接著建立 Azure VM application 資源和 VM application version資源,參考這些儲存塊。 Azure 會將這些 blobs 儲存並複製到區域管理的儲存帳號中。 最後,透過 applicationProfile 傳遞應用程式參照,將該應用程式部署至任何虛擬機或虛擬機器規模設定。

圖表顯示發佈與部署虛擬機器應用程式的逐步流程。

必要條件

  1. 建立 Azure storage account 和 storage container。 此容器可用來上傳您的應用程式檔案。
  2. 建立 Azure 計算圖庫用於儲存與分享應用程式資源。
  3. 建立 user-assigned managed identity 並將其分配至 Azure Compute Gallery

備註

請在關閉匿名存取後建立儲存帳號以提升安全性。 使用指派給 Azure Compute Gallery 的 受控身分識別,安全發佈你的虛擬機應用程式,無需 SAS 代幣。

封裝應用程式

在將 VM Application 資源發佈到 Azure Compute Gallery 之前,先將應用程式檔案打包好,然後上傳到 Azure Storage 帳號。 下圖顯示了用於組織應用程式檔案的可能資料夾結構:

螢幕擷取畫面顯示建議用於上傳和建立 VM 應用程式的資料夾結構。

1.打包應用程式檔案

VM 應用程式需要一個單一檔案作為應用程式套件。

  • 如果你的應用程式安裝需要單一可執行檔(.exe、.msi、.sh、.ps 等),那你可以把它當作應用程式套件使用。
  • 如果你的應用程式需要多個檔案(可執行檔、相依、腳本、元資料等),請將它們歸檔成一個檔案(, , ),並以此檔案作為應用程式套件使用。
  • 對於微服務應用程式,你可以將每個微服務打包並發佈為獨立的 Azure VM 應用程式。 這種模組化促進了應用程式的重用性、跨團隊開發,以及利用 applicationProfile 中的屬性順序安裝微服務。

了解更多關於 為 Azure VM 應用程式建立應用程式套件的資訊。

2.(可選)打包應用程式設定檔

  • 您可以在 VM 應用程式的 中,使用 另外提供組態檔。 這可減少保存和取消保存應用程式套件的額外負荷。
  • 在應用程式部署時,也可以利用 虛擬機中的 屬性傳遞設定檔,啟用每台虛擬機的客製化安裝。
  • 如果同時設定這兩個屬性, 會覆寫使用 傳遞的組態。

3. 建立安裝腳本

應用程式與設定 blob 下載完後,Azure 會執行提供的安裝腳本來安裝該應用程式。 安裝腳本以字串形式提供 ,字元限制上限為 4,096 個字元。 安裝命令應假設應用程式套件和組態檔位於目前目錄中。

安裝指令碼中可能需要執行的作業很少

  • (可選)使用正確的指令直譯器 Azure 在 Linux 作業系統上使用的預設指令直譯器為 /bin/bash,Windows 作業系統則為 cmd.exe。 如果機器上安裝了 Chocolatey 或 PowerShell,則可以使用不同的解譯器。 呼叫可執行檔並將命令傳遞給它。 例如: 。 若使用 PowerShell,您需要使用 Azure 儲存體模組的 3.11.0 版本。

  • (可選)重新命名應用程式 blob 和設定 blob Azure 無法保留原始的 blob 名稱和檔案副檔名。 Azure 下載包含 Azure Compute Gallery 上 VM 應用資源名稱的應用程式檔案。 所以如果虛擬機應用程式名稱是「VMApp1」,那麼下載在虛擬機上的檔案名稱就是「VMApp1」,沒有副檔名。 設定檔預設名稱為「VMApp1-config」,沒有副檔名。

    您可以使用安裝指令碼,以副檔名重新命名檔案,也可以在 VM 應用程式版本資源的 中,於 與 屬性傳遞名稱。 Azure 在下載檔案時會使用這些名稱,而不是預設名稱。

  • 解除封存應用程式 Blob 對於已封存的應用程式套件,在安裝應用程式之前,需要先解除封存。 請使用 .zip 或.tar,因為大多數作業系統內建支援這些格式的解封。 對於其他格式,請確定客體作業系統提供支援。

  • 將腳本轉換為 string,安裝腳本會以字串形式傳遞給 Azure VM 應用程式版本資源的publishingProfile屬性中的install。

  • 安靜且同步安裝 安裝應用程式時可安靜或靜音,無需任何使用者介面提示。 由於安裝在無法取得客戶輸入的虛擬機上執行,必須使用靜默或無人值守的安裝旗標。 此外,若應用程式安裝程式會產生背景或子程序,或非同步執行,父腳本可能會在安裝完成前返回。 為了確保在 Azure 標記操作成功之前完整安裝完成,請使用等待旗標或阻擋指令。 此方法適用於安裝涉及多個非同步執行步驟,或需要在序列中下一個應用程式 開始前驗證安裝完成時。

    常見的範例包括:

    • Windows .msi: start /wait msiexec /i app.msi /quiet /qn
    • Windows .exe:start /wait app.exe /silent 或 start /wait app.exe /quiet 或 start /wait app.exe /S
    • PowerShell:
    • Linux .sh: (shell 腳本預設同步執行)
    • Linux .deb: (預設同步運行)
    • Linux .rpm: (預設同步執行)
  • (選擇性) 設定正確的執行原則和權限 取消封存之後,可以重設檔案權限。 在執行檔案之前設定正確的權限是一個很好的做法。

  • (可選)設定冗長執行與日誌 VM 應用程式會自動擷取安裝腳本的任何輸出,並儲存在虛擬機上的 stdout 檔案中。 利用此功能記錄安裝進度、除錯失敗並驗證成功部署。

    • 啟用詳細資訊模式,以擷取應用程式安裝程式記錄。 Bash:, PowerShell:, Cmd:.
    • 新增自訂訊息 來追蹤腳本進度。 Bash: , PowerShell: , Cmd:

    你可以用 執行指令 或連接虛擬機來取得這些日誌。 與 檔案位於下列路徑

    • Linux
    • Windows:C:\Packages\Plugins\Microsoft.CPlat.Core.VMApplicationManagerWindows\1.0.9\Downloads\<application name>\<application version>/
  • (可選)將應用程式與設定 blob 移至適當位置 Azure 將應用程式 blob 與設定 blob 下載至後續位置。 必要時,安裝指令碼必須將檔案移至適當的位置。

    Linux

    Windows:C:\Packages\Plugins\Microsoft.CPlat.Core.VMApplicationManagerWindows\1.0.16\Downloads\<application name>\<application version>

以下是幾個基於應用程式 blob 檔案副檔名的安裝腳本範例。 如果 在 檔名與副檔名中提供了 & 屬性,請移除後續腳本中重新命名檔案的程式碼。

  • .TAR
  • .ZIP壓縮檔案格式
  • .EXE
  • .MSI
  • .DEB
  • .RPM
  • .SH
  • .PS1

在應用程式套件(VMApp1)和設定檔(VMApp1-config)中替換 成你的虛擬機應用程式名稱。 請替換 成想要的應用程式名稱。 替換 成你想要的設定名稱。

使用 bash 安裝時不使用設定檔:

mv VMApp1 app.tar && tar -xf app.tar && chmod -R +xr . && bash ./install.sh
mv VMApp1 app.tar && tar -xf app.tar && chmod -R +xr . && sudo DEBIAN_FRONTEND=noninteractive dpkg -i ./app.deb

使用 bash 搭配設定檔安裝:

mv VMApp1 app.tar && mv VMApp1-config config.yaml && tar -xf app.tar && chmod -R +xr . && bash ./install.sh --config config.yaml

如果設定檔是打包在 tar 檔案裡的話

mv VMApp1 app.tar && tar -xf app.tar && chmod -R +xr . && sudo debconf-set-selections < config.cfg && sudo DEBIAN_FRONTEND=noninteractive dpkg -i ./app.deb

4. 建立移除腳本

腳 本讓你能定義移除應用程式的操作。 此 腳本以字串形式提供,最大字元限制為 4,096 個字元。 假設應用程式套件和設定檔都在目前的目錄中,寫入指令。 在卸載操作過程中,Azure 會執行卸載腳本,然後從儲存庫刪除所有檔案。

腳本必須執行的操作 很少。

  • 卸載應用程式: 從 VM 正確解除安裝應用程式。 例如:
  • CMD
  • PowerShell
  • Bash

Windows 上的 CMD:

start /wait uninstall.exe /quiet
start /wait python.exe /uninstall /quiet
start /wait msiexec /x app.msi /quiet /qn
  • 移除殘留檔案: 如果應用程式安裝在檔案系統的其他部分建立了檔案,請移除那些檔案。

將應用程式檔案上傳到 Azure 儲存帳號

這很重要

在上傳檔案或產生 SAS URL 前,先將角色分配給執行目標儲存帳號或容器操作的使用者、服務主體或管理身份:

  • 儲存 Blob 數據貢獻者或儲存 Blob 數據擁有者:需要上傳、修改或刪除 Blob。
  • 若要使用 Azure AD 產生 SAS (例如,使用 --auth-mode 登入 CLI/PowerShell),也請在儲存體帳戶範圍指派 Storage Blob Delegator。

1. 將您的應用程式與設定檔上傳到Azure儲存帳號的容器。

將你已打包的應用程式和可選的設定檔以 blob 形式上傳。 區塊 Blob 適用於大多數案例。

若需使用頁面塊,請在上傳前使用以下腳本之一進行位元對齊:

  • 命令列介面
  • PowerShell
inputFile="<the file you want to pad>"

# Get the file size
fileSize=$(stat -c %s "$inputFile")

# Calculate the remainder when divided by 512
remainder=$((fileSize % 512))

if [ "$remainder" -ne 0 ]; then
  # Calculate how many bytes to pad
  difference=$((512 - remainder))
  
  # Create padding (empty bytes)
  dd if=/dev/zero bs=1 count=$difference >> "$inputFile"
fi

2. 為應用程式套件及設定檔產生 SAS 或 Blob URL

當應用程式和設定檔上傳到儲存帳號後,你需要為這些 blob 產生一個帶有讀取權限的 Blob URL 或 SAS URL 。 這些 URL 在建立 VM 應用程式版本資源時會被提供作為參考。

備註

強烈建議使用帶有受管理身份的 blob URL,以提升安全性與隱私。

使用 Blob URL:

使用 SAS 網址:

  • 如果儲存帳號被停用以進行匿名存取,且管理身份沒有分配到 Azure Compute Gallery。

Blob URL = https://${STORAGE_ACCOUNT}.blob.core.windows.net/${CONTAINER_NAME}/${BLOB_NAME} SAS URL = https://${STORAGE_ACCOUNT}.blob.core.windows.net/${CONTAINER_NAME}/${BLOB_NAME}?${SAS_TOKEN}

  • 使用 Blob URL 的 CLI
  • CLI 使用 SAS URL
  • 使用 Blob URL 的 PowerShell
  • 使用 SAS URL 的 PowerShell
  • 入口網站

如果管理身份被分配至Azure 計算資源庫,請使用以下腳本。 此方法使用不含 SAS 令牌的 blob URL。

#!/bin/bash
set -euo pipefail

# === CONFIGURATION ===
STORAGE_ACCOUNT="your-storage-account-name"
CONTAINER_NAME="your-container-name"
APP_FILE="./path/to/your-app-file"           # Path to your application payload file        
CONFIG_FILE="./path/to/your-config-file"     # Path to your configuration file (optional)   

# === LOGIN (if not already logged in) ===
az login --only-show-errors

# === CREATE CONTAINER IF NOT EXISTS ===
az storage container create \
  --name "$CONTAINER_NAME" \
  --account-name "$STORAGE_ACCOUNT" \
  --auth-mode login \
  --only-show-errors

# === UPLOAD APPLICATION FILE ===
APP_BLOB_NAME=$(basename "$APP_FILE")
az storage blob upload \
  --account-name "$STORAGE_ACCOUNT" \
  --container-name "$CONTAINER_NAME" \
  --name "$APP_BLOB_NAME" \
  --file "$APP_FILE" \
  --auth-mode login \
  --overwrite \
  --only-show-errors

# === UPLOAD CONFIG FILE (optional) ===
if [ -n "$CONFIG_FILE" ] && [ -f "$CONFIG_FILE" ]; then
  CONFIG_BLOB_NAME=$(basename "$CONFIG_FILE")
  az storage blob upload \
    --account-name "$STORAGE_ACCOUNT" \
    --container-name "$CONTAINER_NAME" \
    --name "$CONFIG_BLOB_NAME" \
    --file "$CONFIG_FILE" \
    --auth-mode login \
    --overwrite \
    --only-show-errors
fi

# === GENERATE BLOB URLs ===
echo "Generating Blob URLs..."

APP_BLOB_URL="https://${STORAGE_ACCOUNT}.blob.core.windows.net/${CONTAINER_NAME}/${APP_BLOB_NAME}"
echo "Application file: $APP_BLOB_URL"

if [ -n "$CONFIG_FILE" ] && [ -f "$CONFIG_FILE" ]; then
  CONFIG_BLOB_URL="https://${STORAGE_ACCOUNT}.blob.core.windows.net/${CONTAINER_NAME}/${CONFIG_BLOB_NAME}"
  echo "Configuration file: $CONFIG_BLOB_URL"
fi

建立 VM 應用程式

要建立虛擬機應用程式,首先建立描述該應用程式的 虛擬機應用程式 資源。 然後在裡面建立 VM 應用程式版本 資源,裡面包含 VM 應用程式的有效載荷和安裝、更新、刪除應用程式的腳本。 承載會透過 Blob URL 或 SAS URL 提供給 Azure 儲存體帳戶中 Blob 容器。

請參閱 VM 應用程式和 VM 應用程式版本資源的架構 ,以深入瞭解每個屬性。

請使用以下 ARM 範本建立 Azure 計算庫、VM 應用程式及 VM 應用程式版本。 此範本展示了發佈應用程式套件的關鍵屬性與設定選項。

{
  "$schema": "https://schema.management.azure.com/schemas/2020-06-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "galleryName": {
      "type": "string"
    },
    "applicationName": {
      "type": "string"
    },
    "versionName": {
      "type": "string",
      "metadata": {
        "description": "Must follow the format: major.minor.patch (Example: 1.0.0)"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "West US"
    },
    "supportedOSType": {
      "type": "string",
      "allowedValues": ["Windows", "Linux"]
    },
    "endOfLifeDate": {
      "type": "string",
      "metadata": {
        "description": "Optional. This property is for information only and doesn't block app deployment."
      }
    },
    "description": {
      "type": "string",
      "defaultValue": "Description of the application"
    },
    "eula": {
      "type": "string",
      "defaultValue": ""
    },
    "privacyStatementUri": {
      "type": "string",
      "defaultValue": ""
    },
    "releaseNoteUri": {
      "type": "string",
      "defaultValue": ""
    },
    "mediaLink": {
      "type": "string"
    },
    "configLink": {
      "type": "string"
    },
    "appConfigFileName": {
      "type": "string"
    },
    "appPackageFileName": {
      "type": "string"
    },
    "replicaRegion1": {
      "type": "string",
      "defaultValue": "East US"
    },
    "replicaRegion2": {
      "type": "string",
      "defaultValue": "South Central US"
    },
    "installScript": {
      "type": "string",
      "metadata": {
        "description": "Optional. Script to run to install the application. Example: echo 'Installing application...'"
      }
    },
    "updateScript": {
      "type": "string",
      "metadata": {
        "description": "Optional. Script to run to update the application. Example: echo 'Updating application...'"
      }
    },
    "removeScript": {
      "type": "string",
      "metadata": {
        "description": "Optional. Script to run to delete the application. Example: echo 'Deleting application...'"
      }
    },
    "storageAccountType": {
      "type": "string",
      "allowedValues": ["PremiumV2_LRS", "Premium_LRS", "Standard_LRS", "Standard_ZRS"],
      "defaultValue": "Standard_LRS"
    }
  },
  "resources": [
    {
      "type": "Microsoft.Compute/galleries",
      "apiVersion": "2024-03-03",
      "name": "[parameters('galleryName')]",
      "location": "[parameters('location')]",
      "properties": {
        "identifier": {}
      }
    },
    {
      "type": "Microsoft.Compute/galleries/applications",
      "apiVersion": "2024-03-03",
      "name": "[format('{0}/{1}', parameters('galleryName'), parameters('applicationName'))]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[resourceId('Microsoft.Compute/galleries', parameters('galleryName'))]"
      ],
      "properties": {
        "supportedOSType": "[parameters('supportedOSType')]",
        "endOfLifeDate": "[parameters('endOfLifeDate')]",
        "description": "[parameters('description')]",
        "eula": "[if(equals(parameters('eula'), ''), json('null'), parameters('eula'))]",
        "privacyStatementUri": "[if(equals(parameters('privacyStatementUri'), ''), json('null'), parameters('privacyStatementUri'))]",
        "releaseNoteUri": "[if(equals(parameters('releaseNoteUri'), ''), json('null'), parameters('releaseNoteUri'))]"
      }
    },
    {
      "type": "Microsoft.Compute/galleries/applications/versions",
      "apiVersion": "2024-03-03",
      "name": "[format('{0}/{1}/{2}', parameters('galleryName'), parameters('applicationName'), parameters('versionName'))]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[resourceId('Microsoft.Compute/galleries/applications', parameters('galleryName'), parameters('applicationName'))]"
      ],
      "properties": {
        "publishingProfile": {
          "source": {
            "mediaLink": "[parameters('mediaLink')]",
            "defaultConfigurationLink": "[parameters('configLink')]"
          },
          "manageActions": {
            "install": "[parameters('installScript')]",
            "remove": "[parameters('removeScript')]",
            "update": "[parameters('updateScript')]"
          },
          "settings": {
            "scriptBehaviorAfterReboot": "Rerun",
            "configFileName": "[parameters('appConfigFileName')]",
            "packageFileName": "[parameters('appPackageFileName')]"
          },
          "targetRegions": [
            {
              "name": "[parameters('location')]",
              "regionalReplicaCount": 3,
              "storageAccountType": "[parameters('storageAccountType')]"
            },
            {
              "name": "[parameters('replicaRegion1')]",
              "regionalReplicaCount": 1,
              "storageAccountType": "[parameters('storageAccountType')]"
            },
            {
              "name": "[parameters('replicaRegion2')]"
            },
          ],
          "excludeFromLatest": false,
          "replicaCount": 2,
          "storageAccountType": "[parameters('storageAccountType')]"
        },
        "safetyProfile": {
          "allowDeletionOfReplicatedLocations": true
        },
        "endOfLifeDate": "[parameters('endOfLifeDate')]"
      }
    }
  ]
}

部署 VM 應用程式

現在可以在 Azure 虛擬機或 Azure 虛擬機規模設定的applicationProfile中引用一個或多個虛擬機應用程式。 接著 Azure 會拉取 VM 應用程式的有效載荷,並用提供的安裝腳本安裝到每台虛擬機上。 此 屬性定義虛擬機器應用程式在虛擬機器上安裝的循序順序。

請參考 VM/虛擬機器規模設定組合中的 applicationProfile 的 schema 以了解更多每個屬性的資訊。

  • Template
  • 休息
  • 命令列介面
  • PowerShell
  • 入口網站

請使用以下 ARM 範本部署 VM Application on Azure VM 或 Azure Virtual Machine Scale Sets。 此範本展示了部署虛擬機應用程式的關鍵屬性與設定選項。

在 Virtual Machine Scale Sets 上部署虛擬機應用程式

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "vmssName": {
      "type": "string"
    },
    "location": {
      "type": "string"
    },
    "subscriptionId": {
      "type": "string"
    },
    "resourceGroupName": {
      "type": "string"
    },
    "galleryName": {
      "type": "string"
    },
    "applicationName1": {
      "type": "string"
    },
    "applicationVersion1": {
      "type": "string",
      "defaultValue": "latest"
    },
    "configurationReference1": {
      "type": "string",
      "metadata": {
        "description": "Optional path to configuration file from Storage Account. Overrides default configuration file."
      }
    },
    "applicationName2": {
      "type": "string"
    },
    "applicationVersion2": {
      "type": "string",
      "defaultValue": "latest"
    }
  },
  "variables": {
    "packageReferenceId1": "[format('/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/galleries/{2}/applications/{3}/versions/{4}', parameters('subscriptionId'), parameters('resourceGroupName'), parameters('galleryName'), parameters('applicationName1'), parameters('applicationVersion1'))]",
    "packageReferenceId2": "[format('/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/galleries/{2}/applications/{3}/versions/{4}', parameters('subscriptionId'), parameters('resourceGroupName'), parameters('galleryName'), parameters('applicationName2'), parameters('applicationVersion2'))]"
  },
  "resources": [
    {
      "type": "Microsoft.Compute/virtualMachineScaleSets",
      "apiVersion": "2024-03-03",
      "name": "[parameters('vmssName')]",
      "location": "[parameters('location')]",
      "properties": {
        "virtualMachineProfile": {
          "applicationProfile": {
            "galleryApplications": [
              {
                "order": 1,
                "packageReferenceId": "[variables('packageReferenceId1')]",
                "configurationReference": "[parameters('configurationReference1')]",
                "treatFailureAsDeploymentFailure": true
              },
              {
                "order": 2,
                "packageReferenceId": "[variables('packageReferenceId2')]",
                "treatFailureAsDeploymentFailure": false
              }
            ]
          }
        }
      }
    }
  ]
}

Deploy VM Application on Azure VM

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "vmName": {
      "type": "string"
    },
    "location": {
      "type": "string"
    },
    "subscriptionId": {
      "type": "string"
    },
    "resourceGroupName": {
      "type": "string"
    },
    "galleryName": {
      "type": "string"
    },
    "applicationName1": {
      "type": "string"
    },
    "applicationVersion1": {
      "type": "string",
      "defaultValue": "latest"
    },
    "configurationReference1": {
      "type": "string",
      "metadata": {
        "description": "Optional path to configuration blob for application 1"
      }
    },
    "applicationName2": {
      "type": "string"
    },
    "applicationVersion2": {
      "type": "string",
      "defaultValue": "latest"
    }
  },
  "variables": {
    "packageReferenceId1": "[format('/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/galleries/{2}/applications/{3}/versions/{4}', parameters('subscriptionId'), parameters('resourceGroupName'), parameters('galleryName'), parameters('applicationName1'), parameters('applicationVersion1'))]",
    "packageReferenceId2": "[format('/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/galleries/{2}/applications/{3}/versions/{4}', parameters('subscriptionId'), parameters('resourceGroupName'), parameters('galleryName'), parameters('applicationName2'), parameters('applicationVersion2'))]"
  },
  "resources": [
    {
      "type": "Microsoft.Compute/virtualMachines",
      "apiVersion": "2024-07-01",
      "name": "[parameters('vmName')]",
      "location": "[parameters('location')]",
      "properties": {
        "applicationProfile": {
          "galleryApplications": [
            {
              "order": 1,
              "packageReferenceId": "[variables('packageReferenceId1')]",
              "configurationReference": "[parameters('configurationReference1')]",
              "treatFailureAsDeploymentFailure": true
            },
            {
              "order": 2,
              "packageReferenceId": "[variables('packageReferenceId2')]",
              "treatFailureAsDeploymentFailure": false
            }
          ]
        }
      }
    }
  ]
}

下一步