次の方法で共有


Azure SDK for .NET を使用したリソース管理

Azure SDK for .NET 管理プレーン ライブラリは、.NET アプリケーション内から Azure リソースを作成、プロビジョニング、管理するのに役立ちます。 すべての Azure サービスには、対応する管理ライブラリがあります。

管理ライブラリ (Azure.ResourceManager.Computeなど、Azure.ResourceManagerで始まる名前空間) を使用すると、Azure portal、Azure CLI、またはその他のリソース管理ツールを使用して実行できるのと同じタスクを実行する構成プログラムとデプロイ プログラムを記述できます。

これらのパッケージは、新しい Azure SDK ガイドラインに従います。これは、次のようなすべての Azure SDK 間で共有される コア機能を提供します。

  • 直感的な Azure ID ライブラリ。
  • カスタム ポリシーを含む HTTP パイプライン。
  • エラー処理。
  • 分散トレース。

手記

一部のパッケージはまだプレリリース バージョンであることに気付く場合があります。 追加の Azure サービスの管理プレーン ライブラリの段階的なリリースが進行中です。 特定の Azure リソースの安定版パッケージを探していて、現在プレリリース版しか利用できない場合は、Azure SDK for .NET GitHub リポジトリで問題を報告してください

作業の開始

前提 条件

パッケージをインストールする

.NET 用の Azure ID と 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 を 1 つだけ作成する必要があります。

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 チート シート

Azure Management SDK for .NET の使用を開始するには、一般的な Azure Service Bus 名前空間を作成、一覧表示、更新、削除するタスクがあるとします。次の手順に従います。

  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)
Contains resourceGroup.GetServiceBusNamespaces().Exists(string servicebusNamespaceName)
削除 client.GetServiceBusQueueResource(ResourceIdentifior resourceIdentifior).Delete() または resourceGroup.GetServiceBusNamespace(string servicebusNamespaceName).Delete()

リソース グループ自体を含むすべての Azure リソースは、上記の例のようなコードを使用して、対応する管理 SDK によって管理できることに注意してください。 正しい Azure 管理 SDK パッケージを見つけるには、次のパターン Azure.ResourceManager.{ResourceProviderName}で名前が付けられたパッケージを探します。

ResourceIdentifier の詳細については、構造化リソース識別子のを参照してください。

主な概念

Azure リソース階層について

一般的なタスクの実行に必要なクライアントの数と、各クライアントが受け取る冗長パラメーターの数を減らすために、Azure のオブジェクト階層を模倣するオブジェクト階層を SDK に導入しました。 SDK の各リソース クライアントには、適切なサブスクリプションとリソース グループのスコープが既に設定されている子のリソース クライアントにアクセスするメソッドがあります。

これを実現するために、Azure のすべてのリソースに対して次の 3 つの標準の種類を導入します。

{ResourceName}Resource クラス

この型は、詳細を {ResourceName}Data 型として公開する Data プロパティを含む完全なリソース クライアント オブジェクトを表します。 また、サブスクリプション ID やリソース名などのスコープ パラメーターを渡す必要なく、そのリソースに対するすべての操作にアクセスできます。 これで、すべてが完全なリソース クライアントとして返されるため、リスト呼び出しの結果に対して操作を直接実行すると便利です。

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 データ)
Contains Exists(文字列名)

ほとんどの場合、リソースの親は ResourceGroupですが、場合によってはリソース自体にサブリソースがあります。たとえば、サブネット は、VirtualNetworkの子です。 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());
   }
}

構造化リソース識別子

リソース ID にはリソース自体に関する有用な情報が含まれていますが、解析する必要があるプレーン文字列です。 独自の解析ロジックを実装する代わりに、解析を行う 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 になる可能性があることに注意してください。 通常は、リソース ID の種類を ID 文字列自体で確認できます。 ただし、不明な場合は、プロパティが null かどうかを確認してください。

例: リソース識別子ジェネレーター

純粋な stringから resourceId を手動で作成したくない場合があります。 各 {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 に対して 3 つの API 呼び出しが行われます。 クライアント自体で提供した拡張メソッドを使用して、コードを減らし、API 呼び出しなしで同じことができます。 これらの拡張メソッドを使用すると、リソース識別子を渡し、スコープ付きリソース クライアントを取得できます。 返されるオブジェクトは {ResourceName}Resourceです。 データを取得するために Azure にまだアクセスしていないため、Data プロパティを呼び出すと例外がスローされます。HasData プロパティを使用して、リソース インスタンスにデータが含まれているかどうかを確認するか、リソースに対して Get または GetAsync メソッドを呼び出してリソース データを取得できます。

したがって、前の例は次のようになります。

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);

リソースが存在するかどうかを確認する

取得するリソースが存在するかどうかがわからない場合、またはリソースが存在するかどうかを確認するだけの場合は、任意の {ResourceName}Collection クラスから呼び出すことができる Exists() または ExistsAsync() メソッドを使用できます。

Exists() は、非同期バージョンが Task<Response<bool>>を返すので、ExistsAsync()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 リリース」を参照してください。