首页 > 解决方案 > 如何使用 Microsoft.Azure.Management.Fluent 列出资源组中的资源?

问题描述

我目前正在尝试使用 Microsoft.Azure.Management.Fluent 列出资源组中的所有资源,但我无法弄清楚。我做到了这一点:

var azure Microsoft.Azure.Management.Fluent.Azure
            .Configure()
            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
            .Authenticate(mycredentials)
            .WithDefaultSubscription();

var resourceGroup = azure.ResourceGroups.GetByName("MyResourceGroup");

但是现在我被困住了,因为我似乎只能从资源组(ID、名称等)中获取基本数据。但是,如果我想要组中所有资源的名称/资源类型?

我发现这个扩展方法似乎可以做我想做的事情:

https://docs.azure.cn/zh-cn/dotnet/api/microsoft.azure.management.resourcemanager.fluent.resourcegroupsoperationsextensions.listresourcesasync?view=azure-dotnet

但我不知道从哪里获得 IResourceGroupsOperations 对象。

有些人似乎也在谈论 a ResourceManagementClient,但它只是RestClient在它的构造函数中使用 a ,所以感觉它应该是一种更简单的方法。

标签: c#azure

解决方案


根据我的测试,我们可以ResourceManagementClient在 SDK中使用Microsoft.Azure.Management.ResourceManager.Fluent来列出一个资源组中的所有资源。详细步骤如下

  1. 使用 Azure CLI 创建服务主体
 az login
 az ad sp create-for-rbac --name <ServicePrincipalName>
 az role assignment create --assignee <ServicePrincipalName> --role Contributor
  1. 代码
var tenantId = "<your tenant id>";
var clientId = "<your sp app id> ";
var clientSecret = "<your sp passowrd>";
var subscriptionId = "<your subscription id>";
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
                       clientId,
                       clientSecret,
                       tenantId,
                        AzureEnvironment.AzureGlobalCloud);
RestClient restClient = RestClient.Configure()
                                  .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                                  .WithCredentials(credentials)
                                  .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                                  .Build();
ResourceManagementClient client = new ResourceManagementClient(restClient);
client.SubscriptionId = subscriptionId;
foreach (var resource in await client.Resources.ListByResourceGroupAsync("<your resource group name>")) {

       Console.WriteLine("Name:"+ resource.Name );


}

在此处输入图像描述


推荐阅读