gpt4 book ai didi

c# - 如何使用 Azure Mgmt SDK Fluent 获取空资源组列表

转载 作者:行者123 更新时间:2023-12-03 02:36:04 25 4
gpt4 key购买 nike

我正在使用https://www.nuget.org/packages/Microsoft.Azure.Management.Fluent用于以编程方式(C# .NET-Core Web 应用程序)获取 Azure 中的资源,并尝试通过提供如下服务主体来获取资源信息...

 string subscriptionId="XXX"; 
AzureCredentials cred = new
AzureCredentialsFactory().FromServicePrincipal(UIConstants.ClientID,
UIConstants.Secret, UIConstants.Tenant,AzureEnvironment.AzureGlobalCloud);

var azure = Azure.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(cred)
.WithSubscription(subscriptionId);

如何使用与 dotnetcore、C#.net 兼容的 Azure Mgmt SDK 获取空资源组列表不包含任何 azure 的资源组资源

请提供以上建议。

谢谢

最佳答案

没有内置方法,需要编写代码来检查资源组中是否有资源。

这里是示例代码,它可以列出我这边所有的空资源组:

using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System;

namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
string subscriptionId = "xxx";
string clientId = "xxx";
string tenantId = "xxx";
string clientSecret = "xxx";

AzureCredentials cred = new AzureCredentialsFactory()
.FromServicePrincipal(
clientId,
clientSecret,
tenantId,
AzureEnvironment.AzureGlobalCloud
);

var azure = Azure.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(cred)
.WithSubscription(subscriptionId);


RestClient restClient = RestClient.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithCredentials(cred)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Build();

ResourceManagementClient client = new ResourceManagementClient(restClient);
client.SubscriptionId = subscriptionId;

//list all resource groups
var rgs = azure.ResourceGroups.List();

foreach (var r in rgs)
{

var resources = client.Resources.ListByResourceGroupAsync(r.Name).Result;

//initiate a resource number as 0
int number_of_resources = 0;

//check if there are any resources in the resource group
foreach (var resource in resources)
{
number_of_resources++;
break;
}

//if the resources number is 0 in the resource group, then print out the empty resource group name
if (number_of_resources == 0)
{
Console.WriteLine($"the resource group: {r.Name} is empty");
}
}

Console.WriteLine("**completed**");
Console.ReadLine();
}
}
}

关于c# - 如何使用 Azure Mgmt SDK Fluent 获取空资源组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63242445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com