Share via


使用 Azure 原則來限制 Linux VM 上的延伸模組安裝

如果您想要防止在 Linux VM 上安裝特定的延伸模組,便可以使用 Azure CLI 來建立 Azure 原則定義,以限制某個資源群組內 VM 的延伸模組。 若要了解適用於 Linux 的 Azure VM 擴充功能基本概念,請參閱適用於 Linux 的虛擬機器擴充功能和功能

本教學課程會使用 Azure Cloud Shell 內的 CLI,這會不斷更新至最新版本。 如果您想要在本機執行 Azure CLI,則必須安裝 2.0.26 版或更新版本。 執行 az --version 以尋找版本。 如果您需要安裝或升級,請參閱安裝 Azure CLI

建立規則檔

為了限制可使用的延伸模組,您需要建立規則以識別延伸功能。

此範例示範如何在 Azure Cloud Shell 中定義規則檔案以拒絕安裝不允許的 VM 擴充模組。 不過,如果是在本機使用 Azure CLI,您可以建立本機檔案,並以本機檔案系統上的檔案路徑取代路徑 (~/clouddrive)。

  1. bash Cloud Shell 中,使用任何文字編輯器建立檔案 ~/clouddrive/azurepolicy.rules.json

  2. 將下列 .json 內容複製並貼到新檔案中,並加以儲存。

{
	"if": {
		"allOf": [
			{
				"field": "type",
				"equals": "Microsoft.Compute/virtualMachines/extensions"
			},
			{
				"field": "Microsoft.Compute/virtualMachines/extensions/publisher",
				"equals": "Microsoft.OSTCExtensions"
			},
			{
				"field": "Microsoft.Compute/virtualMachines/extensions/type",
				"in": "[parameters('notAllowedExtensions')]"
			}
		]
	},
	"then": {
		"effect": "deny"
	}
}

建立參數檔案

您也需要一個參數檔以建立結構,用於傳遞未授權的延伸模組清單。

此範例示範如何在 Cloud Shell 中建立 Linux VM 的參數檔案。

  1. 在先前開啟的 bash Cloud Shell 中,使用任何文字編輯器建立 ~/clouddrive/azurepolicy.parameters.json 檔案。

  2. 將下列 .json 內容複製並貼到新檔案中,並加以儲存。

{
	"notAllowedExtensions": {
		"type": "Array",
		"metadata": {
			"description": "The list of extensions that will be denied. Example: CustomScriptForLinux, VMAccessForLinux etc.",
			"displayName": "Denied extension"
		}
	}
}

建立原則

原則定義是用來儲存您所使用設定的物件。 原則定義會使用規則檔和參數檔來定義原則。 請使用 az policy definition create 來建立原則定義。

在此範例中,規則和參數是您在 Cloud Shell 或本地檔案系統中以 .json 檔案形式建立並儲存的檔案。

az policy definition create \
   --name 'not-allowed-vmextension-linux' \
   --display-name 'Block VM Extensions' \
   --description 'This policy governs which VM extensions that are blocked.' \
   --rules '~/clouddrive/azurepolicy.rules.json' \
   --params '~/clouddrive/azurepolicy.parameters.json' \
   --mode All

指派原則

此範例會使用 az policy assignment create 將原則指派到資源群組。 任何建立在 myResourceGroup 資源群組中的 VM 都將無法安裝 Linux VM 存取或適用於 Linux 的自訂指令碼延伸模組。

注意

資源群組必須已存在,您才能指派原則。

使用 az account list 來尋找您的訂用帳戶識別碼,並取代下列範例中的預留位置:

az policy assignment create \
   --name 'not-allowed-vmextension-linux' \
   --scope /subscriptions/<subscription Id>/resourceGroups/myResourceGroup \
   --policy "not-allowed-vmextension-linux" \
   --params '{
		"notAllowedExtensions": {
			"value": [
				"VMAccessForLinux",
				"CustomScriptForLinux"
			]
		}
	}'

測試原則

建立新的 VM 並新增使用者來測試原則。

az vm create \
    --resource-group myResourceGroup \
	--name myVM \
	--image myImage \
	--generate-ssh-keys

注意

請據以取代 myResourceGroupmyVMmyImage 值。

使用「VM 存取」延伸模組來嘗試建立一個名為 myNewUser 的新使用者。

az vm user update \
  --resource-group myResourceGroup \
  --name myVM \
  --username myNewUser \
  --password 'mynewuserpwd123!'

移除指派

az policy assignment delete --name 'not-allowed-vmextension-linux' --resource-group myResourceGroup

移除原則

az policy definition delete --name 'not-allowed-vmextension-linux'

下一步

如需詳細資訊,請參閱 Azure 原則