简体   繁体   中英

How to list resources in a resource group with Microsoft.Azure.Management.Fluent?

I'm currently trying to list all resources in a resource group with Microsoft.Azure.Management.Fluent and I just can't figure it out. I get this far:

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

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

But now I'm stuck as it seems I can just get the basic data from the resource group (Id, name, etc). But if I want the name/resource type of all the resources in the group?

I found this extension method that seems to do what I want to do:

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

But I can't figure out where I would get the IResourceGroupsOperations object from.

Some also seems to talk about a ResourceManagementClient too but that one takes a simply RestClient in it's constructor so it feels like it should be an easier way to do it.

According to my test, we can use ResourceManagementClient in the SDK Microsoft.Azure.Management.ResourceManager.Fluent to list all resources in one resource group. The detailed steps are as below

  1. Use Azure CLI to create a service pricipal
 az login
 az ad sp create-for-rbac --name <ServicePrincipalName>
 az role assignment create --assignee <ServicePrincipalName> --role Contributor
  1. Code
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 );


}

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM