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

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

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

先决条件Prerequisites

如果没有 Azure 订阅,请在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

添加 Resource Graph 包Add the Resource Graph package

若要使 Go 能够查询 Azure Resource Graph,则必须添加该包。To enable Go to query Azure Resource Graph, the package must be added. 此包适用于可使用 Go 的任何情况,包括 Windows 10 上的 bash 或本地安装的 bash。This package works wherever Go can be used, including bash on Windows 10 or locally installed.

  1. 请确保安装最新的 Go(至少为 1.14)。Check that the latest Go is installed (at least 1.14 ). 如果尚未安装,请在 Golang.org 下载。If it isn't yet installed, download it at Golang.org.

  2. 请确保安装最新的 Azure CLI(至少为 2.5.1)。Check that the latest Azure CLI is installed (at least 2.5.1 ). 如果尚未安装,请参阅安装 Azure CLIIf it isn't yet installed, see Install the Azure CLI.

    备注

    在以下示例中,需要 Azure CLI 来启用 Go 以使用 auth.NewAuthorizerFromCLI() 方法。Azure CLI is required to enable Go to use the auth.NewAuthorizerFromCLI() method in the following example. 有关其他选项的信息,请参阅 Azure SDK for Go - 更多身份验证详细信息For information about other options, see Azure SDK for Go - More authentication details.

  3. 通过 Azure CLI 进行身份验证。Authenticate through Azure CLI.

    az login
    
  4. 在所选的 Go 环境中,安装 Azure Resource Graph 所需的包:In your Go environment of choice, install the required packages for Azure Resource Graph:

    # Add the Resource Graph package for Go
    go get -u github.com/Azure/azure-sdk-for-go/services/resourcegraph/mgmt/2019-04-01/resourcegraph
    
    # Add the Azure auth package for Go
    go get -u github.com/Azure/go-autorest/autorest/azure/auth
    

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

将 Go 包添加到所选环境中后,即可尝试一个简单的 Resource Graph 查询。With the Go packages added to your environment of choice, 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.

  1. 创建 Go 应用程序并将以下源保存为 argQuery.goCreate the Go application and save the following source as argQuery.go:

    package main
    
    import (
        "fmt"
        "os"
        "context"
        "strconv"
        arg "github.com/Azure/azure-sdk-for-go/services/resourcegraph/mgmt/2019-04-01/resourcegraph"
        "github.com/Azure/go-autorest/autorest/azure/auth"
    )
    
    func main() {
       // Get variables from command line arguments
       var query = os.Args[1]
       var subList = os.Args[2:]
    
       // Create and authorize a ResourceGraph client
       argClient := arg.New()
       authorizer, err := auth.NewAuthorizerFromCLI()
       if err == nil {
           argClient.Authorizer = authorizer
       } else {
           fmt.Printf(err.Error())
       }
    
       // Set options
       RequestOptions := arg.QueryRequestOptions {
           ResultFormat: "objectArray",
       }
    
       // Create the query request
       Request := arg.QueryRequest {
           Subscriptions: &subList,
           Query: &query,
           Options: &RequestOptions,
       }
    
       // Run the query and get the results
       var results, queryErr = argClient.Resources(context.Background(), Request)
       if queryErr == nil {
           fmt.Printf("Resources found: " + strconv.FormatInt(*results.TotalRecords, 10) + "\n")
           fmt.Printf("Results: " + fmt.Sprint(results.Data) + "\n")
       } else {
           fmt.Printf(queryErr.Error())
       }
    }
    
  2. 构建 Go 应用程序:Build the Go application:

    go build argQuery.go
    
  3. 使用已编译的 Go 应用程序运行首个 Azure Resource Graph 查询。Run your first Azure Resource Graph query using the compiled Go application. <SubID> 替换为订阅 ID:Replace <SubID> with your subscription ID:

    argQuery "Resources | project name, type | limit 5" "<SubID>"
    

    备注

    由于此查询示例未提供排序修饰符(例如 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.

  4. 将第一个参数更改为 argQuery,并将查询更改为 order by Name 属性。Change the first parameter to argQuery and change the query to order by the Name property. <SubID> 替换为订阅 ID:Replace <SubID> with your subscription ID:

    argQuery "Resources | project name, type | limit 5 | order by name asc" "<SubID>"
    

    备注

    与第一个查询一样,多次运行此查询可能会为每个请求生成一组不同的资源。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.

  5. 将第一个参数更改为 argQuery,并将查询更改为先 order by Name 属性,然后对前五个结果应用 limitChange the first parameter to argQuery and change the query to first order by the Name property and then limit to the top five results. <SubID> 替换为订阅 ID:Replace <SubID> with your subscription ID:

    argQuery "Resources | project name, type | order by name asc | limit 5" "<SubID>"
    

假设环境中没有任何变化,则多次运行最后一个查询时,返回的结果将是一致的且按 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

如果希望从 Go 环境中删除已安装的包,可使用以下命令执行此操作:If you wish to remove the installed packages from your Go environment, you can do so by using the following command:

# Remove the installed packages from the Go environment
go clean -i github.com/Azure/azure-sdk-for-go/services/resourcegraph/mgmt/2019-04-01/resourcegraph
go clean -i github.com/Azure/go-autorest/autorest/azure/auth

后续步骤Next steps

本快速入门介绍了如何将 Resource Graph 包添加到 Go 环境并运行第一个查询。In this quickstart, you've added the Resource Graph packages to your Go environment and run your first query. 若要详细了解 Resource Graph 语言,请继续阅读查询语言详细信息页。To learn more about the Resource Graph language, continue to the query language details page.