教程:了解如何使用 Azure CLI 管理 Linux 虚拟机Tutorial: Learn about Linux virtual machine management with Azure CLI

将资源部署到 Azure 时,可以灵活选择想要部署的资源类型、资源的位置以及对它们的设置方式。When deploying resources to Azure, you have tremendous flexibility when deciding what types of resources to deploy, where they are located, and how to set them up. 但是,除了你想要在组织中允许的选项,这种灵活性可能还会开放更多其他选项。However, that flexibility may open more options than you would like to allow in your organization. 在考虑将资源部署到 Azure 时,你可能想知道以下问题:As you consider deploying resources to Azure, you might be wondering:

  • 如何满足特定国家/地区针对数据所有权制定的法规要求?How do I meet legal requirements for data sovereignty in certain countries?
  • 如何控制成本?How do I control costs?
  • 如何确保用户不会无意中更改关键系统?How do I ensure that someone does not inadvertently change a critical system?
  • 如何跟踪资源成本并准确地进行计费?How do I track resource costs and bill it accurately?

本文会为你解答这些问题。This article addresses those questions. 具体而言,你需要:Specifically, you:

  • 将用户分配到角色并分配角色对应的作用域,这样用户就能具备执行预期操作所需的权限,同时并不会涉及其他操作。Assign users to roles and assign the roles to a scope so users have permission to perform expected actions but not more actions.
  • 应用策略来对订阅中的资源进行约定。Apply policies that prescribe conventions for resources in your subscription.
  • 锁定系统中的关键资源。Lock resources that are critical to your system.
  • 标记资源,以便按它们对组织的价值进行跟踪。Tag resources so you can track them by values that make sense to your organization.

本文重点介绍实现管理需要完成的任务。This article focuses on the tasks you take to implement governance.


请先运行 az cloud set -n AzureChinaCloud 更改云环境,然后才能在 Azure 中国中使用 Azure CLI。Before you can use Azure CLI in Azure China , please run az cloud set -n AzureChinaCloud first to change the cloud environment. 若要切换回 Azure 公有云,请再次运行 az cloud set -n AzureCloudIf you want to switch back to Azure Public Cloud, run az cloud set -n AzureCloud again.

如果选择在本地安装并使用 Azure CLI,本教程要求运行 Azure CLI 2.0.30 或更高版本。If you choose to install and use Azure CLI locally, this tutorial requires that you're running the Azure CLI version 2.0.30 or later. 运行 az --version 即可查找版本。Run az --version to find the version. 如果需要进行安装或升级,请参阅安装 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

了解范围Understand scope

在创建任何项之前,让我们复习一下作用域的概念。Before creating any items, let's review the concept of scope. Azure 提供四个级别的管理:管理组、订阅、资源组和资源。Azure provides four levels of management: management groups, subscription, resource group, and resource. 下图显示了这些层的一个示例。The following image shows an example of these layers.


将在上述任何级别的作用域中应用管理设置。You apply management settings at any of these levels of scope. 所选的级别确定应用设置的广泛程度。The level you select determines how widely the setting is applied. 较低级别继承较高级别的设置。Lower levels inherit settings from higher levels. 将设置应用到订阅时,该设置将应用于订阅中的所有资源组和资源。When you apply a setting to the subscription, that setting is applied to all resource groups and resources in your subscription. 将设置应用到资源组时,该设置将应用到资源组及其所有资源。When you apply a setting on the resource group, that setting is applied the resource group and all its resources. 但是,其他资源组不具有该设置。However, another resource group does not have that setting.

通常情况下,最好在较高级别应用关键设置,在较低级别应用特定于项目的要求。Usually, it makes sense to apply critical settings at higher levels and project-specific requirements at lower levels. 例如,可能想要确保组织的所有资源均已部署到特定区域。For example, you might want to make sure all resources for your organization are deployed to certain regions. 若要完成此要求,请将策略应用到指定允许位置的订阅。To accomplish this requirement, apply a policy to the subscription that specifies the allowed locations. 当组织中的其他用户添加新资源组和资源时,会自动强制实施允许的位置。As other users in your organization add new resource groups and resources, the allowed locations are automatically enforced.

在本教程中,你将所有管理设置应用于一个资源组,以便在完成后可以轻松地删除这些设置。In this tutorial, you apply all management settings to a resource group so you can easily remove those settings when done.

让我们创建该资源组。Let's create that resource group.

az group create --name myResourceGroup --location "China East"

目前,资源组为空。Currently, the resource group is empty.

Azure 基于角色的访问控制Azure role-based access control

你希望确保你的组织中的用户对这些资源具有合适级别的访问权限。You want to make sure users in your organization have the right level of access to these resources. 你不希望向用户授予不受限的访问权限,但还需要确保他们可以执行其工作。You don't want to grant unlimited access to users, but you also need to make sure they can do their work. 使用 Azure 基于角色的访问控制 (Azure RBAC),你可以管理哪些用户有权在某个范围内完成特定操作。Azure role-based access control (Azure RBAC) enables you to manage which users have permission to complete specific actions at a scope.

若要创建和删除角色分配,用户必须具有 Microsoft.Authorization/roleAssignments/* 访问权限。To create and remove role assignments, users must have Microsoft.Authorization/roleAssignments/* access. 此访问权限是通过“所有者”或“用户访问”管理员角色授权的。This access is granted through the Owner or User Access Administrator roles.

若要管理虚拟机解决方案,可以使用三种特定于资源的角色来进行通常所需的访问:For managing virtual machine solutions, there are three resource-specific roles that provide commonly needed access:

通常情况下,与其向单个用户分配角色,不如使用其用户需要执行类似操作的 Azure Active Directory 组,Instead of assigning roles to individual users, it's often easier to use an Azure Active Directory group that has users who need to take similar actions. 然后向该组分配相应的角色。Then, assign that group to the appropriate role. 就本文来说,请使用现有的组来管理虚拟机,或者使用门户来创建 Azure Active Directory 组For this article, either use an existing group for managing the virtual machine, or use the portal to create an Azure Active Directory group.

创建新组或找到现有组以后,请使用 az role assignment create 命令将新的 Azure Active Directory 组分配到资源组的“虚拟机参与者”角色。After creating a new group or finding an existing one, use the az role assignment create command to assign the new Azure Active Directory group to the Virtual Machine Contributor role for the resource group.

adgroupId=$(az ad group show --group <your-group-name> --query objectId --output tsv)

az role assignment create --assignee-object-id $adgroupId --role "Virtual Machine Contributor" --resource-group myResourceGroup

如果收到一条错误,指出 主体 <guid> 不存在于目录中,则表明新组未在 Azure Active Directory 中完成传播。If you receive an error stating Principal <guid> does not exist in the directory, the new group hasn't propagated throughout Azure Active Directory. 请尝试再次运行命令。Try running the command again.

通常情况下,请对 网络参与者存储帐户参与者 重复执行此过程,确保分配用户来管理已部署的资源。Typically, you repeat the process for Network Contributor and Storage Account Contributor to make sure users are assigned to manage the deployed resources. 在本文中,可以跳过这些步骤。In this article, you can skip those steps.

Azure PolicyAzure Policy

Azure Policy 可帮助确保订阅中的所有资源符合企业标准。Azure Policy helps you make sure all resources in subscription meet corporate standards. 订阅已经有多个策略定义。Your subscription already has several policy definitions. 若要查看可用的策略定义,请使用 az policy definition list 命令:To see the available policy definitions, use the az policy definition list command:

az policy definition list --query "[].[displayName, policyType, name]" --output table

可以看到现有的策略定义。You see the existing policy definitions. 策略类型为“内置”或“自定义” 。The policy type is either BuiltIn or Custom. 在这些定义中查找所述条件正是你要分配的条件的定义。Look through the definitions for ones that describe a condition you want assign. 在本文中,分配的策略要符合以下条件:In this article, you assign policies that:

  • 限制所有资源的位置。Limit the locations for all resources.
  • 限制虚拟机的 SKU。Limit the SKUs for virtual machines.
  • 审核不使用托管磁盘的虚拟机。Audit virtual machines that don't use managed disks.

在下面的示例中,你将基于显示名称检索三个策略定义。In the following example, you retrieve three policy definitions based on the display name. 并且使用 az policy assignment create 命令将这些定义分配到资源组。You use the az policy assignment create command to assign those definitions to the resource group. 对于某些策略,你将提供参数值来指定允许的值。For some policies, you provide parameter values to specify the allowed values.

# Get policy definitions for allowed locations, allowed SKUs, and auditing VMs that don't use managed disks
locationDefinition=$(az policy definition list --query "[?displayName=='Allowed locations'].name | [0]" --output tsv)
skuDefinition=$(az policy definition list --query "[?displayName=='Allowed virtual machine SKUs'].name | [0]" --output tsv)
auditDefinition=$(az policy definition list --query "[?displayName=='Audit VMs that do not use managed disks'].name | [0]" --output tsv)

# Assign policy for allowed locations
az policy assignment create --name "Set permitted locations" \
  --resource-group myResourceGroup \
  --policy $locationDefinition \
  --params '{ 
      "listOfAllowedLocations": {
        "value": [

# Assign policy for allowed SKUs
az policy assignment create --name "Set permitted VM SKUs" \
  --resource-group myResourceGroup \
  --policy $skuDefinition \
  --params '{ 
      "listOfAllowedSKUs": {
        "value": [

# Assign policy for auditing unmanaged disks
az policy assignment create --name "Audit unmanaged disks" \
  --resource-group myResourceGroup \
  --policy $auditDefinition

前面的示例假定你已知道了策略的参数。The preceding example assumes you already know the parameters for a policy. 如果需要查看参数,请使用:If you need to view the parameters, use:

az policy definition show --name $locationDefinition --query parameters

部署虚拟机Deploy the virtual machine

分配角色和策略以后,即可部署解决方案。You have assigned roles and policies, so you're ready to deploy your solution. 默认大小为 Standard_DS1_v2,这是允许的 SKU 之一。The default size is Standard_DS1_v2, which is one of your allowed SKUs. 如果默认位置中不存在 SSH 密钥,则此命令会创建这些密钥。The command creates SSH keys if they don't exist in a default location.

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

部署完成后,可以对解决方案应用更多的管理设置。After your deployment finishes, you can apply more management settings to the solution.

锁定资源Lock resources

资源锁可以防止组织中的用户意外删除或修改重要资源。Resource locks prevent users in your organization from accidentally deleting or modifying critical resources. 与基于角色的访问控制不同,资源锁对所有用户和角色应用限制。Unlike role-based access control, resource locks apply a restriction across all users and roles. 可以将锁定级别设置为 CanNotDeleteReadOnlyYou can set the lock level to CanNotDelete or ReadOnly.

若要创建或删除管理锁,必须有权执行 Microsoft.Authorization/locks/* 操作。To create or delete management locks, you must have access to Microsoft.Authorization/locks/* actions. 在内置角色中,只有“所有者”和“用户访问管理员”有权执行这些操作。 Of the built-in roles, only Owner and User Access Administrator are granted those actions.

若要锁定虚拟机和网络安全组,请使用 az lock create 命令:To lock the virtual machine and network security group, use the az lock create command:

# Add CanNotDelete lock to the VM
az lock create --name LockVM \
  --lock-type CanNotDelete \
  --resource-group myResourceGroup \
  --resource-name myVM \
  --resource-type Microsoft.Compute/virtualMachines

# Add CanNotDelete lock to the network security group
az lock create --name LockNSG \
  --lock-type CanNotDelete \
  --resource-group myResourceGroup \
  --resource-name myVMNSG \
  --resource-type Microsoft.Network/networkSecurityGroups

若要测试锁,请尝试运行以下命令:To test the locks, try running the following command:

az group delete --name myResourceGroup

将会显示一个错误,指出删除操作由于某个锁而无法完成。You see an error stating that the delete operation can't be completed because of a lock. 只有在明确删除锁以后,才能删除资源组。The resource group can only be deleted if you specifically remove the locks. 该步骤显示在清理资源中。That step is shown in Clean up resources.

标记资源Tag resources

可以将标记应用于 Azure 资源,以逻辑方式按类别对其进行组织。You apply tags to your Azure resources to logically organize them by categories. 每个标记包含一个名称和一个值。Each tag consists of a name and a value. 例如,可以对生产中的所有资源应用名称“Environment”和值“Production”。For example, you can apply the name "Environment" and the value "Production" to all the resources in production.

若要为资源组添加两个标记,请使用 az group update 命令:To add two tags to a resource group, use the az group update command:

az group update -n myResourceGroup --set tags.Environment=Test tags.Dept=IT

让我们假设要添加第三个标记。Let's suppose you want to add a third tag. 在包含新标记的情况下再次运行该命令。Run the command again with the new tag. 它将追加到现有的标记后。It is appended to the existing tags.

az group update -n myResourceGroup --set tags.Project=Documentation

资源不从资源组继承标记。Resources don't inherit tags from the resource group. 目前,资源组有三个标记,但资源没有任何标记。Currently, your resource group has three tags but the resources do not have any tags. 若要将来自资源组的所有标记应用于其资源,并且保留资源上的现有标记,请使用以下脚本:To apply all tags from a resource group to its resources, and retain existing tags on resources, use the following script:

# Get the tags for the resource group
jsontag=$(az group show -n myResourceGroup --query tags)

# Reformat from JSON to space-delimited and equals sign
t=$(echo $jsontag | tr -d '"{},' | sed 's/: /=/g')

# Get the resource IDs for all resources in the resource group
r=$(az resource list -g myResourceGroup --query [].id --output tsv)

# Loop through each resource ID
for resid in $r
  # Get the tags for this resource
  jsonrtag=$(az resource show --id $resid --query tags)

  # Reformat from JSON to space-delimited and equals sign
  rt=$(echo $jsonrtag | tr -d '"{},' | sed 's/: /=/g')

  # Reapply the updated tags to this resource
  az resource tag --tags $t$rt --id $resid

或者,可以将资源组中的标记应用于资源而不保留现有标记:Alternatively, you can apply tags from the resource group to the resources without keeping the existing tags:

# Get the tags for the resource group
jsontag=$(az group show -n myResourceGroup --query tags)

# Reformat from JSON to space-delimited and equals sign
t=$(echo $jsontag | tr -d '"{},' | sed 's/: /=/g')

# Get the resource IDs for all resources in the resource group
r=$(az resource list -g myResourceGroup --query [].id --output tsv)

# Loop through each resource ID
for resid in $r
  # Apply tags from resource group to this resource
  az resource tag --tags $t --id $resid

若要将几个值组合到单个标记中,请使用 JSON 字符串。To combine several values in a single tag, use a JSON string.

az group update -n myResourceGroup --set tags.CostCenter='{"Dept":"IT","Environment":"Test"}'

若要删除资源组上的所有标记,请使用:To remove all tags on a resource group, use:

az group update -n myResourceGroup --remove tags

若要将标记应用于虚拟机,请使用 az resource tag 命令。To apply tags to a virtual machine, use the az resource tag command. 资源上的任何现有标记都不会保留。Any existing tags on the resource aren't retained.

az resource tag -n myVM \
  -g myResourceGroup \
  --tags Dept=IT Environment=Test Project=Documentation \
  --resource-type "Microsoft.Compute/virtualMachines"

按标记查找资源Find resources by tag

若要通过标记名称和值查找资源,请使用 az resource list 命令:To find resources with a tag name and value, use the az resource list command:

az resource list --tag Environment=Test --query [].name

可以将返回的值用于管理任务,例如停止带有某个标记值的所有虚拟机。You can use the returned values for management tasks like stopping all virtual machines with a tag value.

az vm stop --ids $(az resource list --tag Environment=Test --query "[?type=='Microsoft.Compute/virtualMachines'].id" --output tsv)

清理资源Clean up resources

在解除锁定之前,不能删除锁定的网络安全组。The locked network security group can't be deleted until the lock is removed. 若要删除锁,请检索锁的 ID,并将其提供给 az lock delete 命令:To remove the lock, retrieve the IDs of the locks and provide them to the az lock delete command:

vmlock=$(az lock show --name LockVM \
  --resource-group myResourceGroup \
  --resource-type Microsoft.Compute/virtualMachines \
  --resource-name myVM --output tsv --query id)
nsglock=$(az lock show --name LockNSG \
  --resource-group myResourceGroup \
  --resource-type Microsoft.Network/networkSecurityGroups \
  --resource-name myVMNSG --output tsv --query id)
az lock delete --ids $vmlock $nsglock

如果不再需要资源组、VM 和所有相关的资源,可以使用 az group delete 命令将其删除。When no longer needed, you can use the az group delete command to remove the resource group, VM, and all related resources. 退出 SSH 会话,返回 VM,然后删除资源,如下所示:Exit the SSH session to your VM, then delete the resources as follows:

az group delete --name myResourceGroup

后续步骤Next steps

在本教程中,已创建自定义 VM 映像。In this tutorial, you created a custom VM image. 你已了解如何执行以下操作:You learned how to:

  • 为用户分配角色Assign users to a role
  • 应用强制实施标准的策略Apply policies that enforce standards
  • 使用锁保护重要资源Protect critical resources with locks
  • 标记用于计费和管理的资源Tag resources for billing and management