Search all IAM policies

Search through assets for all IAM policies.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


// 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"
	"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.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)
	}
}

Java

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * 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

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

/**
 * @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
    $request = (new SearchAllIamPoliciesRequest())
        ->setScope($scope)
        ->setQuery($query)
        ->setPageSize($pageSize)
        ->setPageToken($pageToken);
    $response = $asset->searchAllIamPolicies($request);

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

Python

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.