使用 Azure Policy 限制 Linux VM 上的扩展安装

如果想要阻止在 Linux VM 上安装某些扩展,可以使用 Azure CLI 创建 Azure Policy 定义以限制资源组中的 VM 扩展。 若要了解适用于 Linux 的 Azure VM 扩展的基础知识,请参阅适用于 Linux 的虚拟机扩展和功能

本教程在 Azure 本地 Shell 中使用 CLI,后者已不断更新到最新版本。 如果要在本地运行 Azure CLI,则需要安装版本 2.0.26 或更高版本。 运行 az --version 即可查找版本。 如果需要进行安装或升级,请参阅安装 Azure CLI

创建规则文件

为了限制哪些扩展可用,你需要创建一个规则来识别扩展。

此示例演示如何通过定义规则文件来拒绝安装不允许的 VM 扩展。 但是,如果你在本地使用 Azure CLI,则可以创建本地文件并将路径 (~/clouddrive) 替换为本地文件系统上的文件路径。

  1. 在 bash 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"
	}
}

创建参数文件

你还需要一个参数文件,该文件创建一个结构,用于传入未经授权的扩展列表。

此示例演示如何为 Linux VM 创建参数文件。 在本地使用 CLI 时。

  1. 在之前打开的 bash 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 创建策略定义。

在此示例中,规则和参数是在本地 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 Access 和适用于 Linux 的自定义脚本扩展。

注意

该资源组必须存在,然后才能分配策略。

使用 az account list 查找你的订阅 ID 并替换以下示例中的占位符:

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 Policy