共用方式為


使用適用於 .NET 的 Azure SDK 進行資源管理

Azure SDK for .NET 管理平面連結庫可協助您從 .NET 應用程式內建立、布建和管理 Azure 資源。 所有 Azure 服務都有對應的管理程式庫。

使用管理連結庫 (命名空間開頭為 Azure.ResourceManager,例如,Azure.ResourceManager.Compute),您可以撰寫組態和部署程式,以執行您可以透過 Azure 入口網站、Azure CLI 或其他資源管理工具執行的相同工作。

這些套件會遵循 新的 Azure SDK 指導方針,其提供所有 Azure SDK 之間共用的 核心功能,包括:

  • 直覺式 Azure 身分識別程式庫。
  • 具有自定義原則的 HTTP 管線。
  • 錯誤處理。
  • 分散式追蹤。

注意

您可能會注意到某些套件仍是發行前版本。 目前正在分階段釋出其他 Azure 服務的管理層庫。 如果您要尋找特定 Azure 資源的穩定版本套件,且目前只有發行前版本可用,請在 Azure SDK for .NET GitHub 存放庫中提出問題。

開始使用

先決條件

安裝套件

安裝適用於 .NET 的 Azure 身分識別和 Azure 資源管理 NuGet 套件。 例如:

Install-Package Azure.Identity
Install-Package Azure.ResourceManager
Install-Package Azure.ResourceManager.Resources
Install-Package Azure.ResourceManager.Compute
Install-Package Azure.ResourceManager.Network

驗證用戶端

建立已驗證客戶端的預設選項是使用 DefaultAzureCredential。 由於所有管理 API 都經過相同的端點,若要與資源互動,只有一個最上層 ArmClient 必須被建立。

若要向 Azure 進行驗證並建立 ArmClient,請具現化指定的認證 ArmClient

using Azure.Identity;
using Azure.ResourceManager;
using System;
using System.Threading.Tasks;

// Code omitted for brevity

ArmClient client = new ArmClient(new DefaultAzureCredential());

如需 Azure.Identity.DefaultAzureCredential 類別的詳細資訊,請參閱 DefaultAzureCredential 類別

管理 SDK 速查表

若要開始使用適用於 .NET 的 Azure 管理 SDK,假設您有建立/列出/更新/刪除一般 Azure 服務總線命名空間的工作,請遵循下列步驟:

  1. 請對您要處理的訂用帳戶和資源群組進行身份驗證。
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ServiceBus;

ArmClient client = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = client.GetDefaultSubscription();
ResourceGroupResource resourceGroup =
    client.GetDefaultSubscription().GetResourceGroup(resourceGroupName);
  1. 尋找用來管理 Azure 資源的對應方法。
操作 方法
取得具有資源標識碼的資源 client.GetServiceBusQueueResource(ResourceIdentifier resourceIdentifier)
清單 resourceGroup.GetServiceBusNamespaces()
指數 resourceGroup.GetServiceBusNamespace(string servicebusNamespaceName)
新增/更新 resourceGroup.GetServiceBusNamespaces().CreateOrUpdate(Azure.WaitUntil waitUntil, string name, ServiceBusNamespaceData data)
包含 resourceGroup.GetServiceBusNamespaces().Exists(string servicebusNamespaceName)
刪除 client.GetServiceBusQueueResource(ResourceIdentifior resourceIdentifior).Delete()resourceGroup.GetServiceBusNamespace(string servicebusNamespaceName).Delete()

請記住,所有 Azure 資源,包括資源群組本身,都可以由其對應的管理 SDK 使用類似上述範例的程式代碼來管理。 若要尋找正確的 Azure 管理 SDK 套件,請尋找符合以下模式的套件:Azure.ResourceManager.{ResourceProviderName}

若要深入瞭解 ResourceIdentifier,請參閱 結構化資源識別碼

重要概念

瞭解 Azure 資源階層

為了減少執行一般工作所需的用戶端數目,以及每個用戶端採用的備援參數數目,我們在 SDK 中引進了模擬 Azure 中物件階層的物件階層。 SDK 中的每個資源用戶端都有方法可存取其子系的資源用戶端,這些用戶端已限定為適當的訂用帳戶和資源群組。

為了達成此目的,我們會針對 Azure 中的所有資源引進三種標準類型:

{ResourceName} Resource 類別

此類型代表完整的資源客戶端物件,其中包含 Data 屬性,以 {ResourceName}Data 類型公開詳細數據。 它也能夠存取該資源上的所有作業,而不需要傳入範圍參數,例如訂用帳戶標識碼或資源名稱。 這可讓您在列表調用結果上直接執行操作,因為現在會以完整資源用戶端的形式傳回所有內容。

ArmClient client = new ArmClient(new DefaultAzureCredential());
string resourceGroupName = "myResourceGroup";
SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
ResourceGroupResource resourceGroup = await subscription.GetResourceGroupAsync(resourceGroupName);
await foreach (VirtualMachineResource virtualMachine in resourceGroup.GetVirtualMachinesAsync())
{
    //previously we would have to take the resourceGroupName and the vmName from the vm object
    //and pass those into the powerOff method as well as we would need to execute that on a separate compute client
    await virtualMachine.PowerOffAsync(WaitUntil.Completed);
}

{ResourceName}Data 類別

此類型代表組成指定資源的模型。 一般而言,這是來自服務呼叫的響應數據,例如 HTTP GET,並提供基礎資源的詳細數據。 先前,這是由 Model 類別表示。

{ResourceName}Collection 類別

此類型代表您可以在屬於特定父資源的資源集合上執行的作業。 這個物件提供大部分的邏輯集合作業。

集合行為 集合方法
迭代/清單 GetAll()
指數 Get(字符串名稱)
CreateOrUpdate(Azure.WaitUntil waitUntil,字符串名稱,{ResourceName}Data data)
包含 Exists(字串名稱)

在大部分情況下,資源的父項是 ResourceGroup,但在某些情況下,資源本身具有子資源。例如,SubnetVirtualNetwork的子項。 ResourceGroup 本身是 訂用帳戶 的子系

整合所有內容

假設我們的公司要求所有虛擬機都以擁有者標記。 我們負責撰寫程式,以將標籤新增至指定資源群組中的任何遺漏虛擬機。

// First we construct our armClient
ArmClient client = new ArmClient(new DefaultAzureCredential());

// Next we get a resource group object
// ResourceGroup is a {ResourceName}Resource object from above
SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
ResourceGroupResource resourceGroup =
   await subscription.GetResourceGroupAsync("myRgName");

// Next we get the collection for the virtual machines
// vmCollection is a {ResourceName}Collection object from above
VirtualMachineCollection virtualMachineCollection = await resourceGroup.GetVirtualMachines();

// Next we loop over all vms in the collection
// Each vm is a {ResourceName}Resource object from above
await foreach(VirtualMachineResource virtualMachine in virtualMachineCollection)
{
   // We access the {ResourceName}Data properties from vm.Data
   if(!virtualMachine.Data.Tags.ContainsKey("owner"))
   {
       // We can also access all operations from vm since it is already scoped for us
       await virtualMachine.AddTagAsync("owner", GetOwner());
   }
}

結構化資源標識碼

資源標識元包含資源本身的實用資訊,但它們是必須剖析的純文本字串。 您可以使用會為您進行剖析的 ResourceIdentifier 物件,而不是實作自己的剖析邏輯。

範例:使用 ResourceIdentifier 物件解析 ID

string resourceId = "/subscriptions/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/resourceGroups/workshop2021-rg/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet";
ResourceIdentifier id = new ResourceIdentifier(resourceId);
Console.WriteLine($"Subscription: {id.SubscriptionId}");
Console.WriteLine($"ResourceGroup: {id.ResourceGroupName}");
Console.WriteLine($"Vnet: {id.Parent.Name}");
Console.WriteLine($"Subnet: {id.Name}");

不過,請記住,其中一些屬性可能是 Null。 您通常可以使用識別符字串本身來判斷資源識別碼的類型。 但如果您不確定,請檢查屬性是否為 Null。

範例:資源標識碼產生器

您可能不想從純 resourceId手動建立 string。 每個 {ResourceName}Resource 類別都有一個靜態方法,可協助您建立資源標識符字串。

ResourceIdentifier resourceId =
    AvailabilitySetResource.CreateResourceIdentifier(
        "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
        "resourceGroupName",
        "resourceName");

管理現有的資源

使用管理客戶端連結庫時,對已經存在的資源執行作業是常見的使用案例。 在此案例中,您通常會有想要當做字串處理之資源的標識碼。 雖然新的物件階層非常適合在指定父系的範圍內布建及運作,但對於此特定案例而言,它並不是最有效率的。

以下範例說明如何存取 AvailabilitySetResource 物件,並使用其資源識別碼直接管理它:

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Compute;
using System;
using System.Threading.Tasks;

// Code omitted for brevity

ResourceIdentifier subscriptionId =
    SubscriptionResource.CreateResourceIdentifier("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee");

ResourceIdentifier resourceId =
    AvailabilitySetResource.CreateResourceIdentifier(
        subscriptionId.SubscriptionId,
        "resourceGroupName",
        "resourceName");

// We construct a new armClient to work with
ArmClient client = new ArmClient(new DefaultAzureCredential());
// Next we get the specific subscription this resource belongs to
SubscriptionResource subscription = client.GetSubscriptionResource(subscriptionId);
// Next we get the specific resource group this resource belongs to
ResourceGroupResource resourceGroup = await subscription.GetResourceGroupAsync(resourceId.ResourceGroupName);
// Finally we get the resource itself
// Note: for this last step in this example, Azure.ResourceManager.Compute is needed
AvailabilitySetResource availabilitySet = await resourceGroup.GetAvailabilitySetAsync(resourceId.Name);

此方法需要對 Azure 進行許多程式代碼和三個 API 呼叫。 使用我們在用戶端本身提供的擴充方法,即可使用較少的程序代碼,而不需要任何 API 呼叫。 這些擴充方法可讓您傳入資源標識符,並擷取限定範圍的資源用戶端。 傳回的物件是 {ResourceName}Resource。 由於尚未連絡 Azure 以擷取數據,因此呼叫 Data 屬性將會擲回例外狀況,因此您可以使用 HasData 屬性來判斷資源實例是否包含數據,或呼叫資源上的 GetGetAsync 方法來擷取資源數據。

因此,上一個範例最後看起來會像這樣:

ResourceIdentifier resourceId =
    AvailabilitySetResource.CreateResourceIdentifier(
        "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
        "resourceGroupName",
        "resourceName");
// We construct a new armClient to work with
ArmClient client = new ArmClient(new DefaultAzureCredential());
// Next we get the AvailabilitySet resource client from the armClient
// The method takes in a ResourceIdentifier but we can use the implicit cast from string
AvailabilitySetResource availabilitySet = client.GetAvailabilitySetResource(resourceId);
// At this point availabilitySet.Data will be null and trying to access it will throw exception
// If we want to retrieve the objects data we can simply call get
availabilitySet = await availabilitySet.GetAsync();
// we now have the data representing the availabilitySet
Console.WriteLine(availabilitySet.Data.Name);

檢查資源是否存在

如果您不確定想要取得的資源是否存在,或只是想要檢查資源是否存在,您可以使用 Exists()ExistsAsync() 方法,從任何 {ResourceName}Collection 類別叫用。

Exists() 傳回 Response<bool> ,而其異步版本 ExistsAsync() 則傳回 Task<Response<bool>>。 在 Response<bool> 物件中,您可以流覽其 Value 屬性,以檢查資源是否存在。 如果資源不存在,則 Valuefalse,反之亦然。

在舊版套件中,您必須擷取 RequestFailedException,並檢查 404 的狀態代碼。 有了這個新的 API,我們希望這可以提升開發人員生產力,並將資源存取優化。

ArmClient client = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
string resourceGroupName = "myRgName";

try
{
    ResourceGroupResource resourceGroup = await subscription.GetResourceGroupAsync(resourceGroupName);
    // At this point, we are sure that myRG is a not null Resource Group, so we can use this object to perform any operations we want.
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
    Console.WriteLine($"Resource Group {resourceGroupName} does not exist.");
}

現在,透過這些便利方法,我們只要執行下列動作即可。

ArmClient client = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
string resourceGroupName = "myRgName";

bool exists = await subscription.GetResourceGroups().ExistsAsync(resourceGroupName).Value;

if (exists)
{
    Console.WriteLine($"Resource Group {resourceGroupName} exists.");

    // We can get the resource group now that we know it exists.
    // This does introduce a small race condition where resource group could have been deleted between the check and the get.
    ResourceGroupResource resourceGroup = await subscription.GetResourceGroupAsync(resourceGroupName);
}
else
{
    Console.WriteLine($"Resource Group {rgName} does not exist.");
}

例子

建立資源群組

// First, initialize the ArmClient and get the default subscription
ArmClient client = new ArmClient(new DefaultAzureCredential());
// Now we get a ResourceGroup collection for that subscription
SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
ResourceGroupCollection resourceGroupCollection = subscription.GetResourceGroups();

// With the collection, we can create a new resource group with an specific name
string resourceGroupName = "myRgName";
AzureLocation location = AzureLocation.WestUS2;
ResourceGroupData resourceGroupData = new ResourceGroupData(location);
ResourceGroupResource resourceGroup = (await resourceGroupCollection.CreateOrUpdateAsync(resourceGroupName, resourceGroupData)).Value;

列出所有資源群組

// First, initialize the ArmClient and get the default subscription
ArmClient client = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
// Now we get a ResourceGroup collection for that subscription
ResourceGroupCollection resourceGroupCollection = subscription.GetResourceGroups();
// With GetAllAsync(), we can get a list of the resources in the collection
await foreach (ResourceGroupResource resourceGroup in resourceGroupCollection)
{
    Console.WriteLine(resourceGroup.Data.Name);
}

更新資源群組

// Note: Resource group named 'myRgName' should exist for this example to work.
ArmClient client = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
string resourceGroupName = "myRgName";
ResourceGroupResource resourceGroup = await subscription.GetResourceGroupAsync(resourceGroupName);
resourceGroup = await resourceGroup.AddTagAsync("key", "value");

刪除資源群組

ArmClient client = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
string resourceGroupName = "myRgName";
ResourceGroupResource resourceGroup = await subscription.GetResourceGroupAsync(resourceGroupName);
await resourceGroup.DeleteAsync();

如需更詳細的範例,請參閱 範例。

故障排除

  • 如果您要報告錯誤或提出建議,請透過 GitHub 問題 提出,並確保在問題中新增「預覽」標籤。
  • 如果您需要協助,請檢查 先前的問題,或使用 Azure 和 .NET 標籤在 StackOverflow 上詢問新的問題。
  • 如果在驗證時遇到問題,請參閱 DefaultAzureCredential 文件

後續步驟

更多範例程序代碼

附加文件

如果您要從舊版 SDK 移轉至此預覽版,請參閱此 移轉指南

如需 Azure SDK 的詳細資訊,請參閱 Azure SDK 版本