שליטה בגישה למשאבים ב-Cloud Healthcare API

בדף הזה מוסבר איך לנהל את הגישה למערכי נתונים ולמאגרי נתונים של Cloud Healthcare API באמצעות הרשאות של ניהול זהויות והרשאות גישה (IAM). באמצעות IAM תוכלו לקבוע למי תהיה גישה למערכי הנתונים ולמאגרי הנתונים שלכם. מידע נוסף על IAM ל-Cloud Healthcare API זמין במאמר בנושא בקרת גישה.

סקירה כללית של מדיניות IAM

הגישה למשאב מנוהלת באמצעות מדיניות IAM. מדיניות מכילה מערך שנקרא bindings. המערך הזה מכיל אוסף של קישורים, שהם שיוכים בין חשבונות ראשיים, כמו חשבון משתמש או חשבון שירות, לבין תפקיד. כללי המדיניות מיוצגים באמצעות JSON או YAML.

בדוגמה הבאה של מדיניות אפשר לראות ש-user-1@example.com קיבל את התפקיד roles/healthcare.datasetAdmin, ו-user-2@example.com ו-service-account-13@appspot.gserviceaccount.com קיבלו את התפקיד roles/healthcare.datasetViewer:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

כדי לעדכן מדיניות של משאב, צריך להשתמש בתבנית קריאה-שינוי-כתיבה. אין שיטות נפרדות ליצירה, לשינוי ולביטול של גישת משתמשים.

כדי לעדכן מדיניות:

  1. קוראים את המדיניות הנוכחית באמצעות קריאה ל-method ‏getIamPolicy() של המשאב. לדוגמה, כדי לקרוא את המדיניות הנוכחית של קבוצת נתונים, קוראים את projects.locations.datasets.getIamPolicy.
  2. כדי להוסיף או להסיר חשבונות משתמשים רלוונטיים והרשאות לתפקידים שלהם, עורכים את המדיניות שמוחזרת באמצעות כלי לעריכת טקסט או באופן פרוגרמטי.
  3. כותבים את המדיניות המעודכנת באמצעות קריאה ל-method ‏setIamPolicy() של המשאב. לדוגמה, כדי לכתוב את המדיניות המעודכנת של קבוצת נתונים, קוראים ל-projects.locations.datasets.setIamPolicy.

בקטעים הבאים מוסבר איך לקבל, לשנות ולהגדיר מדיניות למאגר הסכמה. הקטעים האלה מתבססים על מדיניות לדוגמה:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.consentStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.consentReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

אחזור מדיניות

בדוגמאות הבאות אפשר לראות איך קוראים מדיניות IAM ברמת מאגר ההסכמה. מידע נוסף זמין במאמר projects.locations.datasets.consentStores.getIamPolicy.

כדי לראות את מדיניות ה-IAM של מאגר הסכמה:

  1. נכנסים לדף Datasets במסוף Google Cloud .

    למעבר אל Datasets

  2. לוחצים על המזהה של מערך הנתונים שמכיל את מאגר ההסכמות, ואז בוחרים את מאגר ההסכמות שרוצים לקבל לגביו מדיניות.
  3. לוחצים על הצגת חלונית המידע.
  4. כדי לראות את החשבונות הראשיים שהוקצה להם תפקיד מסוים, מרחיבים את התפקיד.

כדי לראות את מדיניות ה-IAM של מאגר הסכמה, מריצים את הפקודה gcloud healthcare consent-stores get-iam-policy. מציינים את השם של מאגר ההסכמות, את השם של מערך הנתונים ואת המיקום.

gcloud healthcare consent-stores get-iam-policy CONSENT_STORE_ID \
    --dataset=DATASET_ID \
    --location=LOCATION

אם הבקשה מצליחה, מוצגים הקישורים.

bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.consentStoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.consentReader
etag: bytes
version: VERSION_NUMBER
const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const getConsentStoreIamPolicy = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const consentStoreId = 'my-consent-store';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/consentStores/${consentStoreId}`;
  const request = {resource_};

  const consentStore =
    await healthcare.projects.locations.datasets.consentStores.getIamPolicy(
      request
    );
  console.log(
    'Got consent store IAM policy:',
    JSON.stringify(consentStore.data, null, 2)
  );
};

getConsentStoreIamPolicy();
def get_consent_store_iam_policy(
    project_id: str, location: str, dataset_id: str, consent_store_id: str
):
    """Gets the IAM policy for the specified consent store.
    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/consent
    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 = discovery.build(service_name, 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 parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the consent store's parent dataset ID
    # consent_store_id = 'my-consent-store'  # replace with the consent store's ID
    consent_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    consent_store_name = "{}/consentStores/{}".format(
        consent_store_parent, consent_store_id
    )

    request = (
        client.projects()
        .locations()
        .datasets()
        .consentStores()
        .getIamPolicy(resource=consent_store_name)
    )
    response = request.execute()

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

כדי לקרוא את מדיניות ה-IAM של מאגר הסכמה, שולחים בקשת GET ומציינים את שם מערך הנתונים, את שם מאגר ההסכמה ואת טוקן הגישה.

בדוגמה הבאה מוצגת בקשת GET באמצעות curl:

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/consentStores/CONSENT_STORE_ID:getIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.consentStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.consentReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

כדי לקרוא את מדיניות ה-IAM של מאגר הסכמה, שולחים בקשת GET ומציינים את שם מערך הנתונים, את שם מאגר ההסכמה ואת טוקן הגישה.

בדוגמה הבאה מוצגת בקשת GET באמצעות Windows PowerShell:

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/consentStores/CONSENT_STORE_ID:getIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.consentStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.consentReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

שינוי מדיניות

בדוגמאות הבאות מוענק למשתמש חדש התפקיד roles/healthcare.consentReader. מידע נוסף זמין במאמר projects.locations.datasets.consentStores.setIamPolicy.

הגדרת מדיניות

כדי להגדיר מדיניות IAM ברמת מאגר ההסכמות, מבצעים את השלבים הבאים:

  1. נכנסים לדף Datasets במסוף Google Cloud .

    למעבר אל Datasets

  2. לוחצים על המזהה של מערך הנתונים שמכיל את מאגר ההסכמות, ואז בוחרים את מאגר ההסכמות שרוצים להגדיר לו מדיניות.
  3. לוחצים על הצגת חלונית המידע.
  4. לוחצים על Add principal.
  5. בשדה New principals, מזינים את הזהות (או הזהויות) שצריכה גישה למאגר הסכמה.
  6. ברשימה Select a role, בקטע Cloud Healthcare, בוחרים את ההרשאה שרוצים להעניק. לדוגמה, בעל הרשאת צפייה במאגר הסכמה ב-Healthcare.
  7. לוחצים על Save.

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק תפקיד למשתמש חדש, מוסיפים את כתובת האימייל שלו למערך members מתחת לקישור roles/healthcare.consentReader:

{
  "role":"roles/healthcare.consentReader",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, מריצים את הפקודה המתאימה של set-iam-policy כדי שהשינויים יתעדכנו. כדי להגדיר מדיניות ברמת מאגר הסכמה, מריצים את הפקודה gcloud healthcare consent-stores set-iam-policy. מציינים את השם של מאגר ההסכמה, את השם של מערך הנתונים, את המיקום ואת הנתיב לקובץ המדיניות שיצרתם.

gcloud healthcare consent-stores set-iam-policy CONSENT_STORE_ID \
    --dataset=DATASET_ID \
    --location=LOCATION \
    POLICY_FILE_NAME

אם הבקשה מצליחה, מוצגים השם של מאגר ההסכמה והקישורים.

Updated IAM policy for consentStore [CONSENT_STORE_ID].
bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.consentStoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  - user:NEW_USER_EMAIL_ADDRESS
  role: roles/healthcare.consentReader
etag: bytes
version: VERSION_NUMBER
const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const setConsentStoreIamPolicy = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const consentStoreId = 'my-consent-store';
  // const member = 'user:example@gmail.com';
  // const role = 'roles/healthcare.consentStoreViewer';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/consentStores/${consentStoreId}`;
  const request = {
    resource_,
    resource: {
      policy: {
        bindings: [
          {
            members: member,
            role: role,
          },
        ],
      },
    },
  };

  const consentStore =
    await healthcare.projects.locations.datasets.consentStores.setIamPolicy(
      request
    );
  console.log(
    'Set consent store IAM policy:',
    JSON.stringify(consentStore.data, null, 2)
  );
};

setConsentStoreIamPolicy();
def set_consent_store_iam_policy(
    project_id: str,
    location: str,
    dataset_id: str,
    consent_store_id: str,
    member,
    role,
    etag=None,
):
    """Sets the IAM policy for the specified consent store.
    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'
    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/consent
    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 = discovery.build(service_name, 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 parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the consent store's parent dataset ID
    # consent_store_id = 'my-consent-store'  # replace with the consent store's ID
    # member = 'myemail@example.com'  # replace with an authorized member
    # role = 'roles/viewer'  # replace with a Healthcare API IAM role
    consent_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    consent_store_name = "{}/consentStores/{}".format(
        consent_store_parent, consent_store_id
    )

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

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

    request = (
        client.projects()
        .locations()
        .datasets()
        .consentStores()
        .setIamPolicy(resource=consent_store_name, body={"policy": policy})
    )
    response = request.execute()

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

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק תפקיד למשתמש חדש, מוסיפים את כתובת האימייל שלו למערך members מתחת לקישור roles/healthcare.consentReader:

{
  "role":"roles/healthcare.consentReader",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.locations.datasets.consentStores.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת מאגר ההסכמות, שולחים POSTבקשה ומציינים את שם מערך הנתונים, את שם מאגר ההסכמות, את המדיניות ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl להענקת התפקיד הקיים roles/healthcare.consentReader למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
curl -X POST \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'policy': {
        'bindings': [
          {
            'role':'roles/healthcare.consentStoreAdmin',
            'members': [
              'user:user-1@example.com'
            ]
          },
          {
            'role':'roles/healthcare.consentReader',
            'members': [
              'serviceAccount:service-account-13@appspot.gserviceaccount.com',
              'user:user-2@example.com',
              'user:NEW_USER_EMAIL_ADDRESS'
            ]
          }
        ]
      }
    }" "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/consentStores/CONSENT_STORE_ID:setIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.consentStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.consentReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק תפקיד למשתמש חדש, מוסיפים את כתובת האימייל שלו למערך members מתחת לקישור roles/healthcare.consentReader:

{
  "role":"roles/healthcare.consentReader",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.locations.datasets.consentStores.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת מאגר ההסכמות, שולחים POSTבקשה ומציינים את שם מערך הנתונים, את שם מאגר ההסכמות, את המדיניות ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות Windows PowerShell להקצאת התפקיד הקיים roles/healthcare.consentReader למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
    'policy': {
      'bindings': [
        {
          'role': 'roles/healthcare.consentStoreAdmin',
          'members': [
            'user:user-1@example.com',
          ]
        },
        {
          'role': 'roles/healthcare.consentReader',
          'members': [
            'serviceAccount:service-account-13@appspot.gserviceaccount.com',
            'user:user-2@example.com',
            'user:NEW_USER_EMAIL_ADDRESS'
          ]
        }
      ]
    }
  }" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/consentStores/CONSENT_STORE_ID:setIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.consentStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.consentReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

שימוש ב-IAM עם מערכי נתונים

בקטעים הבאים מוסבר איך לקבל, לשנות ולהגדיר מדיניות עבור מערך נתונים. הקטעים האלה מתבססים על מדיניות לדוגמה:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

אחזור מדיניות

בדוגמאות הבאות אפשר לראות איך קוראים מדיניות IAM ברמת מערך הנתונים. מידע נוסף זמין במאמר projects.locations.datasets.getIamPolicy.

curl

כדי לקרוא את מדיניות ה-IAM של מערך נתונים, שולחים בקשת GET ומציינים את השם של מערך הנתונים ואסימון גישה.

בדוגמה הבאה מוצגת בקשת GET באמצעות curl:

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID:getIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

PowerShell

כדי לראות את מדיניות ה-IAM של מערך נתונים, שולחים בקשת GET ומציינים את השם של מערך הנתונים ואת טוקן הגישה.

בדוגמה הבאה מוצגת בקשת GET באמצעות Windows PowerShell:

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID:getIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

המסוף

כדי לראות את מדיניות ה-IAM של מערך נתונים:
  1. נכנסים לדף Datasets במסוף Google Cloud .

    למעבר אל Datasets

  2. בוחרים מערך נתונים ולוחצים על הצגת חלונית המידע.
  3. כדי לראות את החשבונות הראשיים שהוקצה להם תפקיד מסוים, מרחיבים את התפקיד.

gcloud

כדי לראות את מדיניות ה-IAM של מערך נתונים, מריצים את הפקודה gcloud healthcare datasets get-iam-policy. מציינים את השם של מערך הנתונים ואת המיקום.

gcloud healthcare datasets get-iam-policy DATASET_ID \
    --location=LOCATION

אם הבקשה מצליחה, מוצגים הקישורים.

bindings:
- members:
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.datasetViewer
etag: bytes
version: VERSION_NUMBER

Go

import (
	"context"
	"fmt"
	"io"

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

// datasetIAMPolicy gets the dataset's IAM policy.
func datasetIAMPolicy(w io.Writer, projectID, location, datasetID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %w", 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: %w", err)
	}

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

Java

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.gson.GsonFactory;
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.Policy;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

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

  public static void datasetGetIamPolicy(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();

    // Create request and configure any parameters.
    Datasets.GetIamPolicy request =
        client.projects().locations().datasets().getIamPolicy(datasetName);

    // Execute the request and process the results.
    Policy policy = request.execute();
    System.out.println("Dataset IAMPolicy retrieved: \n" + policy.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 =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const getDatasetIamPolicy = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {resource_};

  const dataset =
    await healthcare.projects.locations.datasets.getIamPolicy(request);
  console.log(
    'Got dataset IAM policy:',
    JSON.stringify(dataset.data, null, 2)
  );
};

getDatasetIamPolicy();

Python

# Imports the Dict and Any types for runtime type hints.
from typing import Any, Dict


def get_dataset_iam_policy(
    project_id: str, location: str, dataset_id: str
) -> Dict[str, Any]:
    """Gets the IAM policy for the specified dataset.

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/datasets
    before running the sample.
    See https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.html#getIamPolicy
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Google Cloud project you want
          to use.
      location: The name of the dataset's location.
      dataset_id: The ID of the dataset containing the IAM policy to get.

    Returns:
      A dictionary representing an IAM policy.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    # Imports HttpError from the Google Python API client errors module.
    from googleapiclient.errors import HttpError

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

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

    request = (
        client.projects().locations().datasets().getIamPolicy(resource=dataset_name)
    )

    try:
        response = request.execute()
        print("etag: {}".format(response.get("name")))
        return response
    except HttpError as err:
        raise err

שינוי מדיניות

בדוגמאות הבאות מוענק למשתמש חדש התפקיד roles/healthcare.datasetViewer:

הגדרת מדיניות

המסוף

כדי להגדיר מדיניות IAM ברמת מערך הנתונים, מבצעים את השלבים הבאים:

  1. נכנסים לדף Datasets במסוף Google Cloud .

    למעבר אל Datasets

  2. בוחרים את מערך הנתונים שרוצים להגדיר לו מדיניות ולוחצים על הצגת חלונית המידע.
  3. לוחצים על Add principal.
  4. בשדה New principals, מזינים את הזהות (או הזהויות) שצריכה גישה למערך הנתונים.
  5. ברשימה Select a role, בקטע Cloud Healthcare, בוחרים את ההרשאה שרוצים להעניק. לדוגמה, Healthcare Dataset Viewer.
  6. לוחצים על Save.

gcloud

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק תפקיד למשתמש חדש, מוסיפים את כתובת האימייל שלו למערך members מתחת לקישור roles/healthcare.datasetViewer:

{
  "role":"roles/healthcare.datasetViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, מריצים את הפקודה המתאימה של set-iam-policy כדי שהשינויים יתעדכנו. כדי להגדיר מדיניות ברמת מערך הנתונים, מריצים את הפקודה gcloud healthcare datasets set-iam-policy. מציינים את השם של מערך הנתונים, את המיקום ואת הנתיב לקובץ המדיניות שיצרתם.

gcloud healthcare datasets set-iam-policy DATASET_ID \
    --location=LOCATION \
    POLICY_FILE_NAME

אם הבקשה מצליחה, מוצגים שם מערך הנתונים והקישורים.

Updated IAM policy for dataset [DATASET_ID].
bindings:
- members:
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.datasetAdmin
  - user:user-1@example.com
  - user:NEW_USER_EMAIL_ADDRESS
  role: roles/healthcare.datasetViewer
etag: bytes
version: VERSION_NUMBER

curl

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק תפקיד למשתמש חדש, מוסיפים את כתובת האימייל שלו למערך members מתחת לקישור roles/healthcare.datasetViewer:

{
  "role":"roles/healthcare.datasetViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.locations.datasets.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת מערך הנתונים, שולחים POSTבקשה ומציינים את השם של מערך הנתונים, את המדיניות ואת טוקן הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl להענקת התפקיד הקיים roles/healthcare.datasetViewer למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
curl -X POST \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'policy': {
        'bindings': [
          {
            'role':'roles/healthcare.datasetAdmin',
            'members': [
              'user:user-1@example.com'
            ]
          },
          {
            'role':'roles/healthcare.datasetViewer',
            'members': [
              'serviceAccount:service-account-13@appspot.gserviceaccount.com',
              'user:user-2@example.com',
              'user:NEW_USER_EMAIL_ADDRESS'
            ]
          }
        ]
      }
    }" "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID:setIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

PowerShell

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק תפקיד למשתמש חדש, מוסיפים את כתובת האימייל שלו למערך members מתחת לקישור roles/healthcare.datasetViewer:

{
  "role":"roles/healthcare.datasetViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.locations.datasets.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת מערך הנתונים, שולחים POSTבקשה ומציינים את השם של מערך הנתונים, את המדיניות ואת טוקן הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות Windows PowerShell להקצאת התפקיד הקיים roles/healthcare.datasetViewer למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
    'policy': {
      'bindings': [
        {
          'role': 'roles/healthcare.datasetAdmin',
          'members': [
            'user:user-1@example.com'
          ]
        },
        {
          'role': 'roles/healthcare.datasetViewer',
          'members': [
            'serviceAccount:service-account-13@appspot.gserviceaccount.com',
            'user:user-2@example.com',
            'user:NEW_USER_EMAIL_ADDRESS'
          ]
        }
      ]
    }
  }" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID:setIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

	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: %w", 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: %w", 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: %w", err)
	}

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

Java

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.gson.GsonFactory;
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 GsonFactory();
  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()
            .setRole("roles/healthcare.datasetViewer")
            .setMembers(Arrays.asList("domain:google.com"));
    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 =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

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 = 'user:example@gmail.com';
  // const role = 'roles/healthcare.datasetViewer';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {
    resource_,
    resource: {
      policy: {
        bindings: [
          {
            members: member,
            role: role,
          },
        ],
      },
    },
  };

  const dataset =
    await healthcare.projects.locations.datasets.setIamPolicy(request);
  console.log(
    'Set dataset IAM policy:',
    JSON.stringify(dataset.data, null, 2)
  );
};

setDatasetIamPolicy();

Python

# Imports the Dict and Any types for runtime type hints.
from typing import Any, Dict

def set_dataset_iam_policy(
    project_id: str,
    location: str,
    dataset_id: str,
    member: str,
    role: str,
    etag: str = None,
) -> Dict[str, Any]:
    """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'

    See
    https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/datasets
    before running the sample.
    See https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1.projects.locations.datasets.html#setIamPolicy
    for the Python API reference.

    Args:
      project_id: The project ID or project number of the Google Cloud project you want
          to use.
      location: The name of the dataset's location.
      dataset_id: The ID of the dataset containing the IAM policy to set.
      member: The principals to grant access for a Google Cloud resource.
      role: The role to assign to the list of 'members'.
      etag: The 'etag' returned in a previous getIamPolicy request to ensure that
        setIamPolicy changes apply to the same policy version.

    Returns:
      A dictionary representing an IAM policy.
    """
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    # Imports HttpError from the Google Python API client errors module.
    from googleapiclient.errors import HttpError

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

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

    # TODO(developer): Uncomment these lines and replace with your values.
    # role = 'roles/viewer'
    # member = 'serviceAccount:group@example.com'
    policy = {"bindings": [{"role": role, "members": [member]}]}

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

    request = (
        client.projects()
        .locations()
        .datasets()
        .setIamPolicy(resource=dataset_name, body={"policy": policy})
    )
    try:
        response = request.execute()
        print("etag: {}".format(response.get("name")))
        print("bindings: {}".format(response.get("bindings")))
        return response
    except HttpError as err:
        raise err

שימוש ב-IAM עם מאגרי DICOM

בקטעים הבאים מוסבר איך לקבל, לשנות ולהגדיר מדיניות עבור מאגר DICOM. הקטעים האלה מתבססים על מדיניות לדוגמה:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.dicomStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.dicomViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

אחזור מדיניות

בדוגמאות הבאות אפשר לראות איך קוראים מדיניות IAM ברמת מאגר DICOM. מידע נוסף זמין במאמר projects.locations.datasets.dicomStores.getIamPolicy.

המסוף

כדי לראות את מדיניות ה-IAM של מאגר DICOM:

  1. נכנסים לדף Datasets במסוף Google Cloud .

    למעבר אל Datasets

  2. לוחצים על מזהה מערך הנתונים שמכיל את מאגר DICOM, ואז בוחרים את מאגר DICOM שרוצים לקבל לגביו מדיניות.
  3. לוחצים על הצגת חלונית המידע.
  4. כדי לראות את החשבונות הראשיים שהוקצה להם תפקיד מסוים, מרחיבים את התפקיד.

gcloud

כדי לראות את מדיניות ה-IAM של מאגר DICOM, מריצים את הפקודה gcloud healthcare dicom-stores get-iam-policy. מציינים את שם מאגר DICOM, את שם מערך הנתונים ואת המיקום.

gcloud healthcare dicom-stores get-iam-policy DICOM_STORE_ID \
    --dataset=DATASET_ID \
    --location=LOCATION

אם הבקשה מצליחה, מוצגים הקישורים.

bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.dicomStoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.dicomViewer
etag: bytes
version: VERSION_NUMBER

Go

import (
	"context"
	"fmt"
	"io"

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

// getDICOMIAMPolicy gets the DICOM store's IAM policy.
func getDICOMIAMPolicy(w io.Writer, projectID, location, datasetID, dicomStoreID string) error {
	ctx := context.Background()

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

	dicomService := healthcareService.Projects.Locations.Datasets.DicomStores

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

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

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

Java

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.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.DicomStores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Policy;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

public class DicomStoreGetIamPolicy {
  private static final String DICOM_NAME = "projects/%s/locations/%s/datasets/%s/dicomStores/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void dicomStoreGetIamPolicy(String dicomStoreName) throws IOException {
    // String dicomStoreName =
    //    String.format(
    //        DICOM_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-dicom-id");

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

    // Create request and configure any parameters.
    DicomStores.GetIamPolicy request =
        client.projects().locations().datasets().dicomStores().getIamPolicy(dicomStoreName);

    // Execute the request and process the results.
    Policy policy = request.execute();
    System.out.println("DICOM store IAMPolicy retrieved: \n" + policy.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 =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const getDicomStoreIamPolicy = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const dicomStoreId = 'my-dicom-store';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/dicomStores/${dicomStoreId}`;
  const request = {resource_};

  const dicomStore =
    await healthcare.projects.locations.datasets.dicomStores.getIamPolicy(
      request
    );
  console.log(
    'Got DICOM store IAM policy:',
    JSON.stringify(dicomStore.data, null, 2)
  );
};

getDicomStoreIamPolicy();

Python

def get_dicom_store_iam_policy(project_id, location, dataset_id, dicom_store_id):
    """Gets the IAM policy for the specified DICOM store.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/dicom
    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 = discovery.build(service_name, 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 parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the DICOM store's parent dataset ID
    # dicom_store_id = 'my-dicom-store'  # replace with the DICOM store's ID
    dicom_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    dicom_store_name = f"{dicom_store_parent}/dicomStores/{dicom_store_id}"

    request = (
        client.projects()
        .locations()
        .datasets()
        .dicomStores()
        .getIamPolicy(resource=dicom_store_name)
    )
    response = request.execute()

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

curl

כדי לקרוא את מדיניות IAM של מאגר DICOM, שולחים בקשת GET ומציינים את שם מערך הנתונים, את שם מאגר DICOM ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת GET באמצעות curl:

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/dicomStores/DICOM_STORE_ID:getIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.dicomStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.dicomViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

PowerShell

כדי לקרוא את מדיניות IAM של מאגר DICOM, שולחים בקשת GET ומציינים את שם מערך הנתונים, את שם מאגר DICOM ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת GET באמצעות Windows PowerShell:

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/dicomStores/DICOM_STORE_ID:getIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.dicomStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.dicomViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

שינוי מדיניות

בדוגמאות הבאות מוענק למשתמש חדש התפקיד roles/healthcare.dicomViewer. מידע נוסף זמין במאמר projects.locations.datasets.dicomStores.setIamPolicy.

הגדרת מדיניות

המסוף

כדי להגדיר מדיניות IAM ברמת חנות DICOM, מבצעים את השלבים הבאים:

  1. נכנסים לדף Datasets במסוף Google Cloud .

    למעבר אל Datasets

  2. לוחצים על מזהה מערך הנתונים שמכיל את מאגר DICOM, ואז בוחרים את מאגר DICOM שרוצים להגדיר לו מדיניות.
  3. לוחצים על הצגת חלונית המידע.
  4. לוחצים על Add principal.
  5. בשדה New principals, מזינים את הזהות (או הזהויות) שצריכה גישה למאגר DICOM.
  6. ברשימה Select a role, בקטע Cloud Healthcare, בוחרים את ההרשאה שרוצים להעניק. לדוגמה, Healthcare DICOM Store Viewer.
  7. לוחצים על Save.

gcloud

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק תפקיד למשתמש חדש, מוסיפים את כתובת האימייל שלו למערך members מתחת לקישור roles/healthcare.dicomViewer:

{
  "role":"roles/healthcare.dicomViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, מריצים את הפקודה המתאימה של set-iam-policy כדי שהשינויים יתעדכנו. כדי להגדיר מדיניות ברמת מאגר DICOM, מריצים את הפקודה gcloud healthcare dicom-stores set-iam-policy. מציינים את שם מאגר ה-DICOM, את שם מערך הנתונים, את המיקום ואת הנתיב לקובץ המדיניות שיצרתם.

gcloud healthcare dicom-stores set-iam-policy DICOM_STORE_ID \
    --dataset=DATASET_ID \
    --location=LOCATION \
    POLICY_FILE_NAME

אם הבקשה מצליחה, מוצגים שם מאגר ה-DICOM והקישורים.

Updated IAM policy for dicomStore [DICOM_STORE_ID].
bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.dicomStoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  - user:NEW_USER_EMAIL_ADDRESS
  role: roles/healthcare.dicomViewer
etag: bytes
version: VERSION_NUMBER

Go

import (
	"context"
	"fmt"
	"io"

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

// setDICOMIAMPolicy sets the DICOM store's IAM policy.
func setDICOMIAMPolicy(w io.Writer, projectID, location, datasetID, dicomStoreID string) error {
	ctx := context.Background()

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

	dicomService := healthcareService.Projects.Locations.Datasets.DicomStores

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

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

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

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

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

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

Java

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.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.DicomStores;
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 DicomStoreSetIamPolicy {
  private static final String DICOM_NAME = "projects/%s/locations/%s/datasets/%s/dicomStores/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void dicomStoreSetIamPolicy(String dicomStoreName) throws IOException {
    // String dicomStoreName =
    //    String.format(
    //        DICOM_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-dicom-id");

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

    // Configure the IAMPolicy to apply to the store.
    // For more information on understanding IAM roles, see the following:
    // https://cloud.google.com/iam/docs/understanding-roles
    Binding binding =
        new Binding()
            .setRole("roles/healthcare.dicomStoreAdmin")
            .setMembers(Arrays.asList("domain:google.com"));
    Policy policy = new Policy().setBindings(Arrays.asList(binding));
    SetIamPolicyRequest policyRequest = new SetIamPolicyRequest().setPolicy(policy);

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

    // Execute the request and process the results.
    Policy updatedPolicy = request.execute();
    System.out.println("DICOM 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 =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const setDicomStoreIamPolicy = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const dicomStoreId = 'my-dicom-store';
  // const member = 'user:example@gmail.com';
  // const role = 'roles/healthcare.dicomStoreViewer';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/dicomStores/${dicomStoreId}`;
  const request = {
    resource_,
    resource: {
      policy: {
        bindings: [
          {
            members: member,
            role: role,
          },
        ],
      },
    },
  };

  const dicomStore =
    await healthcare.projects.locations.datasets.dicomStores.setIamPolicy(
      request
    );
  console.log(
    'Set DICOM store IAM policy:',
    JSON.stringify(dicomStore.data, null, 2)
  );
};

setDicomStoreIamPolicy();

Python

def set_dicom_store_iam_policy(
    project_id, location, dataset_id, dicom_store_id, member, role, etag=None
):
    """Sets the IAM policy for the specified DICOM store.

    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'

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/dicom
    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 = discovery.build(service_name, 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 parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the DICOM store's parent dataset ID
    # dicom_store_id = 'my-dicom-store'  # replace with the DICOM store's ID
    # member = 'myemail@example.com'  # replace with an authorized member
    # role = 'roles/viewer'  # replace with a Healthcare API IAM role
    dicom_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    dicom_store_name = f"{dicom_store_parent}/dicomStores/{dicom_store_id}"

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

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

    request = (
        client.projects()
        .locations()
        .datasets()
        .dicomStores()
        .setIamPolicy(resource=dicom_store_name, body={"policy": policy})
    )
    response = request.execute()

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

curl

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק תפקיד למשתמש חדש, מוסיפים את כתובת האימייל שלו למערך members מתחת לקישור roles/healthcare.dicomViewer:

{
  "role":"roles/healthcare.dicomViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.locations.datasets.dicomStores.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת מאגר DICOM, שולחים בקשת POST ומציינים את שם מערך הנתונים, את שם מאגר DICOM, את המדיניות ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl להענקת התפקיד הקיים roles/healthcare.dicomViewer למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
curl -X POST \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'policy': {
        'bindings': [
          {
            'role':'roles/healthcare.dicomStoreAdmin',
            'members': [
              'user:user-1@example.com'
            ]
          },
          {
            'role':'roles/healthcare.dicomViewer',
            'members': [
              'serviceAccount:service-account-13@appspot.gserviceaccount.com',
              'user:user-2@example.com',
              'user:NEW_USER_EMAIL_ADDRESS'
            ]
          }
        ]
      }
    }" "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/dicomStores/DICOM_STORE_ID:setIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.dicomStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.dicomViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

PowerShell

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק תפקיד למשתמש חדש, מוסיפים את כתובת האימייל שלו למערך members מתחת לקישור roles/healthcare.dicomViewer:

{
  "role":"roles/healthcare.dicomViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.locations.datasets.dicomStores.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת מאגר DICOM, שולחים בקשת POST ומציינים את שם מערך הנתונים, את שם מאגר DICOM, את המדיניות ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות Windows PowerShell להקצאת התפקיד הקיים roles/healthcare.dicomViewer למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
    'policy': {
      'bindings': [
        {
          'role': 'roles/healthcare.dicomStoreAdmin',
          'members': [
            'user:user-1@example.com',
          ]
        },
        {
          'role': 'roles/healthcare.dicomViewer',
          'members': [
            'serviceAccount:service-account-13@appspot.gserviceaccount.com',
            'user:user-2@example.com',
            'user:NEW_USER_EMAIL_ADDRESS'
          ]
        }
      ]
    }
  }" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/dicomStores/DICOM_STORE_ID:setIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.dicomStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.dicomViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

שימוש ב-IAM עם מאגרי FHIR

בקטעים הבאים מוסבר איך לקבל, לשנות ולהגדיר מדיניות עבור מאגר FHIR. הקטעים האלה מתבססים על מדיניות לדוגמה:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.fhirStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.fhirResourceReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

אחזור מדיניות

בדוגמאות הבאות אפשר לראות איך קוראים מדיניות IAM ברמת מאגר FHIR. מידע נוסף זמין במאמר projects.locations.datasets.fhirStores.getIamPolicy.

המסוף

כדי לראות את מדיניות ה-IAM של מאגר FHIR:

  1. נכנסים לדף Datasets במסוף Google Cloud .

    למעבר אל Datasets

  2. לוחצים על המזהה של מערך הנתונים שמכיל את מאגר ה-FHIR, ואז בוחרים את מאגר ה-FHIR שעבורו רוצים לקבל מדיניות.
  3. לוחצים על הצגת חלונית המידע.
  4. כדי לראות את החשבונות הראשיים שהוקצה להם תפקיד מסוים, מרחיבים את התפקיד.

gcloud

כדי לראות את מדיניות ה-IAM של מאגר FHIR, מריצים את הפקודה gcloud healthcare fhir-stores get-iam-policy. מציינים את השם של מאגר FHIR, את השם של מערך הנתונים ואת המיקום.

gcloud healthcare fhir-stores get-iam-policy FHIR_STORE_ID \
    --dataset=DATASET_ID \
    --location=LOCATION

אם הבקשה מצליחה, מוצגים הקישורים.

bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.fhirStoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.fhirResourceReader
etag: bytes
version: VERSION_NUMBER

Go

import (
	"context"
	"fmt"
	"io"

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

// getFHIRIAMPolicy gets the FHIR store's IAM policy.
func getFHIRIAMPolicy(w io.Writer, projectID, location, datasetID, fhirStoreID string) error {
	ctx := context.Background()

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

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores

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

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

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

Java

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.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.FhirStores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Policy;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

public class FhirStoreGetIamPolicy {
  private static final String FHIR_NAME = "projects/%s/locations/%s/datasets/%s/fhirStores/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirStoreGetIamPolicy(String fhirStoreName) throws IOException {
    // String fhirStoreName =
    //    String.format(
    //        FHIR_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-fhir-id");

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

    // Create request and configure any parameters.
    FhirStores.GetIamPolicy request =
        client.projects().locations().datasets().fhirStores().getIamPolicy(fhirStoreName);

    // Execute the request and process the results.
    Policy policy = request.execute();
    System.out.println("FHIR store IAMPolicy retrieved: \n" + policy.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 =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
  responseType: 'json',
});

const getFhirStoreIamPolicy = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}`;
  const request = {resource_};

  try {
    const fhirStore =
      await healthcare.projects.locations.datasets.fhirStores.getIamPolicy(
        request
      );
    console.log(
      'Got FHIR store IAM policy:',
      JSON.stringify(fhirStore.data, null, 2)
    );
  } catch (error) {
    console.error(
      'Error getting FHIR store IAM policy:',
      error.message || error
    );
  }
};

getFhirStoreIamPolicy();

Python

def get_fhir_store_iam_policy(project_id, location, dataset_id, fhir_store_id):
    """Gets the IAM policy for the specified FHIR store.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"
    # Instantiates an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, 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 parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the parent dataset's ID
    # fhir_store_id = 'my-fhir-store' # replace with the FHIR store ID
    fhir_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    fhir_store_name = f"{fhir_store_parent}/fhirStores/{fhir_store_id}"

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .getIamPolicy(resource=fhir_store_name)
    )
    response = request.execute()

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

curl

כדי לקרוא את מדיניות ה-IAM של מאגר FHIR, צריך לשלוח בקשת POST ולציין את שם קבוצת הנתונים, את שם מאגר ה-FHIR ואת טוקן הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl:

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID:getIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.fhirStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.fhirResourceReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

PowerShell

כדי לקרוא את מדיניות ה-IAM של מאגר FHIR, צריך לשלוח בקשת POST ולציין את שם קבוצת הנתונים, את שם מאגר ה-FHIR ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות Windows PowerShell:

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID:getIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.fhirStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.fhirResourceReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

שינוי מדיניות

בדוגמאות הבאות מוענק למשתמש חדש התפקיד roles/healthcare.fhirResourceReader. מידע נוסף זמין במאמר projects.locations.datasets.fhirStores.setIamPolicy.

הגדרת מדיניות

המסוף

כדי להגדיר מדיניות IAM ברמת מאגר FHIR, מבצעים את השלבים הבאים:

  1. נכנסים לדף Datasets במסוף Google Cloud .

    למעבר אל Datasets

  2. לוחצים על המזהה של מערך הנתונים שמכיל את מאגר ה-FHIR, ואז בוחרים את מאגר ה-FHIR שרוצים להגדיר לו מדיניות.
  3. לוחצים על הצגת חלונית המידע.
  4. לוחצים על Add principal.
  5. בשדה New principals, מזינים את הזהות (או הזהויות) שצריכה גישה למאגר FHIR.
  6. ברשימה Select a role, בקטע Cloud Healthcare, בוחרים את ההרשאה שרוצים להעניק. לדוגמה, Healthcare FHIR Resource Reader.
  7. לוחצים על Save.

gcloud

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק למשתמש חדש את התפקיד, מוסיפים את כתובת האימייל שלו למערך members בקטע roles/healthcare.fhirResourceReader binding:

{
  "role":"roles/healthcare.fhirResourceReader",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, מריצים את הפקודה המתאימה של set-iam-policy כדי שהשינויים יתעדכנו. כדי להגדיר מדיניות ברמת מאגר FHIR, מריצים את הפקודה gcloud healthcare fhir-stores set-iam-policy. מציינים את השם של מאגר FHIR, את השם של מערך הנתונים, את המיקום ואת הנתיב לקובץ המדיניות שיצרתם.

gcloud healthcare fhir-stores set-iam-policy FHIR_STORE_ID \
    --dataset=DATASET_ID \
    --location=LOCATION \
    POLICY_FILE_NAME

אם הבקשה תאושר, יוצגו שם מאגר ה-FHIR והקישורים.

Updated IAM policy for fhirStore [FHIR_STORE_ID].
bindings:
- members:
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  - user:NEW_USER_EMAIL_ADDRESS
  role: roles/healthcare.fhirResourceReader
etag: bytes
version: VERSION_NUMBER

Go

import (
	"context"
	"fmt"
	"io"

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

// setFHIRIAMPolicy sets the FHIR store's IAM policy.
func setFHIRIAMPolicy(w io.Writer, projectID, location, datasetID, fhirStoreID string) error {
	ctx := context.Background()

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

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores

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

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

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

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

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

	fmt.Fprintf(w, "IAM Policy version: %v\n", policy.Version)
	return nil
}

Java

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.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.FhirStores;
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 FhirStoreSetIamPolicy {
  private static final String FHIR_NAME = "projects/%s/locations/%s/datasets/%s/fhirStores/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirStoreSetIamPolicy(String fhirStoreName) throws IOException {
    // String fhirStoreName =
    //    String.format(
    //        FHIR_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-fhir-id");

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

    // Configure the IAMPolicy to apply to the store.
    // For more information on understanding IAM roles, see the following:
    // https://cloud.google.com/iam/docs/understanding-roles
    Binding binding =
        new Binding()
            .setRole("roles/healthcare.fhirResourceReader")
            .setMembers(Arrays.asList("domain:google.com"));
    Policy policy = new Policy().setBindings(Arrays.asList(binding));
    SetIamPolicyRequest policyRequest = new SetIamPolicyRequest().setPolicy(policy);

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

    // Execute the request and process the results.
    Policy updatedPolicy = request.execute();
    System.out.println("FHIR 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 =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const setFhirStoreIamPolicy = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  // const member = 'user:example@gmail.com';
  // const role = 'roles/healthcare.fhirStoreViewer';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}`;
  const request = {
    resource_,
    resource: {
      policy: {
        bindings: [
          {
            members: [member],
            role: role,
          },
        ],
      },
    },
  };

  const fhirStore =
    await healthcare.projects.locations.datasets.fhirStores.setIamPolicy(
      request
    );
  console.log(
    'Set FHIR store IAM policy:',
    JSON.stringify(fhirStore.data, null, 2)
  );
};

setFhirStoreIamPolicy();

Python

def set_fhir_store_iam_policy(
    project_id,
    location,
    dataset_id,
    fhir_store_id,
    member,
    role,
    etag=None,
):
    """Sets the IAM policy for the specified FHIR store.
        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'

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/fhir
    before running the sample."""
    # Imports the Google API Discovery Service.
    from googleapiclient import discovery

    api_version = "v1"
    service_name = "healthcare"
    # Instantiates an authorized API client by discovering the Healthcare API
    # and using GOOGLE_APPLICATION_CREDENTIALS environment variable.
    client = discovery.build(service_name, 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 parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the parent dataset's ID
    # fhir_store_id = 'my-fhir-store' # replace with the FHIR store ID
    # member = 'myemail@example.com'  # replace with an authorized member
    # role = 'roles/viewer'  # replace with a Healthcare API IAM role
    fhir_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    fhir_store_name = f"{fhir_store_parent}/fhirStores/{fhir_store_id}"

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

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

    request = (
        client.projects()
        .locations()
        .datasets()
        .fhirStores()
        .setIamPolicy(resource=fhir_store_name, body={"policy": policy})
    )
    response = request.execute()

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

curl

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק למשתמש חדש את התפקיד, מוסיפים את כתובת האימייל שלו למערך members בקטע roles/healthcare.fhirResourceReader binding:

{
  "role":"roles/healthcare.fhirResourceReader",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.locations.datasets.fhirStores.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת מאגר FHIR, שולחים בקשת POST ומציינים את שם מערך הנתונים, את שם מאגר ה-FHIR, את המדיניות ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl להענקת התפקיד הקיים roles/healthcare.fhirResourceReader למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
curl -X POST \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'policy': {
        'bindings': [
          {
            'role':'roles/healthcare.fhirStoreAdmin',
            'members': [
              'user:user-1@example.com'
            ]
          },
          {
            'role':'roles/healthcare.fhirResourceReader',
            'members': [
              'serviceAccount:service-account-13@appspot.gserviceaccount.com',
              'user:user-2@example.com',
              'user:NEW_USER_EMAIL_ADDRESS'
            ]
          }
        ]
      }
    }" "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID:setIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.fhirStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.fhirResourceViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

PowerShell

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק למשתמש חדש את התפקיד, מוסיפים את כתובת האימייל שלו למערך members בקטע roles/healthcare.fhirResourceReader binding:

{
  "role":"roles/healthcare.fhirResourceReader",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.locations.datasets.fhirStores.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת מאגר FHIR, שולחים בקשת POST ומציינים את שם מערך הנתונים, את שם מאגר ה-FHIR, את המדיניות ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות Windows PowerShell להקצאת התפקיד הקיים roles/healthcare.fhirResourceReader למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
    'policy': {
      'bindings': [
        {
          'role': 'roles/healthcare.fhirStoreAdmin',
          'members': [
            'user:user-1@example.com',
          ]
        },
        {
          'role': 'roles/healthcare.fhirResourceReader',
          'members': [
            'serviceAccount:service-account-13@appspot.gserviceaccount.com',
            'user:user-2@example.com',
            'user:NEW_USER_EMAIL_ADDRESS'
          ]
        }
      ]
    }
  }" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID:setIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.fhirStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.fhirResourceViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

שימוש ב-IAM עם חנויות HL7v2

בקטעים הבאים מוסבר איך לקבל, לשנות ולהגדיר מדיניות לחנות HL7v2. הקטעים האלה מתבססים על מדיניות לדוגמה:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.hl7V2StoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.hl7V2Consumer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

אחזור מדיניות

בדוגמאות הבאות אפשר לראות איך קוראים מדיניות IAM ברמת מאגר HL7v2. מידע נוסף זמין במאמר projects.locations.datasets.hl7V2Stores.getIamPolicy.

המסוף

כדי לראות את מדיניות ה-IAM של מאגר HL7v2:

  1. נכנסים לדף Datasets במסוף Google Cloud .

    למעבר אל Datasets

  2. לוחצים על המזהה של מערך הנתונים שמכיל את החנות ב-HL7v2, ואז בוחרים את החנות ב-HL7v2 שרוצים לקבל לגביה מדיניות.
  3. לוחצים על הצגת חלונית המידע.
  4. כדי לראות את החשבונות הראשיים שהוקצה להם תפקיד מסוים, מרחיבים את התפקיד.

gcloud

כדי לראות את מדיניות ה-IAM של מאגר HL7v2, מריצים את הפקודה hl7v2-stores get-iam-policy. מציינים את השם של חנות HL7v2, את השם של מערך הנתונים ואת המיקום.

gcloud healthcare hl7v2-stores get-iam-policy HL7V2_STORE_ID \
    --dataset=DATASET_ID \
    --location=LOCATION

אם הבקשה מצליחה, מוצגים הקישורים.

bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.hl7v2StoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.hl7v2Consumer
etag: bytes
version: VERSION_NUMBER

curl

כדי לקרוא את מדיניות ה-IAM של חנות HL7v2, שולחים בקשת GET ומציינים את השם של מערך הנתונים, את השם של חנות HL7v2 ואת טוקן הגישה.

בדוגמה הבאה מוצגת בקשת GET באמצעות curl:

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID:getIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.hl7V2StoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.hl7V2Consumer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

PowerShell

כדי לקרוא את מדיניות ה-IAM של חנות HL7v2, שולחים בקשת GET ומציינים את השם של מערך הנתונים, את השם של חנות HL7v2 ואת טוקן הגישה.

בדוגמה הבאה מוצגת בקשת GET באמצעות Windows PowerShell:

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID:getIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.hl7V2StoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.hl7V2Consumer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

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

// hl7V2IAMPolicy gets the IAM policy.
func hl7V2IAMPolicy(w io.Writer, projectID, location, datasetID, hl7V2StoreID string) error {
	ctx := context.Background()

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

	storesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores

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

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

	fmt.Fprintf(w, "IAM policy etag: %q\n", policy.Etag)
	return nil
}

Java

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.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores;
import com.google.api.services.healthcare.v1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1.model.Policy;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

public class Hl7v2StoreGetIamPolicy {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2StoreGetIamPolicy(String hl7v2StoreName) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");

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

    // Create request and configure any parameters.
    Hl7V2Stores.GetIamPolicy request =
        client.projects().locations().datasets().hl7V2Stores().getIamPolicy(hl7v2StoreName);

    // Execute the request and process the results.
    Policy policy = request.execute();
    System.out.println("HL7v2 store IAMPolicy retrieved: \n" + policy.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 =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const getHl7v2StoreIamPolicy = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {resource_};

  const hl7v2Store =
    await healthcare.projects.locations.datasets.hl7V2Stores.getIamPolicy(
      request
    );
  console.log(
    'Got HL7v2 store IAM policy:',
    JSON.stringify(hl7v2Store.data, null, 2)
  );
};

getHl7v2StoreIamPolicy();

Python

def get_hl7v2_store_iam_policy(project_id, location, dataset_id, hl7v2_store_id):
    """Gets the IAM policy for the specified HL7v2 store.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    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 = discovery.build(service_name, 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 parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the HL7v2 store's parent dataset
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    hl7v2_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    hl7v2_store_name = f"{hl7v2_store_parent}/hl7V2Stores/{hl7v2_store_id}"

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .getIamPolicy(resource=hl7v2_store_name)
    )
    response = request.execute()

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

שינוי מדיניות

בדוגמאות הבאות מוענק למשתמש חדש התפקיד roles/healthcare.hl7V2Consumer. מידע נוסף זמין במאמר projects.locations.datasets.hl7V2Stores.setIamPolicy.

הגדרת מדיניות

המסוף

כדי להגדיר מדיניות IAM ברמת מאגר HL7v2, מבצעים את השלבים הבאים:

  1. נכנסים לדף Datasets במסוף Google Cloud .

    למעבר אל Datasets

  2. לוחצים על מזהה מערך הנתונים שמכיל את החנות ב-HL7v2, ואז בוחרים את החנות ב-HL7v2 שרוצים להגדיר לה מדיניות.
  3. לוחצים על הצגת חלונית המידע.
  4. לוחצים על Add principal.
  5. בשדה New principals, מזינים את הזהות (או הזהויות) שצריכה גישה לחנות HL7v2.
  6. ברשימה Select a role, בקטע Cloud Healthcare, בוחרים את ההרשאה שרוצים להעניק. לדוגמה, צרכן הודעות של Healthcare HL7v2.
  7. לוחצים על Save.

gcloud

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק למשתמש חדש את התפקיד, מוסיפים את כתובת האימייל שלו למערך members בקטע roles/healthcare.hl7V2Consumer binding:

{
  "role":"roles/healthcare.hl7V2Consumer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, מריצים את הפקודה המתאימה של set-iam-policy כדי שהשינויים יתעדכנו. כדי להגדיר מדיניות ברמת חנות HL7v2, מריצים את הפקודה gcloud healthcare hl7v2-stores set-iam-policy. מציינים את שם החנות ב-HL7v2, את שם מערך הנתונים, את המיקום ואת הנתיב לקובץ המדיניות שיצרתם.

gcloud healthcare hl7v2-stores set-iam-policy HL7V2_STORE_ID \
    --dataset=DATASET_ID \
    --location=LOCATION \
    POLICY_FILE_NAME

אם הבקשה מצליחה, מוצגים שם מאגר HL7v2 והקישורים.

Updated IAM policy for hl7v2Store [HL7V2_STORE_ID].
bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.hl7v2StoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  - user:NEW_USER_EMAIL_ADDRESS
  role: roles/healthcare.hl7v2Consumer
etag: bytes
version: VERSION_NUMBER

curl

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק למשתמש חדש את התפקיד, מוסיפים את כתובת האימייל שלו למערך members בקטע roles/healthcare.hl7V2Consumer binding:

{
  "role":"roles/healthcare.hl7V2Consumer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.locations.datasets.hl7V2Stores.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת חנות HL7v2, שולחים בקשת POST ומציינים את שם מערך הנתונים, את שם חנות HL7v2, את המדיניות ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl להענקת התפקיד הקיים roles/healthcare.hl7V2Consumer למשתמש חדש.

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
curl -X POST \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'policy': {
        'bindings': [
          {
            'role':'roles/healthcare.hl7V2StoreAdmin',
            'members': [
              'user:user-1@example.com'
            ]
          },
          {
            'role':'roles/healthcare.hl7V2Consumer',
            'members': [
              'serviceAccount:service-account-13@appspot.gserviceaccount.com',
              'user:user-2@example.com',
              'user:NEW_USER_EMAIL_ADDRESS'
            ]
          }
        ]
      }
    }" "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID:setIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.hl7V2StoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.hl7V2Consumer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

PowerShell

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להעניק למשתמש חדש את התפקיד, מוסיפים את כתובת האימייל שלו למערך members בקטע roles/healthcare.hl7V2Consumer binding:

{
  "role":"roles/healthcare.hl7V2Consumer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.locations.datasets.hl7V2Stores.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת חנות HL7v2, שולחים בקשת POST ומציינים את שם מערך הנתונים, את שם חנות HL7v2, את המדיניות ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl להענקת התפקיד הקיים roles/healthcare.hl7V2Consumer למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
    'policy': {
      'bindings': [
        {
          'role': 'roles/healthcare.hl7V2StoreAdmin',
          'members': [
            'user:user-1@example.com',
          ]
        },
        {
          'role': 'roles/healthcare.hl7V2Consumer',
          'members': [
            'serviceAccount:service-account-13@appspot.gserviceaccount.com',
            'user:user-2@example.com',
            'user:NEW_USER_EMAIL_ADDRESS'
          ]
        }
      ]
    }
  }" `
  -Uri "https://healthcare.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID:setIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.hl7V2StoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.hl7V2Consumer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

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

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

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

	storesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores

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

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

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

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

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

	fmt.Fprintf(w, "Sucessfully set IAM Policy.\n")
	return nil
}

Java

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.gson.GsonFactory;
import com.google.api.services.healthcare.v1.CloudHealthcare;
import com.google.api.services.healthcare.v1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores;
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 Hl7v2StoreSetIamPolicy {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  private static final JsonFactory JSON_FACTORY = new GsonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2StoreSetIamPolicy(String hl7v2StoreName) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");

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

    // Configure the IAMPolicy to apply to the store.
    // For more information on understanding IAM roles, see the following:
    // https://cloud.google.com/iam/docs/understanding-roles
    Binding binding =
        new Binding()
            .setRole("roles/healthcare.hl7V2Consumer")
            .setMembers(Arrays.asList("domain:google.com"));
    Policy policy = new Policy().setBindings(Arrays.asList(binding));
    SetIamPolicyRequest policyRequest = new SetIamPolicyRequest().setPolicy(policy);

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

    // Execute the request and process the results.
    Policy updatedPolicy = request.execute();
    System.out.println("HL7v2 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 =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // 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)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const google = require('@googleapis/healthcare');
const healthcare = google.healthcare({
  version: 'v1',
  auth: new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  }),
});

const setHl7v2StoreIamPolicy = async () => {
  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const dicomStoreId = 'my-dicom-store';
  // const member = 'user:example@gmail.com';
  // const role = 'roles/healthcare.hl7V2StoreViewer';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {
    resource_,
    resource: {
      policy: {
        bindings: [
          {
            members: member,
            role: role,
          },
        ],
      },
    },
  };

  const hl7v2Store =
    await healthcare.projects.locations.datasets.hl7V2Stores.setIamPolicy(
      request
    );
  console.log(
    'Set HL7v2 store IAM policy:',
    JSON.stringify(hl7v2Store.data, null, 2)
  );
};

setHl7v2StoreIamPolicy();

Python

def set_hl7v2_store_iam_policy(
    project_id, location, dataset_id, hl7v2_store_id, member, role, etag=None
):
    """Sets the IAM policy for the specified HL7v2 store.
        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'.

    See https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/healthcare/api-client/v1/hl7v2
    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 = discovery.build(service_name, 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 parent dataset's location
    # dataset_id = 'my-dataset'  # replace with the HL7v2 store's parent dataset
    # hl7v2_store_id = 'my-hl7v2-store'  # replace with the HL7v2 store's ID
    # member = 'myemail@example.com'  # replace with an authorized member
    # role = 'roles/viewer'  # replace with a Healthcare API IAM role
    hl7v2_store_parent = "projects/{}/locations/{}/datasets/{}".format(
        project_id, location, dataset_id
    )
    hl7v2_store_name = f"{hl7v2_store_parent}/hl7V2Stores/{hl7v2_store_id}"

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

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

    request = (
        client.projects()
        .locations()
        .datasets()
        .hl7V2Stores()
        .setIamPolicy(resource=hl7v2_store_name, body={"policy": policy})
    )
    response = request.execute()

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

שימוש ב-IAM עם Healthcare Natural Language API

בקטעים הבאים מוסבר איך מקבלים, משנים ומגדירים מדיניות עבור Healthcare Natural Language API. הקטעים האלה מתבססים על מדיניות לדוגמה בתור נקודת התחלה:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.nlpServiceViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com"
      ]
    }
  ]
}

אחזור מדיניות

בדוגמאות הבאות מוצגות דרכים לקרוא מדיניות IAM ברמת הפרויקט. מידע נוסף זמין בשיטה projects.getIamPolicy.

curl

כדי לקרוא את מדיניות ה-IAM של פרויקט, שולחים בקשת POST ומציינים את שם הפרויקט ואת טוקן הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl:

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID:getIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.nlpServiceViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com"
      ]
    }
  ]
}

PowerShell

כדי לראות את מדיניות ה-IAM של פרויקט, שולחים בקשת POST ומציינים את שם הפרויקט ואת טוקן הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות Windows PowerShell:

$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method POST `
  -Headers $headers `
  -Uri "https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID:getIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.nlpServiceViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com"
      ]
    }
  ]
}

המסוף

כדי להציג את מדיניות ה-IAM של פרויקט:

  1. נכנסים לדף IAM במסוף Google Cloud .

    כניסה לדף IAM

  2. כדי לראות את חשבונות המשתמשים שהוקצו לתפקיד מסוים, לוחצים על Roles ומרחיבים את התפקיד.

gcloud

כדי לראות את מדיניות ה-IAM של פרויקט, מריצים את הפקודה gcloud projects get-iam-policy. מציינים את שם הפרויקט בבקשה.

gcloud projects get-iam-policy PROJECT_ID 

אם הבקשה מצליחה, מוצגים הקישורים.

bindings:
- members:
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  role: roles/healthcare.nlpServiceViewer
etag: bytes
version: VERSION_NUMBER

שינוי מדיניות

בדוגמאות הבאות מוקצה לשירות התפקיד roles/healthcare.nlpServiceViewer. מידע נוסף זמין במאמר projects.setIamPolicy.

הגדרת מדיניות

המסוף

כדי להגדיר מדיניות IAM ברמת הפרויקט:

  1. נכנסים לדף IAM במסוף Google Cloud .

    כניסה לדף IAM

  2. לוחצים על הלחצן Edit לצד החשבון הראשי, או לוחצים על Add principal ואז בשדה New principals מזינים את הזהות (או הזהויות) שצריכה גישה לפרויקט.
  3. ברשימה Select a role, בקטע Cloud Healthcare, בוחרים באפשרות Healthcare Natural Language Service Viewer.
  4. לוחצים על Save.

gcloud

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להקצות את התפקיד לחשבון שירות חדש, מוסיפים את כתובת האימייל של חשבון השירות למערך members בקטע roles/healthcare.nlpServiceViewerbinding:

{
  "role":"roles/healthcare.nlpServiceViewer",
  "members": [
      "serviceAccount:service-account-13@appspot.gserviceaccount.com",
      "serviceAccount:NEW_SERVICE_ACCOUNT_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, מריצים את הפקודה gcloud projects set-iam-policy כדי שהשינויים יתעדכנו. מציינים את הפרויקט ואת הנתיב לקובץ המדיניות שיצרתם.

gcloud projects set-iam-policy PROJECT_STORE_ID \
    POLICY_FILE_NAME 

אם הבקשה מצליחה, מוצגים שם הפרויקט וההתאמות.

Updated IAM policy for project [PROJECT_ID].
bindings:
- members:
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - serviceAccount:NEW_USER_EMAIL_ADDRESS
  role: roles/healthcare.nlpServiceViewer
etag: bytes
version: VERSION_NUMBER

curl

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להקצות את התפקיד לחשבון שירות חדש, מוסיפים את כתובת האימייל של חשבון השירות למערך members בקטע roles/healthcare.nlpServiceViewerbinding:

{
  "role":"roles/healthcare.nlpServiceViewer",
  "members": [
      "serviceAccount:service-account-13@appspot.gserviceaccount.com",
      "serviceAccount:NEW_SERVICE_ACCOUNT_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת הפרויקט, שולחים בקשת POST ומציינים את שם הפרויקט, את המדיניות ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl להענקת התפקיד הקיים roles/healthcare.nlpServiceViewer למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
curl -X POST \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'policy': {
        'bindings': [
          {
            'role':'roles/healthcare.nlpServiceViewer',
            'members': [
              'serviceAccount:service-account-13@appspot.gserviceaccount.com'
            ]
          }
        ]
      }
    }" "https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID:setIamPolicy"

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.nlpServiceViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com"
      ]
    }
  ]
}

PowerShell

כדי להקצות או לבטל תפקידים למשתמשים, משנים את המדיניות שאוחזרה באופן פרוגרמטי או באמצעות כלי לעריכת טקסט. הערך של etag משתנה כשהמדיניות משתנה, ולכן צריך לציין את הערך הנוכחי.

כדי להקצות את התפקיד לחשבון שירות חדש, מוסיפים את כתובת האימייל של חשבון השירות למערך members בקטע roles/healthcare.nlpServiceViewerbinding:

{
  "role":"roles/healthcare.nlpServiceViewer",
  "members": [
      "serviceAccount:service-account-13@appspot.gserviceaccount.com",
      "serviceAccount:NEW_SERVICE_ACCOUNT_EMAIL_ADDRESS"
  ]
}
כדי לבטל את הגישה של חשבון משתמש, מוחקים את כתובת האימייל שלו ממערך members. כדי לבטל את הגישה של החשבון הראשי האחרון שיש לו תפקיד, מוחקים את מערך ה-bindings של התפקיד. אסור שיהיה במדיניות מערך bindings ריק.

אחרי שמשנים את המדיניות ונותנים את התפקידים הרלוונטיים, צריך לבצע קריאה אל projects.setIamPolicy כדי שהשינויים יתעדכנו.

כדי להגדיר מדיניות IAM ברמת הפרויקט, צריך לשלוח POSTבקשה ולציין את שם הפרויקט, את המדיניות ואת אסימון הגישה.

בדוגמה הבאה מוצגת בקשת POST באמצעות curl להענקת התפקיד הקיים roles/healthcare.nlpServiceViewer למשתמש חדש:

אפשר לכתוב את המדיניות ישירות בבקשה, כמו בדוגמה שמופיעה כאן, או להעביר אותה כקובץ JSON או YAML. דוגמאות לפורמט מדיניות כ-JSON או כ-YAML מופיעות במאמר Policy.
$cred = gcloud auth application-default print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
    'policy': {
      'bindings': [
        {
          'role': 'roles/healthcare.nlpServiceViewer',
          'members': [
            'serviceAccount:service-account-13@appspot.gserviceaccount.com',
            'serviceAccount:NEW_USER_EMAIL_ADDRESS'
          ]
        }
      ]
    }
  }" `
  -Uri "https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID:setIamPolicy" | Select-Object -Expand Content

התגובה היא:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.nlpServiceViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "serviceAccount:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

המאמרים הבאים