Create sample code for BatchGetEffectiveIamPolicies API.

Create sample code for BatchGetEffectiveIamPolicies API as part of its launch to GA.

Code sample

Go

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


// Sample asset-quickstart batch get effective iam policies.
package main

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

	asset "cloud.google.com/go/asset/apiv1"
	"cloud.google.com/go/asset/apiv1/assetpb"
)

func main() {
	projectId := flag.String("projectId", "", "Project Id to construct the scope under which the effective IAM policies to get.")
	fullResourceName := flag.String("fullResourceName", "", "Resource on which the IAM policies are effective.")

	flag.Parse()
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	}
	defer client.Close()

	req := &assetpb.BatchGetEffectiveIamPoliciesRequest{
		Scope: fmt.Sprintf("projects/%s", *projectId),
		Names: []string{*fullResourceName},
	}

	op, err := client.BatchGetEffectiveIamPolicies(ctx, req)
	if err != nil {
		log.Fatal(err)
	}
	for index, result := range op.PolicyResults {
		fmt.Println(index, result)
	}
}

Java

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

// Imports the Google Cloud client library

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.BatchGetEffectiveIamPoliciesRequest;
import com.google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * Batch get effective iam policy example.
 */
public class BatchGetEffectiveIamPolicyExample {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String scope = "organizations/ORG_ID";
    String[] resourceNames = {"//cloudresourcemanager.googleapis.com/projects/PROJ_ID"};
    batchGetEffectiveIamPolicies(resourceNames, scope);
  }

  /**
   * Batch get effective iam policies specified list of resources within accessible scope, such as a
   * project, folder or organization.
   *
   * @param resourceNames a string array denoting full resource names.
   * @param scope a string denoting scope, which can be a Project, Folder or Organization.
   */
  public static void batchGetEffectiveIamPolicies(String[] resourceNames, String scope) {
    BatchGetEffectiveIamPoliciesRequest request =
        BatchGetEffectiveIamPoliciesRequest.newBuilder()
            .setScope(scope)
            .addAllNames(Arrays.asList(resourceNames))
            .build();
    try (AssetServiceClient client = AssetServiceClient.create()) {
      BatchGetEffectiveIamPoliciesResponse response = client.batchGetEffectiveIamPolicies(request);
      System.out.println("BatchGetEffectiveIamPolicies completed successfully:\n" + response);
    } catch (IOException e) {
      System.out.println("Failed to create client:\n" + e);
    } catch (ApiException e) {
      System.out.println("Error during BatchGetEffectiveIamPolicies:\n" + e);
    }
  }
}

Node.js

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

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

const client = new AssetServiceClient();

async function batchGetEffectiveIamPolicies() {
  const projectId = await client.getProjectId();
  const request = {
    scope: `projects/${projectId}`,
    names: assetNames.split(','),
  };

  // Handle the operation using the promise pattern.
  const result = await client.batchGetEffectiveIamPolicies(request);
  // Handle the response.
  console.dir(result, {depth: null});
}

Python

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 = 'project ID/number, folder number or org number'
# TODO resource_names = 'List of resource names'

client = asset_v1.AssetServiceClient()

response = client.batch_get_effective_iam_policies(
    request={"scope": scope, "names": resource_names}
)
print(response)

What's next

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