快速入门:使用 .NET Core 运行你的第一个 Resource Graph 查询Quickstart: Run your first Resource Graph query using .NET Core

使用 Azure Resource Graph 的第一步是确保为 .NET Core 安装了所需的包。The first step to using Azure Resource Graph is to check that the required packages for .NET Core are installed. 本快速入门将指导你完成将该包添加到 .NET Core 安装的过程。This quickstart walks you through the process of adding the packages to your .NET Core installation.

在此过程结束时,你已将该包添加到 .NET Core 安装中,并将运行你的第一个 Resource Graph 查询。At the end of this process, you'll have added the packages to your .NET Core installation and run your first Resource Graph query.

先决条件Prerequisites

  • Azure 订阅。An Azure subscription. 如果没有 Azure 订阅,请在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.
  • Azure 服务主体,包括 clientId 和 clientSecret 。An Azure service principal, including the clientId and clientSecret. 如果你没有与 Resource Graph 一起使用的服务主体,或想要创建一个新的服务主体,请参阅用于 .NET 身份验证的 Azure 管理库If you don't have a service principal for use with Resource Graph or want to create a new one, see Azure management libraries for .NET authentication. 跳到安装 .NET Core 包的步骤,我们将在接下来的步骤中执行此安装。Skip the step to install the .NET Core packages as we'll do that in the next steps.

创建 Resource Graph 项目Create the Resource Graph project

若要使 .NET Core 能够查询 Azure Resource Graph,请创建新的控制台应用程序并安装所需的包。To enable .NET Core to query Azure Resource Graph, create a new console application and install the required packages.

  1. 请确保安装最新的 .NET Core(至少为 3.1.5)。Check that the latest .NET Core is installed (at least 3.1.5). 如果尚未安装,请前往 dotnet.microsoft.com 下载。If it isn't yet installed, download it at dotnet.microsoft.com.

  2. 初始化名为“argQuery”的新 .NET Core 控制台应用程序:Initialize a new .NET Core console application named "argQuery":

    dotnet new console --name "argQuery"
    
  3. 将目录切换到新项目文件夹,并安装 Azure Resource Graph 所需的包:Change directories into the new project folder and install the required packages for Azure Resource Graph:

    # Add the Resource Graph package for .NET Core
    dotnet add package Microsoft.Azure.Management.ResourceGraph --version 2.0.0
    
    # Add the Azure app auth package for .NET Core
    dotnet add package Microsoft.Azure.Services.AppAuthentication --version 1.5.0
    
  4. 用以下代码替换默认的 program.cs,并保存更新的文件:Replace the default program.cs with the following code and save the updated file:

    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Microsoft.Rest;
    using Microsoft.Azure.Management.ResourceGraph;
    using Microsoft.Azure.Management.ResourceGraph.Models;
    
    namespace argQuery
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                string strTenant = args[0];
                string strClientId = args[1];
                string strClientSecret = args[2];
                string strSubscriptionId = args[3];
                string strQuery = args[4];
    
                AuthenticationContext authContext = new AuthenticationContext("https://login.partner.microsoftonline.cn" + strTenant);
                AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://management.core.chinacloudapi.cn", new ClientCredential(strClientId, strClientSecret));
                ServiceClientCredentials serviceClientCreds = new TokenCredentials(authResult.AccessToken);
    
                ResourceGraphClient argClient = new ResourceGraphClient(serviceClientCreds);
                QueryRequest request = new QueryRequest();
                request.Subscriptions = new List<string>(){ strSubscriptionId };
                request.Query = strQuery;
    
                QueryResponse response = argClient.Resources(request);
                Console.WriteLine("Records: " + response.Count);
                Console.WriteLine("Data:\n" + response.Data);
            }
        }
    }
    
  5. 生成并发布 argQuery 控制台应用程序:Build and publish the argQuery console application:

    dotnet build
    dotnet publish -o {run-folder}
    

运行首个 Resource Graph 查询Run your first Resource Graph query

生成并发布 .NET Core 控制台应用程序之后,即可尝试创建简单的 Resource Graph 查询。With the .NET Core console application built and published, it's time to try out a simple Resource Graph query. 该查询返回前五个 Azure 资源,以及每个资源的名称和资源类型 。The query returns the first five Azure resources with the Name and Resource Type of each resource.

在对 argQuery 的每次调用中,都包含替换为自己的值时需要使用的变量:In each call to argQuery, there are variables that are used that you need to replace with your own values:

  • {tenantId} - 替换为租户 ID{tenantId} - Replace with your tenant ID
  • {clientId} -替换为服务主体的客户端 ID{clientId} - Replace with the client ID of your service principal
  • {clientSecret} -替换为服务主体的客户端机密{clientSecret} - Replace with the client secret of your service principal
  • {subscriptionId} - 替换为订阅 ID{subscriptionId} - Replace with your subscription ID
  1. 将目录更改为使用先前的 dotnet publish 命令定义的 {run-folder}Change directories to the {run-folder} you defined with the previous dotnet publish command.

  2. 使用已编译的 .NET Core 控制台应用程序运行首个 Azure Resource Graph 查询:Run your first Azure Resource Graph query using the compiled .NET Core console application:

    argQuery "{tenantId}" "{clientId}" "{clientSecret}" "{subscriptionId}" "Resources | project name, type | limit 5"
    

    备注

    由于此查询示例未提供排序修饰符(例如 order by),因此多次运行此查询可能会为每个请求生成一组不同的资源。As this query example does not provide a sort modifier such as order by, running this query multiple times is likely to yield a different set of resources per request.

  3. 将最后一个参数更改为 argQuery.exe,并将查询更改为按 Name 属性应用 order byChange the final parameter to argQuery.exe and change the query to order by the Name property:

    argQuery "{tenantId}" "{clientId}" "{clientSecret}" "{subscriptionId}" "Resources | project name, type | limit 5 | order by name asc"
    

    备注

    与第一个查询一样,多次运行此查询可能会为每个请求生成一组不同的资源。Just as with the first query, running this query multiple times is likely to yield a different set of resources per request. 查询命令的顺序非常重要。The order of the query commands is important. 在本例中,order by 位于 limit 之后。In this example, the order by comes after the limit. 命令按此顺序执行,首先会限制查询结果,然后对它们进行排序。This command order first limits the query results and then orders them.

  4. 将最后一个参数更改为 argQuery.exe,并将查询更改为先按 Name 属性应用 order by,然后对前五个结果应用 limitChange the final parameter to argQuery.exe and change the query to first order by the Name property and then limit to the top five results:

    argQuery "{tenantId}" "{clientId}" "{clientSecret}" "{subscriptionId}" "Resources | project name, type | order by name asc | limit 5"
    

假设环境中没有任何变化,则多次运行最后一个查询时,返回的结果将是一致的且按 Name 属性排序,但仍限制为前五个结果。When the final query is run several times, assuming that nothing in your environment is changing, the results returned are consistent and ordered by the Name property, but still limited to the top five results.

清理资源Clean up resources

如果要删除 .NETCore 控制台应用程序和已安装的包,可以通过删除 argQuery 项目文件夹来完成。If you wish to remove the .NET Core console application and installed packages, you can do so by deleting the argQuery project folder.

后续步骤Next steps

在此快速入门中,你已经创建了一个使用所需 Resource Graph 包的 .NET Core 控制台应用程序,并运行了第一个查询。In this quickstart, you've created a .NET Core console application with the required Resource Graph packages and run your first query. 若要详细了解 Resource Graph 语言,请继续阅读查询语言详细信息页。To learn more about the Resource Graph language, continue to the query language details page.