教學課程:了解如何使用 Azure CLI 控管 Linux 虛擬機器Tutorial: Learn about Linux virtual machine governance 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/regions?
  • 如何控制成本?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 中的治理For a broader discussion of the concepts, see Governance in Azure.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. Cloud Shell 可讓您使用 bashPowerShell 以與 Azure 服務搭配使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文提到的程式碼,而不必在本機環境上安裝任何工具。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要啟動 Azure Cloud Shell:To launch Azure Cloud Shell:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 選取 [試用] 並不會自動將程式碼複製到 Cloud Shell 中。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的試試看範例
請前往 https://shell.azure.com 或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. <a href="https://shell.azure.com" title="啟動 Azure Cloud Shell
選取 Azure 入口網站右上角功能表列中的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

若要在 Azure Cloud Shell 中執行本文中的程式碼:To run the code in this article in Azure Cloud Shell:

  1. 啟動 Cloud Shell。Launch Cloud Shell.
  2. 選取程式碼區塊上的 [複製] 按鈕,複製程式碼。Select the Copy button on a code block to copy the code.
  3. 在 Windows 和 Linux 上按 Ctrl+Shift+V;或在 macOS 上按 Cmd+Shift+V,將程式碼貼到 Cloud Shell工作階段中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
  4. 按下 Enter 鍵執行程式碼。Press Enter to run the code.

如果您選擇在本機安裝和使用 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. 管理群組是預覽版本。Management groups are in a preview release. 下圖顯示這些層級的範例。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 "East US"

目前資源群組是空的。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.

建立新群組或找到現有群組後,請使用 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 原則Azure Policy

Azure 原則可協助您確認訂用帳戶中的所有資源均符合公司標準。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": [
          "eastus", 
          "eastus2"
        ]
      }
    }'

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

# 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. 例如,您可以將「環境」名稱和「生產」值套用至生產環境中的所有資源。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
do
  # 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
done

或者,您可以從資源群組將標記套用至資源,而不保留現有標記: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
do
  # Apply tags from resource group to this resource
  az resource tag --tags $t --id $resid
done

若要在單一標記中合併數個值,請使用 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)

依標籤值檢視成本View costs by tag values

將標記套用至資源之後,您可以檢視具有這些標記之資源的成本。After applying tags to resources, you can view costs for resources with those tags. 成本分析顯示最新的使用方式需要一些時間,因此您可能還看不到成本。It takes a while for cost analysis to show the latest usage, so you may not see the costs yet. 當有成本可顯示時,您可以檢視訂用帳戶中所有資源群組的資源成本。When the costs are available, you can view costs for resources across resource groups in your subscription. 使用者必須擁有訂用帳戶層級的計費資訊存取權才能查看成本。Users must have subscription level access to billing information to see the costs.

若要在入口網站中依標記檢視成本,請選取您的訂用帳戶,然後選取 [成本分析] 。To view costs by tag in the portal, select your subscription and select Cost Analysis.

成本分析

接著,以標記值篩選,選取 [套用] 。Then, filter by the tag value, and select Apply.

依標記檢視成本

您也可以使用 Azure 計費 API 透過程式設計的方式檢視成本。You can also use the Azure Billing APIs to programmatically view costs.

清除資源Clean up resources

您無法刪除已鎖定的網路安全性群組,除非移除鎖定。The locked network security group can't be deleted until the lock is removed. 若要移除鎖定,請擷取鎖定的識別碼,並將這些識別碼提供給 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

若不再需要,您可以使用 az group delete 命令來移除資源群組、VM 和所有相關資源。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

請前進到下一個教學課程,以了解如何使虛擬機器具備高可用性。Advance to the next tutorial to learn about how highly available virtual machines.