모든 IAM 정책 검색

모든 IAM 정책의 애셋을 검색합니다.

이 코드 샘플이 포함된 문서 페이지

컨텍스트에서 사용된 코드 샘플을 보려면 다음 문서를 참조하세요.

코드 샘플

C#


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

public class SearchAllIamPoliciesSample
{
    public SearchAllIamPoliciesResponse SearchAllIamPolicies(string scope, string query)
    {
        // Create the client.
        AssetServiceClient client = AssetServiceClient.Create();

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

        // Call the API.
        PagedEnumerable<SearchAllIamPoliciesResponse, IamPolicySearchResult> response = client.SearchAllIamPolicies(request);

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

Go


// Sample search-all-iam-policies searches all IAM policies within the given scope.
package main

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

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

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.SearchAllIamPoliciesRequest{
		Scope: *scope,
		Query: *query,
	}
	it := client.SearchAllIamPolicies(ctx, req)
	for {
		policy, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(policy)
	}
}

자바

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.SearchAllIamPoliciesPagedResponse;
import com.google.cloud.asset.v1.SearchAllIamPoliciesRequest;
import java.io.IOException;

public class SearchAllIamPoliciesExample {

  // Searches for all the iam policies within the given scope.
  public static void searchAllIamPolicies(String scope, String query) {
    // TODO(developer): Replace these variables before running the sample.
    int pageSize = 0;
    String pageToken = "";

    SearchAllIamPoliciesRequest request =
        SearchAllIamPoliciesRequest.newBuilder()
            .setScope(scope)
            .setQuery(query)
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .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()) {
      SearchAllIamPoliciesPagedResponse response = client.searchAllIamPolicies(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 SearchAllIamPolicies:%n%s", e.toString()));
    }
  }
}

Node.js

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

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

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

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

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

PHP

use Google\Cloud\Asset\V1\AssetServiceClient;

/**
 * @param string $scope      Scope of the search
 * @param string $query      (Optional) Query statement
 * @param int    $pageSize   (Optional) Size of each result page
 * @param string $pageToken  (Optional) Token produced by the preceding call
 */
function search_all_iam_policies(
    string $scope,
    string $query = '',
    int $pageSize = 0,
    string $pageToken = ''
) {
    // Instantiate a client.
    $asset = new AssetServiceClient();

    // Run request
    $response = $asset->searchAllIamPolicies($scope, [
        'query' => $query,
        'pageSize' => $pageSize,
        'pageToken' => $pageToken
    ]);

    // Print the resources that the policies are set on
    foreach ($response->getPage() as $policy) {
        print($policy->getResource() . PHP_EOL);
    }
}

Python

from google.cloud import asset_v1

# TODO scope = 'Scope of the search'
# TODO query = 'Query statement'
# TODO page_size = Size of each result page

client = asset_v1.AssetServiceClient()
response = client.search_all_iam_policies(
    request={"scope": scope, "query": query, "page_size": page_size}
)
for policy in response:
    print(policy)
    break

Ruby

require "google/cloud/asset"

# scope = 'SCOPE_OF_THE_QUERY'
# query = 'QUERY_STATEMENT'
# page_size = 'SIZE_OF_EACH_RESULT_PAGE'
# page_token = 'TOKEN_PRODUCED_BY_THE_PRECEDING_CALL'
asset_service = Google::Cloud::Asset.asset_service

response = asset_service.search_all_iam_policies(
  scope:      scope,
  query:      query,
  page_size:  page_size,
  page_token: page_token
)
# Do things with the response
response.page.each do |policy|
  puts policy
end

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.