如何使用Azure资源管理API获取资源组的资源列表
我已经安装了Microsoft.Azure.Management.ResourceManager.Fluent Nuget包 以下脚本仅提供资源组列表,但不提供每个资源组的资源列表。
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
var azure = Azure.Configure().Authenticate(credentials).WithSubscription(subscriptionID);
var resourecelist = azure.ResourceGroups.List().ToList();
我正在寻找类似于powershell
的内容Get-AzureRmResource -ResourceGroupName $batchResourceGroup -ResourceType 'Microsoft.Batch/batchAccounts'
答案 0 :(得分:1)
请尝试使用以下代码获取资源列表。我测试它在我身边,它正常工作。我们也可以使用Resources - List By Resource Group Rest API来执行此操作。
var resouceManagementClient = new ResourceManagementClient(credentials) {SubscriptionId = subscriptionId};
var resource = resouceManagementClient.ResourceGroups.ListResourcesAsync(resourceGroup,new ODataQuery<GenericResourceFilterInner>(x=>x.ResourceType == "Microsoft.Batch/batchAccounts")).Result;
答案 1 :(得分:1)
以上答案已过时,因此这是我在 2020 年 12 月生效的代码片段。
Azure.IAuthenticated _azure;
string _subscriptionId;
RestClient _restClient;
async Task Main()
{
Connect();
// Get resource groups
var resourceManagementClient = new ResourceManagementClient(_restClient)
{
SubscriptionId = _subscriptionId
};
var resourceList = (await resourceManagementClient.ResourceGroups.ListAsync()).ToList().OrderBy(r => r.Name);
// ...
}
void Connect()
{
_subscriptionId = "XXX";
var tenantId = "YYY";
var clientId = "ZZZ";
var secret = "QQQ";
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId, secret, tenantId,
AzureEnvironment.AzureGlobalCloud)
.WithDefaultSubscription(_subscriptionId);
_restClient = RestClient
.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.WithCredentials(credentials)
.Build();
var creds = new AzureCredentialsFactory().FromServicePrincipal(
clientId, secret, tenantId,
AzureEnvironment.AzureGlobalCloud
);
_azure = Azure.Authenticate(creds);
}
使用/导入/NuGet。 (您不需要所有这些...):
Microsoft.Azure.Management.AppService.Fluent
Microsoft.Azure.Management.AppService.Fluent.Models
Microsoft.Azure.Management.Fluent
Microsoft.Azure.Management.ResourceManager.Fluent
Microsoft.Azure.Management.ResourceManager.Fluent.Authentication
Microsoft.Azure.Management.ResourceManager.Fluent.Core
Microsoft.IdentityModel.Clients.ActiveDirectory
Microsoft.Rest
Microsoft.ServiceBus.Messaging
System.Threading.Tasks
Microsoft.Rest.Azure