Configurar política de IAM

Organízate con las colecciones Guarda y clasifica el contenido según tus preferencias.

Configura la política de control de acceso de un recurso.

Páginas de documentación que incluyen esta muestra de código

Para ver la muestra de código usada en contexto, consulta la siguiente documentación:

Muestra de código


import (

	healthcare ""

// setDatasetIAMPolicy sets an IAM policy for the dataset.
func setDatasetIAMPolicy(w io.Writer, projectID, location, datasetID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)

	datasetsService := healthcareService.Projects.Locations.Datasets

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID)

	policy, err := datasetsService.GetIamPolicy(name).Do()
	if err != nil {
		return fmt.Errorf("GetIamPolicy: %v", err)

	policy.Bindings = append(policy.Bindings, &healthcare.Binding{
		Members: []string{""},
		Role:    "roles/viewer",

	req := &healthcare.SetIamPolicyRequest{
		Policy: policy,

	policy, err = datasetsService.SetIamPolicy(name, req).Do()
	if err != nil {
		return fmt.Errorf("SetIamPolicy: %v", err)

	fmt.Fprintf(w, "IAM Policy etag: %v", policy.Etag)
	return nil


import java.util.Arrays;
import java.util.Collections;

public class DatasetSetIamPolicy {
  private static final String DATASET_NAME = "projects/%s/locations/%s/datasets/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void datasetSetIamPolicy(String datasetName) throws IOException {
    // String datasetName =
    //     String.format(DATASET_NAME, "your-project-id", "your-region-id", "your-dataset-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Configure the IAMPolicy to apply to the dataset.
    // For more information on understanding IAM roles, see the following:
    Binding binding =
        new Binding()
    Policy policy = new Policy().setBindings(Arrays.asList(binding));
    SetIamPolicyRequest policyRequest = new SetIamPolicyRequest().setPolicy(policy);

    // Create request and configure any parameters.
    Datasets.SetIamPolicy request =
        client.projects().locations().datasets().setIamPolicy(datasetName, policyRequest);

    // Execute the request and process the results.
    Policy updatedPolicy = request.execute();
    System.out.println("Dataset policy has been updated: " + updatedPolicy.toPrettyString());

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see
    GoogleCredentials credential =

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          new HttpCredentialsAdapter(credential).initialize(request);
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)


const google = require('@googleapis/healthcare');
const healthcare ={
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: [''],

const setDatasetIamPolicy = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const member = '';
  // const role = 'roles/healthcare.datasetViewer';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {
    resource: {
      policy: {
        bindings: [
            members: member,
            role: role,

  const dataset = await healthcare.projects.locations.datasets.setIamPolicy(
    'Set dataset IAM policy:',
    JSON.stringify(, null, 2)



def set_dataset_iam_policy(project_id, location, dataset_id, member, role, etag=None):
    """Sets the IAM policy for the specified dataset.

        A single member will be assigned a single role. A member can be any of:

        - allUsers, that is, anyone
        - allAuthenticatedUsers, anyone authenticated with a Google account
        - user:email, as in ''
        - group:email, as in ''
        - domain:domainname, as in ''
        - serviceAccount:email,
            as in ''

        A role can be any IAM role, such as 'roles/viewer', 'roles/owner',
        or 'roles/editor'

    before running the sample.
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"
    # Returns an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client =, api_version)

    # TODO(developer): Uncomment these lines and replace with your values.
    # project_id = 'my-project'  # replace with your GCP project ID
    # location = 'us-central1'  # replace with the dataset's location
    # dataset_id = 'my-dataset'  # replace with your dataset ID
    dataset_name = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id

    policy = {"bindings": [{"role": role, "members": [member]}]}

    if etag is not None:
        policy["etag"] = etag

    request = (
        .setIamPolicy(resource=dataset_name, body={"policy": policy})
    response = request.execute()

    print("etag: {}".format(response.get("name")))
    print("bindings: {}".format(response.get("bindings")))
    return response

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.