搜索所有资源

在资产中搜索所有资源。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C#

如需了解如何安装和使用 Cloud Asset Inventory 的客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Api.Gax;
using Google.Cloud.Asset.V1;
using System.Collections.Generic;
using System.Linq;

public class SearchAllResourcesSample
{
    public SearchAllResourcesResponse SearchAllResources(string scope, string query)
    {
        // Create the client.
        AssetServiceClient client = AssetServiceClient.Create();

        // Build the request.
        SearchAllResourcesRequest request = new SearchAllResourcesRequest
        {
            Scope = scope,
            Query = query,
        };

        // Call the API.
        PagedEnumerable<SearchAllResourcesResponse, ResourceSearchResult> response = client.SearchAllResources(request);

        // Return the first page.
        IEnumerable<SearchAllResourcesResponse> byPages = response.AsRawResponses();
        return byPages.First();
    }
}

Go

如需了解如何安装和使用 Cloud Asset Inventory 客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// Sample search-all-resources searches all resources within the given scope.
package main

import (
	"context"
	"flag"
	"fmt"
	"log"

	asset "cloud.google.com/go/asset/apiv1"
	"cloud.google.com/go/asset/apiv1/assetpb"
	"google.golang.org/api/iterator"
)

func main() {
	scope := flag.String("scope", "", "Scope of the search.")
	query := flag.String("query", "", "Query statement.")
	flag.Parse()
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	}
	defer client.Close()

	req := &assetpb.SearchAllResourcesRequest{
		Scope: *scope,
		Query: *query,
	}
	it := client.SearchAllResources(ctx, req)
	for {
		resource, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(resource)
	}
}

Java

如需了解如何安装和使用 Cloud Asset Inventory 的客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.AssetServiceClient.SearchAllResourcesPagedResponse;
import com.google.cloud.asset.v1.SearchAllResourcesRequest;
import java.io.IOException;
import java.util.Arrays;

public class SearchAllResourcesExample {

  // Searches for all the resources within the given scope.
  public static void searchAllResources(String scope, String query) {
    // TODO(developer): Replace these variables before running the sample.
    String[] assetTypes = {};
    int pageSize = 0;
    String pageToken = "";
    String orderBy = "";

    SearchAllResourcesRequest request =
        SearchAllResourcesRequest.newBuilder()
            .setScope(scope)
            .setQuery(query)
            .addAllAssetTypes(Arrays.asList(assetTypes))
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .setOrderBy(orderBy)
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AssetServiceClient client = AssetServiceClient.create()) {
      SearchAllResourcesPagedResponse response = client.searchAllResources(request);
      System.out.println("Search completed successfully:\n" + response.getPage().getValues());
    } catch (IOException e) {
      System.out.println(String.format("Failed to create client:%n%s", e.toString()));
    } catch (InvalidArgumentException e) {
      System.out.println(String.format("Invalid request:%n%s", e.toString()));
    } catch (ApiException e) {
      System.out.println(String.format("Error during SearchAllResources:%n%s", e.toString()));
    }
  }
}

Node.js

如需了解如何安装和使用 Cloud Asset Inventory 的客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const scope = '';
// const query = '';
// const assetTypes = [];
// const pageSize = 0;
// const pageToken = '';
// const orderBy = '';

const util = require('util');
const {AssetServiceClient} = require('@google-cloud/asset');

const client = new AssetServiceClient();
const projectId = await client.getProjectId();

async function searchAllResources() {
  const request = {
    scope: `projects/${projectId}`,
    query: query,
    assetTypes: assetTypes,
    pageSize: pageSize,
    pageToken: pageToken,
    orderBy: orderBy,
  };
  const options = {
    autoPaginate: false,
  };

  // Handle the operation using the promise pattern.
  const result = await client.searchAllResources(request, options);
  // Do things with with the response.
  console.log(util.inspect(result, {depth: null}));
}

PHP

如需了解如何安装和使用 Cloud Asset Inventory 的客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Asset\V1\Client\AssetServiceClient;
use Google\Cloud\Asset\V1\SearchAllResourcesRequest;

/**
 * @param string   $scope      Scope of the search
 * @param string   $query      (Optional) Query statement
 * @param string[] $assetTypes (Optional) Asset types to search for
 * @param int      $pageSize   (Optional) Size of each result page
 * @param string   $pageToken  (Optional) Token produced by the preceding call
 * @param string   $orderBy    (Optional) Fields to sort the results
 */
function search_all_resources(
    string $scope,
    string $query = '',
    array $assetTypes = [],
    int $pageSize = 0,
    string $pageToken = '',
    string $orderBy = ''
): void {
    // Instantiate a client.
    $asset = new AssetServiceClient();

    // Run request
    $request = (new SearchAllResourcesRequest())
        ->setScope($scope)
        ->setQuery($query)
        ->setAssetTypes($assetTypes)
        ->setPageSize($pageSize)
        ->setPageToken($pageToken)
        ->setOrderBy($orderBy);
    $response = $asset->searchAllResources($request);

    // Print the resource names in the first page of the result
    foreach ($response->getPage() as $resource) {
        print($resource->getName() . PHP_EOL);
    }
}

Python

如需了解如何安装和使用 Cloud Asset Inventory 的客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import asset_v1

# TODO scope = 'Scope of the search'
# TODO query = 'Query statement'
# TODO asset_types = 'List of asset types to search for'
# TODO page_size = Size of each result page
# TODO order_by = 'Fields to sort the results'

client = asset_v1.AssetServiceClient()
response = client.search_all_resources(
    request={
        "scope": scope,
        "query": query,
        "asset_types": asset_types,
        "page_size": page_size,
        "order_by": order_by,
    }
)
for resource in response:
    print(resource)

Ruby

如需了解如何安装和使用 Cloud Asset Inventory 的客户端库,请参阅 Cloud Asset Inventory 客户端库

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/asset"

# scope = 'SCOPE_OF_THE_QUERY'
# query = 'QUERY_STATEMENT'
# asset_types = 'AN_ARRAY_OF_ASSET_TYPES_TO_SEARCH_FOR'
# page_size = 'SIZE_OF_EACH_RESULT_PAGE'
# page_token = 'TOKEN_PRODUCED_BY_THE_PRECEDING_CALL'
# order_by = 'FIELDS_TO_SORT_THE RESULTS'
asset_service = Google::Cloud::Asset.asset_service

response = asset_service.search_all_resources(
  scope:       scope,
  query:       query,
  asset_types: asset_types,
  page_size:   page_size,
  page_token:  page_token,
  order_by:    order_by
)
# Do things with the response
response.page.each do |resource|
  puts resource
end

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器