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

将资源部署到 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.

启动 Azure PowerShellLaunch Azure PowerShell

打开 Azure Powershell 控制台,并以管理员权限运行以下脚本。Open the Azure Powershell console and run the following scripts with Administrator priviledge.

Note

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

了解范围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.

Connect-AzAccount -Environment AzureChinaCloud
New-AzResourceGroup -Name myResourceGroup -Location ChinaEast

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

基于角色的访问控制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. 使用基于角色的访问控制,你可以管理哪些用户有权在某个范围内完成特定操作。Role-based access control 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.

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

$adgroup = Get-AzADGroup -DisplayName <your-group-name>

New-AzRoleAssignment -ObjectId $adgroup.id `
  -ResourceGroupName myResourceGroup `
  -RoleDefinitionName "Virtual Machine Contributor"

如果收到一条错误,指出“主体 <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. 若要查看可用的策略定义,请使用 Get-AzPolicyDefinition 命令:To see the available policy definitions, use the Get-AzPolicyDefinition command:

(Get-AzPolicyDefinition).Properties | Format-Table displayName, policyType

可以看到现有的策略定义。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. 并且使用 New-AzPolicyAssignment 命令将这些定义分配到资源组。You use the New-AzPolicyAssignment command to assign those definitions to the resource group. 对于某些策略,你将提供参数值来指定允许的值。For some policies, you provide parameter values to specify the allowed values.

# Values to use for parameters
$locations ="chinaeast", "chinaeast2"
$skus = "Standard_DS1_v2", "Standard_E2s_v2"

# Get the resource group
$rg = Get-AzResourceGroup -Name myResourceGroup

# Get policy definitions for allowed locations, allowed SKUs, and auditing VMs that don't use managed disks
$locationDefinition = Get-AzPolicyDefinition | where-object {$_.properties.displayname -eq "Allowed locations"}
$skuDefinition = Get-AzPolicyDefinition | where-object {$_.properties.displayname -eq "Allowed virtual machine SKUs"}
$auditDefinition = Get-AzPolicyDefinition | where-object {$_.properties.displayname -eq "Audit VMs that do not use managed disks"}

# Assign policy for allowed locations
New-AzPolicyAssignment -Name "Set permitted locations" `
  -Scope $rg.ResourceId `
  -PolicyDefinition $locationDefinition `
  -listOfAllowedLocations $locations

# Assign policy for allowed SKUs
New-AzPolicyAssignment -Name "Set permitted VM SKUs" `
  -Scope $rg.ResourceId `
  -PolicyDefinition $skuDefinition `
  -listOfAllowedSKUs $skus

# Assign policy for auditing unmanaged disks
New-AzPolicyAssignment -Name "Audit unmanaged disks" `
  -Scope $rg.ResourceId `
  -PolicyDefinition $auditDefinition

部署虚拟机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. 运行此步骤时,会提示输入凭据。When running this step, you're prompted for credentials. 你输入的值将配置为用于虚拟机的用户名和密码。The values that you enter are configured as the user name and password for the virtual machine.

New-AzVm -ResourceGroupName "myResourceGroup" `
     -Name "myVM" `
     -Location "China East" `
     -VirtualNetworkName "myVnet" `
     -SubnetName "mySubnet" `
     -SecurityGroupName "myNetworkSecurityGroup" `
     -PublicIpAddressName "myPublicIpAddress" `
     -OpenPorts 80,3389

部署完成后,可以对解决方案应用更多的管理设置。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.

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

# Add CanNotDelete lock to the VM
New-AzResourceLock -LockLevel CanNotDelete `
  -LockName LockVM `
  -ResourceName myVM `
  -ResourceType Microsoft.Compute/virtualMachines `
  -ResourceGroupName myResourceGroup

# Add CanNotDelete lock to the network security group
New-AzResourceLock -LockLevel CanNotDelete `
  -LockName LockNSG `
  -ResourceName myNetworkSecurityGroup `
  -ResourceType Microsoft.Network/networkSecurityGroups `
  -ResourceGroupName myResourceGroup

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

Remove-AzResourceGroup -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.

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

Set-AzResourceGroup -Name myResourceGroup -Tag @{ Dept="IT"; Environment="Test" }

让我们假设要添加第三个标记。Let's suppose you want to add a third tag. 每次将标记应用到某个资源或资源组时,都会覆盖该资源或资源组中的现有标记。Every time you apply tags to a resource or a resource group, you overwrite the existing tags on that resource or resource group. 若要添加新标记而不会丢失现有标记,必须检索现有标记、添加新标记,并重新应用标记集合:To add a new tag without losing the existing tags, you must retrieve the existing tags, add a new tag, and reapply the collection of tags:

# Get existing tags and add a new tag
$tags = (Get-AzResourceGroup -Name myResourceGroup).Tags
$tags.Add("Project", "Documentation")

# Reapply the updated set of tags 
Set-AzResourceGroup -Tag $tags -Name myResourceGroup

资源不从资源组继承标记。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 that are not duplicates, use the following script:

# Get the resource group
$group = Get-AzResourceGroup myResourceGroup

if ($group.Tags -ne $null) {
    # Get the resources in the resource group
    $resources = Get-AzResource -ResourceGroupName $group.ResourceGroupName

    # Loop through each resource
    foreach ($r in $resources)
    {
        # Get the tags for this resource
        $resourcetags = (Get-AzResource -ResourceId $r.ResourceId).Tags

        # If the resource has existing tags, add new ones
        if ($resourcetags)
        {
            foreach ($key in $group.Tags.Keys)
            {
                if (-not($resourcetags.ContainsKey($key)))
                {
                    $resourcetags.Add($key, $group.Tags[$key])
                }
            }

            # Reapply the updated tags to the resource 
            Set-AzResource -Tag $resourcetags -ResourceId $r.ResourceId -Force
        }
        else
        {
            Set-AzResource -Tag $group.Tags -ResourceId $r.ResourceId -Force
        }
    }
}

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

# Get the resource group
$g = Get-AzResourceGroup -Name myResourceGroup

# Find all the resources in the resource group, and for each resource apply the tags from the resource group
Get-AzResource -ResourceGroupName $g.ResourceGroupName | ForEach-Object {Set-AzResource -ResourceId $_.ResourceId -Tag $g.Tags -Force }

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

Set-AzResourceGroup -Name myResourceGroup -Tag @{ CostCenter="{`"Dept`":`"IT`",`"Environment`":`"Test`"}" }

若要添加具有多个值的新标记而不丢失现有标记,必须检索现有标记、对新标记使用 JSON 字符串,并重新应用标记集合:To add a new tag with several values without losing the existing tags, you must retrieve the existing tags, use a JSON string for the new tag, and reapply the collection of tags:

# Get existing tags and add a new tag
$ResourceGroup = Get-AzResourceGroup -Name myResourceGroup
$Tags = $ResourceGroup.Tags
$Tags.Add("CostCenter", "{`"Dept`":`"IT`",`"Environment`":`"Test`"}")

# Reapply the updated set of tags
$ResourceGroup | Set-AzResourceGroup -Tag $Tags

若要删除所有标记,请传递一个空哈希表。To remove all tags, you pass an empty hash table.

Set-AzResourceGroup -Name myResourceGroup -Tag @{ }

若要将标记应用于虚拟机,请使用 Set-AzResource 命令:To apply tags to a virtual machine, use the Set-AzResource command:

# Get the virtual machine
$r = Get-AzResource -ResourceName myVM `
  -ResourceGroupName myResourceGroup `
  -ResourceType Microsoft.Compute/virtualMachines

# Apply tags to the virtual machine
Set-AzResource -Tag @{ Dept="IT"; Environment="Test"; Project="Documentation" } -ResourceId $r.ResourceId -Force

按标记查找资源Find resources by tag

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

(Get-AzResource -Tag @{ Environment="Test"}).Name

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

Get-AzResource -Tag @{ Environment="Test"} | Where-Object {$_.ResourceType -eq "Microsoft.Compute/virtualMachines"} | Stop-AzVM

清理资源Clean up resources

在解除锁定之前,不能删除锁定的网络安全组。The locked network security group can't be deleted until the lock is removed. 若要删除锁,请使用 Remove-AzResourceLock 命令:To remove the lock, use the Remove-AzResourceLock command:

Remove-AzResourceLock -LockName LockVM `
  -ResourceName myVM `
  -ResourceType Microsoft.Compute/virtualMachines `
  -ResourceGroupName myResourceGroup
Remove-AzResourceLock -LockName LockNSG `
  -ResourceName myNetworkSecurityGroup `
  -ResourceType Microsoft.Network/networkSecurityGroups `
  -ResourceGroupName myResourceGroup

如果不再需要资源组、VM 和所有相关的资源,可以使用 Remove-AzResourceGroup 命令将其删除。When no longer needed, you can use the Remove-AzResourceGroup command to remove the resource group, VM, and all related resources.

Remove-AzResourceGroup -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