MilleB
MilleB

Reputation: 1580

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.

Upvotes: 2

Views: 2608

Answers (1)

Jim Xu
Jim Xu

Reputation: 23141

According to my test, we can use ResourceManagementClient in the SDKMicrosoft.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 );


}

enter image description here

Upvotes: 4

Related Questions