Cette page a été traduite par l'API Cloud Translation.
Switch to English

Définir les règles IAM

Définissez la stratégie de contrôle d'accès pour un ensemble de données.

Pages de documentation incluant cet exemple de code

Pour afficher l'exemple de code utilisé en contexte, consultez la documentation suivante :

Exemple de code


import (

	healthcare "google.golang.org/api/healthcare/v1"

// 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{"user:example@example.com"},
		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 com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Binding;
import com.google.api.services.healthcare.v1.model.Policy;
import com.google.api.services.healthcare.v1.model.SetIamPolicyRequest;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
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:
    // https://cloud.google.com/iam/docs/understanding-roles
    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 https://cloud.google.com/docs/authentication/production
    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');
const healthcare = google.healthcare('v1');

const setDatasetIamPolicy = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const member = 'user:example@gmail.com';
  // 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(dataset.data, null, 2)



def set_dataset_iam_policy(
    """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 'user:somebody@example.com'
        - group:email, as in 'group:admins@example.com'
        - domain:domainname, as in 'domain:example.com'
        - serviceAccount:email,
            as in 'serviceAccount:my-other-app@appspot.gserviceaccount.com'

        A role can be any IAM role, such as 'roles/viewer', 'roles/owner',
        or 'roles/editor'
    client = get_client()
    dataset_name = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, dataset_id)

    policy = {
        "bindings": [
                "role": role,
                "members": [

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

    request = client.projects().locations().datasets().setIamPolicy(
        resource=dataset_name, body={'policy': policy})
    response = request.execute()

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