דחיית הגישה למשאבים

בדף הזה מוסבר איך למנוע מחשבונות משתמשים להשתמש בהרשאות ספציפיות של ניהול זהויות והרשאות גישה (IAM) כדי לדחות גישה שלהם.

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

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

אפשר לנהל את כללי מדיניות הדחייה באמצעות מסוף Google Cloud ,‏ Google Cloud CLI או API בארכיטקטורת REST של IAM v2.

לפני שמתחילים

התפקידים הנדרשים

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

  • כדי לצפות בכללי מדיניות הדחייה: דחיית סוקר (roles/iam.denyReviewer)
  • כדי להציג, ליצור, לעדכן ולמחוק כללי מדיניות דחייה: דחיית אדמין (roles/iam.denyAdmin)

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

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

הרשאות נדרשות

כדי לנהל את כללי מדיניות הדחייה נדרשות ההרשאות הבאות:

  • כדי להציג את כללי מדיניות הדחייה:
    • iam.denypolicies.get
    • iam.denypolicies.list
  • כדי ליצור, לעדכן ולמחוק כללי מדיניות דחייה:
    • iam.denypolicies.create
    • iam.denypolicies.delete
    • iam.denypolicies.get
    • iam.denypolicies.update

יכול להיות שתקבלו את ההרשאות האלה באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש אחרים.

זיהוי ההרשאות לדחייה

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

אפשר לדחות רק חלק מההרשאות. רשימת ההרשאות שאפשר לדחות מופיעה במאמר ההרשאות שנתמכות בכללי מדיניות הדחייה.

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

כללי מדיניות הדחייה מנוהלים באמצעות ה-v2 של API ל-REST, שדורש פורמט מיוחד עבור שמות הרשאות. לדוגמה, ההרשאה ליצירת תפקיד ב-IAM בהתאמה אישית ל-IAM נקראת כך:

  • v1 API: iam.roles.create
  • v2 API: iam.googleapis.com/roles.create

יצירה של מדיניות דחייה

אפשר להוסיף כללי מדיניות דחייה לארגונים, לתיקיות ולפרויקטים. לכל משאב יכולים להיות עד 500 כללי מדיניות דחייה.

כללי מדיניות הדחייה כוללים כללי דחייה שבהם מפורטים:

  • ההרשאות לדחייה.
  • חשבונות המשתמשים שעבורם נדחו ההרשאות האלה.
  • אופציונלי: החרגת חשבונות משתמשים מדחיית הרשאות.

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

  • אופציונלי: ביטוי תנאי שמציין את הזמן שבו חשבונות המשתמשים לא יכולים להשתמש בהרשאות. בכללי מדיניות דחייה אפשר להשתמש בביטויי תנאי רק בפונקציות של תגי משאבים – אין תמיכה בפונקציות ובאופרטורים אחרים.

לכל משאב יכולים להיות עד 500 כללי דחייה בכל כללי מדיניות הדחייה שמצורפים אליו.

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

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

המסוף

  1. במסוף Google Cloud , עוברים לכרטיסייה Deny בדף IAM.

    כניסה לדף IAM

  2. בוחרים פרויקט, תיקייה או ארגון.

  3. לוחצים על יצירה של מדיניות דחייה.

  4. בקטע Policy name, מגדירים את מזהה המדיניות באחת מהדרכים הבאות:

    • בשדה שם לתצוגה, מזינים שם לתצוגה של המדיניות. מילוי השדה הזה ימלא אוטומטית את השדה מזהה. אם רוצים לשנות את המזהה של המדיניות, מעדכנים את הטקסט בשדה מזהה.
    • בשדה ID, מזינים מזהה למדיניות.
  5. בקטע Deny rules (כללי דחייה), מגדירים את כללי הדחייה של המדיניות. כל מדיניות דחייה חייבת לכלול לפחות כלל דחייה אחד. כדי להוסיף עוד כללי דחייה, לוחצים על הוספת כלל דחייה.

    לכל כלל דחייה, מבצעים את הפעולות הבאות:

    1. בשדה Denied principals, מוסיפים חשבון משתמש אחד או יותר שרוצים למנוע ממנו להשתמש בהרשאות שצוינו. החשבון הראשי יכול להיות כל אחד מסוגי החשבונות שמופיעים במזהים של חשבונות משתמשים בכללי מדיניות הדחייה, חוץ מחשבונות משתמשים שהמזהים שלהם מתחילים ב-deleted:.
    2. אופציונלי: בשדה Exception principals, מוסיפים את חשבונות המשתמשים שרוצים לאפשר להם להשתמש בהרשאות שצוינו, גם אם החשבונות האלה כלולים בקטע Denied principals. לדוגמה, אפשר להשתמש בשדה הזה כדי להחריג משתמשים ספציפיים ששייכים לקבוצה שנדחתה.

    3. בקטעים Denied permissions, מוסיפים את ההרשאות שרוצים לדחות. ההרשאות חייבות להיות נתמכות בכללי מדיניות הדחייה.

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

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

      כדי להוסיף הרשאות חריגות, לוחצים על הרשאות חריגות, לוחצים על הוספת הרשאה נוספת ומזינים את ההרשאה בשדה הרשאה 1. ממשיכים להוסיף הרשאות עד שמוסיפים את כל ההרשאות שרוצים להחריג ממדיניות הדחייה.

    5. אופציונלי: מוסיפים תנאי דחייה כדי לציין מתי חשבונות המשתמשים לא יכולים להשתמש בהרשאה. כדי להוסיף תנאי דחייה, לוחצים על הוספת תנאי דחייה ומגדירים את השדות הבאים:

      • כותרת: אופציונלי. סיכום קצר של מטרת התנאי.
      • תיאור: אופציונלי. תיאור ארוך יותר של התנאי.
      • ביטוי תנאי: אפשר להוסיף ביטוי תנאי באמצעות הכלי להגדרת תנאים או עורך התנאים. הכלי להגדרת תנאים הוא ממשק אינטראקטיבי שבו בוחרים את סוג התנאי, האופרטור ופרטים רלוונטיים אחרים של הביטוי. עורך התנאים הוא ממשק מבוסס-טקסט שבו מזינים ידנית ביטוי בתחביר Common Expression Language ‏ (CEL).

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

  6. לוחצים על יצירה.

gcloud

כדי ליצור מדיניות דחייה למשאב, קודם יוצרים קובץ JSON שמכיל את המדיניות. אפשר להשתמש בפורמט הבא בשביל מדיניות דחייה:

{
  "displayName": "POLICY_NAME",
  "rules": [
    {
      "denyRule": DENY_RULE_1
    },
    {
      "denyRule": DENY_RULE_2
    },
    {
      "denyRule": DENY_RULE_N
    }
  ]
}

מציינים את הערכים הבאים:

  • POLICY_NAME: השם המוצג של מדיניות הדחייה.
  • DENY_RULE_1, DENY_RULE_2, ...DENY_RULE_N: כללי הדחייה במדיניות. כל כלל דחייה יכול להכיל את השדות הבאים:

    • deniedPermissions: רשימה של הרשאות שחשבונות המשתמשים שצוינו לא יכולים להשתמש בהן. ההרשאות חייבות להיות בתמיכה של כללי מדיניות הדחייה.

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

    • exceptionPermissions: רשימה של הרשאות שחשבונות המשתמשים שצוינו יכולים להשתמש בהן, גם אם ההרשאות האלה כלולות ב-deniedPermissions. לדוגמה, אפשר להשתמש בשדה הזה כדי להחריג הרשאות ספציפיות בקבוצת הרשאות.
    • deniedPrincipals: רשימה של חשבונות משתמשים שלא יכולים להשתמש בהרשאות שצוינו. מידע על הפורמט של מזהי חשבונות משתמשים מופיע במאמר מזהים של חשבונות משתמשים בכללי מדיניות הדחייה.
    • exceptionPrincipals: אופציונלי. רשימה של חשבונות משתמשים שיכולים להשתמש בהרשאות שצוינו, גם אם החשבונות האלה כלולים ב-deniedPrincipals. לדוגמה, ניתן להשתמש בשדה הזה כדי להחריג משתמשים ספציפיים ששייכים לקבוצה שנדחתה. מידע על הפורמט של מזהי חשבונות משתמשים מופיע במאמר מזהים של חשבונות משתמשים בכללי מדיניות הדחייה.

    • denialCondition: אופציונלי. ביטוי תנאי שמציין את הזמן שבו חשבונות המשתמשים לא יכולים להשתמש בהרשאות. מכיל את השדות הבאים:

    דוגמאות של כללי דחייה מופיעים במאמר תרחישים נפוצים לדוגמה.

לדוגמה, מדיניות הדחייה הבאה מכילה כלל דחייה אחד שדוחה הרשאה אחת ללוסיאן:

{
  "displayName": "My deny policy.",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create"
        ]
      }
    }
  ]
}

לאחר מכן, מריצים את הפקודה gcloud iam policies create:

gcloud iam policies create POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --policy-file=POLICY_FILE

מציינים את הערכים הבאים:

  • POLICY_ID: המזהה של מדיניות הדחייה.

  • ATTACHMENT_POINT: מזהה של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

  • POLICY_FILE: הנתיב של קובץ ה-JSON שמכיל את מדיניות הדחייה.

כברירת מחדל, אם הפקודה הזו מצליחה, היא לא מדפיסה פלט. כדי להדפיס תגובה מפורטת, מוסיפים את הדגל --format=json לפקודה.

לדוגמה, אפשר להשתמש בפקודה הבאה כדי ליצור מדיניות דחייה בשם my-deny-policy לפרויקט my-project באמצעות הקובץ policy.json:

gcloud iam policies create my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --policy-file=policy.json

Terraform

במאמר פקודות בסיסיות ב-Terraform אפשר לקרוא הסבר על החלה של הגדרות Terraform ועל הסרה שלהן. למידע נוסף, ראו את מאמרי העזרה לספקים של Terraform.

data "google_project" "default" {
}

# Create a service account
resource "google_service_account" "default" {
  display_name = "IAM Deny Example - Service Account"
  account_id   = "example-sa"
  project      = data.google_project.default.project_id
}

# Create an IAM deny policy that denies a permission for the service account
resource "google_iam_deny_policy" "default" {
  provider     = google-beta
  parent       = urlencode("cloudresourcemanager.googleapis.com/projects/${data.google_project.default.project_id}")
  name         = "my-deny-policy"
  display_name = "My deny policy."
  rules {
    deny_rule {
      denied_principals  = ["principal://iam.googleapis.com/projects/-/serviceAccounts/${google_service_account.default.email}"]
      denied_permissions = ["iam.googleapis.com/roles.create"]
    }
  }
}

Go

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Go API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	"cloud.google.com/go/iam/apiv2/iampb"

	"google.golang.org/genproto/googleapis/type/expr"
)

// createDenyPolicy creates a deny policy.
func createDenyPolicy(w io.Writer, projectID, policyID string) error {
	// You can add deny policies to organizations, folders, and projects.
	// Each of these resources can have up to 5 deny policies.
	// Deny policies contain deny rules, which specify the following:
	// 1. The permissions to deny and/or exempt.
	// 2. The principals that are denied, or exempted from denial.
	// 3. An optional condition on when to enforce the deny rules.

	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	denyRule := &iampb.DenyRule{
		// Add one or more principals who should be denied the permissions specified in this rule.
		// For more information on allowed values,
		// see: https://cloud.google.com/iam/help/deny/principal-identifiers
		DeniedPrincipals: []string{"principalSet://goog/public:all"},
		// Optionally, set the principals who should be exempted from the
		// list of denied principals. For example, if you want to deny certain permissions
		// to a group but exempt a few principals, then add those here.
		// ExceptionPrincipals: []string{"principalSet://goog/group/project-admins@example.com"},
		//
		// Set the permissions to deny.
		// The permission value is of the format: service_fqdn/resource.action
		// For the list of supported permissions,
		// see: https://cloud.google.com/iam/help/deny/supported-permissions
		DeniedPermissions: []string{"cloudresourcemanager.googleapis.com/projects.delete"},
		// Optionally, add the permissions to be exempted from this rule.
		// Meaning, the deny rule will not be applicable to these permissions.
		// ExceptionPermissions: []string{"cloudresourcemanager.googleapis.com/projects.create"},
		//
		// Set the condition which will enforce the deny rule.
		// If this condition is true, the deny rule will be applicable.
		// Else, the rule will not be enforced.
		// The expression uses Common Expression Language syntax (CEL).
		// Here we block access based on tags.
		//
		// Here, we create a deny rule that denies the
		// cloudresourcemanager.googleapis.com/projects.delete permission
		// to everyone except project-admins@example.com for resources that are tagged test.
		// A tag is a key-value pair that can be attached to an organization, folder, or project.
		// For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
		DenialCondition: &expr.Expr{
			Expression: "!resource.matchTag('12345678/env', 'test')",
		},
	}

	// Add the deny rule and a description for it.
	policyRule := &iampb.PolicyRule{
		Description: "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value test",
		Kind: &iampb.PolicyRule_DenyRule{
			DenyRule: denyRule,
		},
	}

	policy := &iampb.Policy{
		DisplayName: "Restrict project deletion access",
		Rules:       [](*iampb.PolicyRule){policyRule},
	}

	req := &iampb.CreatePolicyRequest{
		// Construct the full path of the resource's deny policies.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies"
		Parent:   fmt.Sprintf("policies/%s/denypolicies", attachmentPoint),
		Policy:   policy,
		PolicyId: policyID,
	}
	op, err := policiesClient.CreatePolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create policy: %w", err)
	}

	policy, err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Policy %s created\n", policy.GetName())

	return nil
}

Java

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Java API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.


import com.google.iam.v2.CreatePolicyRequest;
import com.google.iam.v2.DenyRule;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import com.google.iam.v2.PolicyRule;
import com.google.longrunning.Operation;
import com.google.type.Expr;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDenyPolicy {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the id of the Deny policy you want to create.
    String policyId = "deny-policy-id";

    createDenyPolicy(projectId, policyId);
  }

  // Create a deny policy.
  // You can add deny policies to organizations, folders, and projects.
  // Each of these resources can have up to 5 deny policies.
  //
  // Deny policies contain deny rules, which specify the following:
  // 1. The permissions to deny and/or exempt.
  // 2. The principals that are denied, or exempted from denial.
  // 3. An optional condition on when to enforce the deny rules.
  public static void createDenyPolicy(String projectId, String policyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    try (PoliciesClient policiesClient = PoliciesClient.create()) {
      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies", attachmentPoint);

      DenyRule denyRule =
          DenyRule.newBuilder()
              // Add one or more principals who should be denied the permissions specified in this
              // rule.
              // For more information on allowed values, see:
              // https://cloud.google.com/iam/docs/principal-identifiers
              .addDeniedPrincipals("principalSet://goog/public:all")

              // Optionally, set the principals who should be exempted from the
              // list of denied principals. For example, if you want to deny certain permissions
              // to a group but exempt a few principals, then add those here.
              // .addExceptionPrincipals(
              //     "principalSet://goog/group/project-admins@example.com")

              // Set the permissions to deny.
              // The permission value is of the format: service_fqdn/resource.action
              // For the list of supported permissions, see:
              // https://cloud.google.com/iam/help/deny/supported-permissions
              .addDeniedPermissions("cloudresourcemanager.googleapis.com/projects.delete")

              // Optionally, add the permissions to be exempted from this rule.
              // Meaning, the deny rule will not be applicable to these permissions.
              // .addExceptionPermissions("cloudresourcemanager.googleapis.com/projects.create")

              // Set the condition which will enforce the deny rule. If this condition is true,
              // the deny rule will be applicable. Else, the rule will not be enforced.
              .setDenialCondition(
                  Expr.newBuilder()
                      // The expression uses Common Expression Language syntax (CEL).
                      // Here we block access based on tags.
                      //
                      // A tag is a key-value pair that can be attached to an organization, folder,
                      // or project. You can use deny policies to deny permissions based on tags
                      // without adding an IAM Condition to every role grant.
                      // For example, imagine that you tag all of your projects as dev, test, or
                      // prod. You want only members of project-admins@example.com to be able to
                      // perform operations on projects that are tagged prod.
                      // To solve this problem, you create a deny rule that denies the
                      // cloudresourcemanager.googleapis.com/projects.delete permission to everyone
                      // except project-admins@example.com for resources that are tagged test.
                      .setExpression("!resource.matchTag('12345678/env', 'test')")
                      .setTitle("Only for test projects")
                      .build())
              .build();

      // Add the deny rule and a description for it.
      Policy policy =
          Policy.newBuilder()
              // Set the deny rule.
              .addRules(
                  PolicyRule.newBuilder()
                      // Set a description for the rule.
                      .setDescription(
                          "block all principals from deleting projects, unless the principal"
                              + " is a member of project-admins@example.com and the project"
                              + " being deleted has a tag with the value test")
                      .setDenyRule(denyRule)
                      .build())
              .build();

      // Set the policy resource path, policy rules and a unique ID for the policy.
      CreatePolicyRequest createPolicyRequest =
          CreatePolicyRequest.newBuilder()
              .setParent(policyParent)
              .setPolicy(policy)
              .setPolicyId(policyId)
              .build();

      // Build the create policy request.
      Operation operation =
          policiesClient
              .createPolicyCallable()
              .futureCall(createPolicyRequest)
              .get(3, TimeUnit.MINUTES);

      // Wait for the operation to complete.
      if (operation.hasError()) {
        System.out.println("Error in creating the policy " + operation.getError());
        return;
      }

      // Retrieve the policy name.
      Policy response = policiesClient.getPolicy(String.format("%s/%s", policyParent, policyId));
      String policyName = response.getName();
      System.out.println(
          "Created the deny policy: " + policyName.substring(policyName.lastIndexOf("/") + 1));
    }
  }
}

Node.js

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Node.js API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

const denyRule = {
  // Add one or more principals who should be denied the permissions specified in this rule.
  // For more information on allowed values, see: https://cloud.google.com/iam/help/deny/principal-identifiers
  deniedPrincipals: ['principalSet://goog/public:all'],
  // Optionally, set the principals who should be exempted from the
  // list of denied principals. For example, if you want to deny certain permissions
  // to a group but exempt a few principals, then add those here.
  // exceptionPrincipals: ['principalSet://goog/group/project-admins@example.com'],
  // Set the permissions to deny.
  // The permission value is of the format: service_fqdn/resource.action
  // For the list of supported permissions, see: https://cloud.google.com/iam/help/deny/supported-permissions
  deniedPermissions: ['cloudresourcemanager.googleapis.com/projects.delete'],
  // Optionally, add the permissions to be exempted from this rule.
  // Meaning, the deny rule will not be applicable to these permissions.
  // exceptionPermissions: ['cloudresourcemanager.googleapis.com/projects.create']
  //
  // Set the condition which will enforce the deny rule.
  // If this condition is true, the deny rule will be applicable. Else, the rule will not be enforced.
  // The expression uses Common Expression Language syntax (CEL).
  // Here we block access based on tags.
  //
  // Here, we create a deny rule that denies the cloudresourcemanager.googleapis.com/projects.delete permission to everyone except project-admins@example.com for resources that are tagged test.
  // A tag is a key-value pair that can be attached to an organization, folder, or project.
  // For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
  denialCondition: {
    expression: '!resource.matchTag("12345678/env", "test")',
  },
};

async function createDenyPolicy() {
  const request = {
    parent: `policies/${attachmentPoint}/denypolicies`,
    policy: {
      displayName: 'Restrict project deletion access',
      rules: [
        {
          description:
            'block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value test',
          denyRule,
        },
      ],
    },
    policyId,
  };

  const [operation] = await iamClient.createPolicy(request);
  const [policy] = await operation.promise();

  console.log(`Created the deny policy: ${policy.name}`);
}

createDenyPolicy();

Python

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Python API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

def create_deny_policy(project_id: str, policy_id: str) -> None:
    """Create a deny policy.

    You can add deny policies to organizations, folders, and projects.
    Each of these resources can have up to 5 deny policies.

    Deny policies contain deny rules, which specify the following:
    1. The permissions to deny and/or exempt.
    2. The principals that are denied, or exempted from denial.
    3. An optional condition on when to enforce the deny rules.

    Params:
    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: Specify the ID of the deny policy you want to create.
    """

    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    deny_rule = types.DenyRule()
    # Add one or more principals who should be denied the permissions specified in this rule.
    # For more information on allowed values, see: https://cloud.google.com/iam/help/deny/principal-identifiers
    deny_rule.denied_principals = ["principalSet://goog/public:all"]

    # Optionally, set the principals who should be exempted from the
    # list of denied principals. For example, if you want to deny certain permissions
    # to a group but exempt a few principals, then add those here.
    # deny_rule.exception_principals = ["principalSet://goog/group/project-admins@example.com"]

    # Set the permissions to deny.
    # The permission value is of the format: service_fqdn/resource.action
    # For the list of supported permissions, see: https://cloud.google.com/iam/help/deny/supported-permissions
    deny_rule.denied_permissions = [
        "cloudresourcemanager.googleapis.com/projects.delete"
    ]

    # Optionally, add the permissions to be exempted from this rule.
    # Meaning, the deny rule will not be applicable to these permissions.
    # deny_rule.exception_permissions = ["cloudresourcemanager.googleapis.com/projects.create"]

    # Set the condition which will enforce the deny rule.
    # If this condition is true, the deny rule will be applicable. Else, the rule will not be enforced.
    # The expression uses Common Expression Language syntax (CEL).
    # Here we block access based on tags.
    #
    # Here, we create a deny rule that denies the cloudresourcemanager.googleapis.com/projects.delete permission to everyone except project-admins@example.com for resources that are tagged test.
    # A tag is a key-value pair that can be attached to an organization, folder, or project.
    # For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
    deny_rule.denial_condition = {
        "expression": "!resource.matchTag('12345678/env', 'test')"
    }

    # Add the deny rule and a description for it.
    policy_rule = types.PolicyRule()
    policy_rule.description = "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value test"
    policy_rule.deny_rule = deny_rule

    policy = types.Policy()
    policy.display_name = "Restrict project deletion access"
    policy.rules = [policy_rule]

    # Set the policy resource path, policy rules and a unique ID for the policy.
    request = types.CreatePolicyRequest()
    # Construct the full path of the resource's deny policies.
    # Its format is: "policies/{attachmentPoint}/denypolicies"
    request.parent = f"policies/{attachment_point}/denypolicies"
    request.policy = policy
    request.policy_id = policy_id

    # Build the create policy request and wait for the operation to complete.
    result = policies_client.create_policy(request=request).result()
    print(f"Created the deny policy: {result.name.rsplit('/')[-1]}")


if __name__ == "__main__":
    import uuid

    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    # Test the policy lifecycle.
    create_deny_policy(PROJECT_ID, policy_id)

REST

השיטה policies.createPolicy יוצרת מדיניות דחייה למשאב.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ENCODED_ATTACHMENT_POINT: מזהה בקידוד כתובת URL של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

  • POLICY_ID: מזהה של מדיניות הדחייה.
  • POLICY_NAME: השם המוצג של מדיניות הדחייה.
  • DENY_RULE_1, DENY_RULE_2, ...DENY_RULE_N: כללי הדחייה במדיניות. כל כלל דחייה יכול להכיל את השדות הבאים:

    • deniedPermissions: רשימה של הרשאות שחשבונות המשתמשים שצוינו לא יכולים להשתמש בהן. ההרשאות חייבות להיות בתמיכה של כללי מדיניות הדחייה.

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

    • exceptionPermissions: רשימה של הרשאות שחשבונות המשתמשים שצוינו יכולים להשתמש בהן, גם אם ההרשאות האלה כלולות ב-deniedPermissions. לדוגמה, אפשר להשתמש בשדה הזה כדי להחריג הרשאות ספציפיות בקבוצת הרשאות.
    • deniedPrincipals: רשימה של חשבונות משתמשים שלא יכולים להשתמש בהרשאות שצוינו. מידע על הפורמט של מזהי חשבונות משתמשים מופיע במאמר מזהים של חשבונות משתמשים בכללי מדיניות הדחייה.
    • exceptionPrincipals: אופציונלי. רשימה של חשבונות משתמשים שיכולים להשתמש בהרשאות שצוינו, גם אם החשבונות האלה כלולים ב-deniedPrincipals. לדוגמה, ניתן להשתמש בשדה הזה כדי להחריג משתמשים ספציפיים ששייכים לקבוצה שנדחתה. מידע על הפורמט של מזהי חשבונות משתמשים מופיע במאמר מזהים של חשבונות משתמשים בכללי מדיניות הדחייה.

    • denialCondition: אופציונלי. ביטוי תנאי שמציין את הזמן שבו חשבונות המשתמשים לא יכולים להשתמש בהרשאות. מכיל את השדות הבאים:

    דוגמאות של כללי דחייה מופיעים במאמר תרחישים נפוצים לדוגמה.

שיטת ה-HTTP וכתובת ה-URL:

POST https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies?policyId=POLICY_ID

תוכן בקשת JSON:

{
  "displayName": "POLICY_NAME",
  "rules": [
    {
      "denyRule": DENY_RULE_1
    },
    {
      "denyRule": DENY_RULE_2
    },

    {
      "denyRule": DENY_RULE_N
    }
  ]
}

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אמורה להתקבל תגובת JSON שדומה לזו:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/89cb3e508bf1ff01",
  "metadata": {
    "@type": "type.googleapis.com/google.iam.v2.PolicyOperationMetadata",
    "createTime": "2022-06-28T19:06:12.455151Z"
  },
  "response": {
    "@type": "type.googleapis.com/google.iam.v2.Policy",
    "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
    "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
    "kind": "DenyPolicy",
    "displayName": "My deny policy.",
    "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
    "createTime": "2022-06-28T19:06:12.455151Z",
    "updateTime": "2022-06-28T22:26:21.968687Z"
    "rules": [
      {
        "denyRule": {
          "deniedPrincipals": [
            "principal://goog/subject/lucian@example.com"
          ],
          "deniedPermissions": [
            "iam.googleapis.com/roles.create"
          ]
        }
      }
    ]
  }
}

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

הצגה של רשימת הכללים של מדיניות הדחייה

משאב יכול לכלול כמה כללי מדיניות דחייה. אפשר לכלול ברשימה את כל כללי מדיניות הדחייה שמצורפים למשאב, ואז להציג כל מדיניות בנפרד כדי לראות את כללי הדחייה בכל מדיניות.

המסוף

  1. במסוף Google Cloud , עוברים לכרטיסייה Deny בדף IAM.

    כניסה לדף IAM

  2. בוחרים פרויקט, תיקייה או ארגון.

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

gcloud

כדי לכלול ברשימה את כללי מדיניות הדחייה למשאב, מריצים את הפקודה gcloud iam policies list:

gcloud iam policies list \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --format=json

מציינים את הערך הבא:

  • ATTACHMENT_POINT: מזהה של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

לדוגמה, הפקודה הבאה מציגה ברשימה כללי מדיניות דחייה שמצורפים לארגון שהמזהה המספרי שלו הוא 123456789012:

gcloud iam policies list \
    --attachment-point=cloudresourcemanager.googleapis.com/organizations/123456789012 \
    --kind=denypolicies \
    --format=json

Go

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Go API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	"cloud.google.com/go/iam/apiv2/iampb"
	"google.golang.org/api/iterator"
)

// listDenyPolicies lists all the deny policies that are attached to a resource.
// A resource can have up to 5 deny policies.
func listDenyPolicies(w io.Writer, projectID string) error {
	// projectID := "your_project_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.ListPoliciesRequest{
		// Construct the full path of the resource's deny policies.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies"
		Parent: fmt.Sprintf("policies/%s/denypolicies", attachmentPoint),
	}
	it := policiesClient.ListPolicies(ctx, req)
	fmt.Fprintf(w, "Policies found in project %s:\n", projectID)

	for {
		policy, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "- %s\n", policy.GetName())
	}
	return nil
}

Java

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Java API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.


import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class ListDenyPolicies {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    listDenyPolicies(projectId);
  }

  // List all the deny policies that are attached to a resource.
  // A resource can have up to 5 deny policies.
  public static void listDenyPolicies(String projectId) throws IOException {
    // Initialize the Policies client.
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies"
      String policyParent = String.format("policies/%s/denypolicies", attachmentPoint);

      // Create a list request and iterate over the returned policies.
      for (Policy policy : policiesClient.listPolicies(policyParent).iterateAll()) {
        System.out.println(policy.getName());
      }
      System.out.println("Listed all deny policies");
    }
  }
}

Node.js

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Node.js API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function listDenyPolicies() {
  const request = {
    parent: `policies/${attachmentPoint}/denypolicies`,
  };

  const policies = await iamClient.listPoliciesAsync(request);
  for await (const policy of policies) {
    console.log(`- ${policy.name}`);
  }
}

listDenyPolicies();

Python

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Python API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

def list_deny_policy(project_id: str) -> None:
    """List all the deny policies that are attached to a resource.

    A resource can have up to 5 deny policies.

    project_id: ID or number of the Google Cloud project you want to use.
    """

    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.ListPoliciesRequest()
    # Construct the full path of the resource's deny policies.
    # Its format is: "policies/{attachmentPoint}/denypolicies"
    request.parent = f"policies/{attachment_point}/denypolicies"

    # Create a list request and iterate over the returned policies.
    policies = policies_client.list_policies(request=request)

    for policy in policies:
        print(policy.name)
    print("Listed all deny policies")


if __name__ == "__main__":
    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    list_deny_policy(PROJECT_ID)

REST

השיטה policies.listPolicies מציגה ברשימה את כללי מדיניות הדחייה של משאב.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ENCODED_ATTACHMENT_POINT: מזהה בקידוד כתובת URL של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

ה-method של ה-HTTP וכתובת ה-URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "policies": [
    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1067607927478/denypolicies/test-policy",
      "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
      "kind": "DenyPolicy",
      "displayName": "My deny policy.",
      "createTime": "2022-06-28T19:06:12.455151Z",
      "updateTime": "2022-06-28T22:26:21.968687Z"
    },
    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1067607927478/denypolicies/test-policy-2",
      "uid": "8465d710-ea20-0a08-d92c-b2a3ebf766ab",
      "kind": "DenyPolicy",
      "displayName": "My second deny policy.",
      "createTime": "2022-06-05T19:21:53.595455Z",
      "updateTime": "2022-06-05T19:21:53.595455Z"
    },
    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1067607927478/denypolicies/test-policy-3",
      "uid": "ee9f7c2f-7e8c-b05c-d4e5-e03bfb2954e0",
      "kind": "DenyPolicy",
      "displayName": "My third deny policy.",
      "createTime": "2022-06-05T19:22:26.770543Z",
      "updateTime": "2022-06-05T19:22:26.770543Z"
    }
  ]
}

הצגת מדיניות הדחייה

אפשר להציג את מדיניות הדחייה כדי לראות את כללי הדחייה שלה. הם כוללים את ההרשאות שנדחו ואת חשבונות המשתמשים שלא יכולים להשתמש בהרשאות האלה.

המסוף

  1. במסוף Google Cloud , עוברים לכרטיסייה Deny בדף IAM.

    כניסה לדף IAM

  2. בוחרים פרויקט, תיקייה או ארגון.

  3. בעמודה מזהה המדיניות, לוחצים על המזהה של המדיניות שרוצים לראות.

    במסוף Google Cloud מוצגים הפרטים של מדיניות הדחייה, כולל מזהה המדיניות, המועד שבו נוצרה המדיניות וכללי הדחייה במדיניות הדחייה.

gcloud

כדי לקבל את מדיניות הדחייה של משאב, מריצים את הפקודה gcloud iam policies get:

gcloud iam policies get POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --format=json

מציינים את הערכים הבאים:

  • POLICY_ID: המזהה של מדיניות הדחייה.

  • ATTACHMENT_POINT: מזהה של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

לדוגמה, הפקודה הבאה מקבלת את מדיניות הדחייה my-deny-policy של הפרויקט my-project ושומרת אותה בקובץ policy.json.

gcloud iam policies get my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --format=json \
    > ./policy.json

Go

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Go API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	"cloud.google.com/go/iam/apiv2/iampb"
)

// getDenyPolicy retrieves the deny policy given the project ID and policy ID.
func getDenyPolicy(w io.Writer, projectID, policyID string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.GetPolicyRequest{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name: fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
	}
	policy, err := policiesClient.GetPolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to get policy: %w", err)
	}

	fmt.Fprintf(w, "Policy %s retrieved\n", policy.GetName())

	return nil
}

Java

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Java API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.


import com.google.iam.v2.GetPolicyRequest;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class GetDenyPolicy {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    getDenyPolicy(projectId, policyId);
  }

  // Retrieve the deny policy given the project ID and policy ID.
  public static void getDenyPolicy(String projectId, String policyId) throws IOException {
    // Create the IAM Policies client.
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      // Specify the policyParent and execute the GetPolicy request.
      GetPolicyRequest getPolicyRequest =
          GetPolicyRequest.newBuilder().setName(policyParent).build();

      Policy policy = policiesClient.getPolicy(getPolicyRequest);
      System.out.printf("Retrieved the deny policy: %s : %s%n", policyId, policy);
    }
  }
}

Node.js

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Node.js API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function getDenyPolicy() {
  const request = {
    name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
  };

  const [policy] = await iamClient.getPolicy(request);

  console.log(`Retrieved the deny policy: ${policy.name}`);
}

getDenyPolicy();

Python

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Python API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

from google.cloud import iam_v2
from google.cloud.iam_v2 import Policy, types


def get_deny_policy(project_id: str, policy_id: str) -> Policy:
    """Retrieve the deny policy given the project ID and policy ID.

    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: The ID of the deny policy you want to retrieve.
    """
    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.GetPolicyRequest()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    request.name = f"policies/{attachment_point}/denypolicies/{policy_id}"

    # Execute the GetPolicy request.
    policy = policies_client.get_policy(request=request)
    print(f"Retrieved the deny policy: {policy_id} : {policy}")
    return policy


if __name__ == "__main__":
    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    policy = get_deny_policy(PROJECT_ID, policy_id)

REST

השיטה policies.get מקבלת מדיניות דחייה למשאב.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ENCODED_ATTACHMENT_POINT: מזהה בקידוד כתובת URL של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

  • POLICY_ID: מזהה של מדיניות הדחייה.

שיטת ה-HTTP וכתובת ה-URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
  "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
  "kind": "DenyPolicy",
  "displayName": "My deny policy.",
  "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
  "createTime": "2022-06-05T19:22:26.770543Z",
  "updateTime": "2022-06-05T19:22:26.770543Z",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create"
        ]
      }
    }
  ]
}

עדכון של מדיניות הדחייה

אחרי יצירת מדיניות דחייה, אפשר לעדכן את כללי הדחייה שהיא כוללת ואת השם המוצג שלה.

אפשר לעדכן מדיניות דחייה באמצעות מסוף Google Cloud או באמצעות אחת מהשיטות הבאות:

  • ה-CLI של gcloud
  • API בארכיטקטורת REST
  • ספריות הלקוח של IAM

עדכון של מדיניות הדחייה באמצעות Google Cloud המסוף

  1. במסוף Google Cloud , עוברים לכרטיסייה Deny בדף IAM.

    כניסה לדף IAM

  2. בוחרים פרויקט, תיקייה או ארגון.

  3. בעמודה מזהה המדיניות, לוחצים על המזהה של המדיניות שרוצים לערוך.

  4. לוחצים על עריכה.

  5. מעדכנים את מדיניות הדחייה:

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

עדכון של מדיניות הדחייה באופן פרוגרמטי

כדי לעדכן מדיניות דחייה באמצעות ה-CLI של gcloud, ה-API בארכיטקטורת REST או ספריות הלקוח של IAM, צריך להשתמש בתבנית קריאה-תיקון-כתיבה:

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

קריאת מדיניות הדחייה

gcloud

כדי לקבל את מדיניות הדחייה של משאב, מריצים את הפקודה gcloud iam policies get:

gcloud iam policies get POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --format=json

מציינים את הערכים הבאים:

  • POLICY_ID: המזהה של מדיניות הדחייה.

  • ATTACHMENT_POINT: מזהה של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

לדוגמה, הפקודה הבאה מקבלת את מדיניות הדחייה my-deny-policy של הפרויקט my-project ושומרת אותה בקובץ policy.json.

gcloud iam policies get my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --format=json \
    > ./policy.json

Go

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Go API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	"cloud.google.com/go/iam/apiv2/iampb"
)

// getDenyPolicy retrieves the deny policy given the project ID and policy ID.
func getDenyPolicy(w io.Writer, projectID, policyID string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.GetPolicyRequest{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name: fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
	}
	policy, err := policiesClient.GetPolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to get policy: %w", err)
	}

	fmt.Fprintf(w, "Policy %s retrieved\n", policy.GetName())

	return nil
}

Java

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Java API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.


import com.google.iam.v2.GetPolicyRequest;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class GetDenyPolicy {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    getDenyPolicy(projectId, policyId);
  }

  // Retrieve the deny policy given the project ID and policy ID.
  public static void getDenyPolicy(String projectId, String policyId) throws IOException {
    // Create the IAM Policies client.
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      // Specify the policyParent and execute the GetPolicy request.
      GetPolicyRequest getPolicyRequest =
          GetPolicyRequest.newBuilder().setName(policyParent).build();

      Policy policy = policiesClient.getPolicy(getPolicyRequest);
      System.out.printf("Retrieved the deny policy: %s : %s%n", policyId, policy);
    }
  }
}

Node.js

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Node.js API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function getDenyPolicy() {
  const request = {
    name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
  };

  const [policy] = await iamClient.getPolicy(request);

  console.log(`Retrieved the deny policy: ${policy.name}`);
}

getDenyPolicy();

Python

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Python API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

from google.cloud import iam_v2
from google.cloud.iam_v2 import Policy, types


def get_deny_policy(project_id: str, policy_id: str) -> Policy:
    """Retrieve the deny policy given the project ID and policy ID.

    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: The ID of the deny policy you want to retrieve.
    """
    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.GetPolicyRequest()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    request.name = f"policies/{attachment_point}/denypolicies/{policy_id}"

    # Execute the GetPolicy request.
    policy = policies_client.get_policy(request=request)
    print(f"Retrieved the deny policy: {policy_id} : {policy}")
    return policy


if __name__ == "__main__":
    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    policy = get_deny_policy(PROJECT_ID, policy_id)

REST

השיטה policies.get מקבלת מדיניות דחייה למשאב.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ENCODED_ATTACHMENT_POINT: מזהה בקידוד כתובת URL של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

  • POLICY_ID: מזהה של מדיניות הדחייה.

שיטת ה-HTTP וכתובת ה-URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
  "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
  "kind": "DenyPolicy",
  "displayName": "My deny policy.",
  "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
  "createTime": "2022-06-05T19:22:26.770543Z",
  "updateTime": "2022-06-05T19:22:26.770543Z",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create"
        ]
      }
    }
  ]
}

תיקון מדיניות הדחייה

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

לדוגמה, אפשר להוסיף הרשאה לכלל דחייה שכבר קיים:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
  "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
  "kind": "DenyPolicy",
  "displayName": "My deny policy.",
  "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
  "createTime": "2021-10-05T19:22:26.770543Z",
  "updateTime": "2021-10-05T19:22:26.770543Z",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create",
          "iam.googleapis.com/roles.delete"
        ]
      }
    }
  ]
}

כתיבה של מדיניות הדחייה העדכנית

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

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

gcloud

כדי לעדכן את מדיניות הדחייה של משאב, מריצים את הפקודה gcloud iam policies update:

gcloud iam policies update POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --policy-file=POLICY_FILE

מציינים את הערכים הבאים:

  • POLICY_ID: המזהה של מדיניות הדחייה.

  • ATTACHMENT_POINT: מזהה של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

  • POLICY_FILE: הנתיב של קובץ ה-JSON שמכיל את מדיניות הדחייה.

כברירת מחדל, אם הפקודה הזו מצליחה, היא לא מדפיסה פלט. כדי להדפיס תגובה מפורטת, מוסיפים את הדגל --format=json לפקודה.

לדוגמה, אפשר להשתמש בפקודה הבאה כדי לעדכן מדיניות דחייה בשם my-deny-policy של הפרויקט my-project, באמצעות הקובץ policy.json:

gcloud iam policies update my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --policy-file=policy.json

Go

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Go API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"

	"cloud.google.com/go/iam/apiv2/iampb"
	"google.golang.org/genproto/googleapis/type/expr"
)

// updateDenyPolicy updates the deny rules and/ or its display name after policy creation.
func updateDenyPolicy(w io.Writer, projectID, policyID, etag string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"
	// etag := "your_etag"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	denyRule := &iampb.DenyRule{
		// Add one or more principals who should be denied the permissions specified in this rule.
		// For more information on allowed values,
		// see: https://cloud.google.com/iam/help/deny/principal-identifiers
		DeniedPrincipals: []string{"principalSet://goog/public:all"},
		// Optionally, set the principals who should be exempted from the
		// list of denied principals. For example, if you want to deny certain permissions
		// to a group but exempt a few principals, then add those here.
		// ExceptionPrincipals: []string{"principalSet://goog/group/project-admins@example.com"},
		//
		// Set the permissions to deny.
		// The permission value is of the format: service_fqdn/resource.action
		// For the list of supported permissions,
		// see: https://cloud.google.com/iam/help/deny/supported-permissions
		DeniedPermissions: []string{"cloudresourcemanager.googleapis.com/projects.delete"},
		// Optionally, add the permissions to be exempted from this rule.
		// Meaning, the deny rule will not be applicable to these permissions.
		// ExceptionPermissions: []string{"cloudresourcemanager.googleapis.com/projects.create"},
		//
		// Set the condition which will enforce the deny rule.
		// If this condition is true, the deny rule will be applicable.
		// Else, the rule will not be enforced.
		// The expression uses Common Expression Language syntax (CEL).
		// Here we block access based on tags.
		//
		// Here, we create a deny rule that denies the
		// cloudresourcemanager.googleapis.com/projects.delete permission
		// to everyone except project-admins@example.com for resources that are tagged prod.
		// A tag is a key-value pair that can be attached to an organization, folder, or project.
		// For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
		DenialCondition: &expr.Expr{
			Expression: "!resource.matchTag('12345678/env', 'prod')",
		},
	}

	// Set the rule description and deny rule to update.
	policyRule := &iampb.PolicyRule{
		Description: "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value prod",
		Kind: &iampb.PolicyRule_DenyRule{
			DenyRule: denyRule,
		},
	}

	// Set the policy resource path, version (etag) and the updated deny rules.
	policy := &iampb.Policy{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name:  fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
		Etag:  etag,
		Rules: [](*iampb.PolicyRule){policyRule},
	}

	// Create the update policy request.
	req := &iampb.UpdatePolicyRequest{
		Policy: policy,
	}
	op, err := policiesClient.UpdatePolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to update policy: %w", err)
	}

	policy, err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Policy %s updated\n", policy.GetName())

	return nil
}

Java

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Java API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.


import com.google.iam.v2.DenyRule;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import com.google.iam.v2.PolicyRule;
import com.google.iam.v2.UpdatePolicyRequest;
import com.google.longrunning.Operation;
import com.google.type.Expr;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateDenyPolicy {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the Deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    // Etag field that identifies the policy version. The etag changes each time
    // you update the policy. Get the etag of an existing policy by performing a GetPolicy request.
    String etag = "policy_etag";

    updateDenyPolicy(projectId, policyId, etag);
  }

  // Update the deny rules and/ or its display name after policy creation.
  public static void updateDenyPolicy(String projectId, String policyId, String etag)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached to.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      DenyRule denyRule =
          DenyRule.newBuilder()
              // Add one or more principals who should be denied the permissions specified in this
              // rule.
              // For more information on allowed values, see:
              // https://cloud.google.com/iam/docs/principal-identifiers
              .addDeniedPrincipals("principalSet://goog/public:all")

              // Optionally, set the principals who should be exempted from the list of principals
              // added in "DeniedPrincipals".
              // Example, if you want to deny certain permissions to a group but exempt a few
              // principals, then add those here.
              // .addExceptionPrincipals(
              //     "principalSet://goog/group/project-admins@example.com")

              // Set the permissions to deny.
              // The permission value is of the format: service_fqdn/resource.action
              // For the list of supported permissions, see:
              // https://cloud.google.com/iam/help/deny/supported-permissions
              .addDeniedPermissions("cloudresourcemanager.googleapis.com/projects.delete")

              // Add the permissions to be exempted from this rule.
              // Meaning, the deny rule will not be applicable to these permissions.
              // .addExceptionPermissions("cloudresourcemanager.googleapis.com/projects.get")

              // Set the condition which will enforce the deny rule.
              // If this condition is true, the deny rule will be applicable. Else, the rule will
              // not be enforced.
              .setDenialCondition(
                  Expr.newBuilder()
                      // The expression uses Common Expression Language syntax (CEL). Here we block
                      // access based on tags.
                      //
                      // A tag is a key-value pair that can be attached to an organization, folder,
                      // or project. You can use deny policies to deny permissions based on tags
                      // without adding an IAM Condition to every role grant.
                      // For example, imagine that you tag all of your projects as dev, test, or
                      // prod. You want only members of project-admins@example.com to be able to
                      // perform operations on projects that are tagged prod.
                      // To solve this problem, you create a deny rule that denies the
                      // cloudresourcemanager.googleapis.com/projects.delete permission to everyone
                      // except project-admins@example.com for resources that are tagged prod.
                      .setExpression("!resource.matchTag('12345678/env', 'prod')")
                      .setTitle("Only for prod projects")
                      .build())
              .build();

      // Set the policy resource path, version (etag) and the updated deny rules.
      Policy policy =
          Policy.newBuilder()
              .setName(policyParent)
              .setEtag(etag)
              .addRules(
                  PolicyRule.newBuilder()
                      // Set the rule description to update.
                      .setDescription(
                          "Block all principals from deleting projects, unless the principal"
                              + " is a member of project-admins@example.com and the project"
                              + "being deleted has a tag with the value prod")
                      // Set the deny rule to update.
                      .setDenyRule(denyRule)
                      .build())
              .build();

      // Create the update policy request.
      UpdatePolicyRequest updatePolicyRequest =
          UpdatePolicyRequest.newBuilder().setPolicy(policy).build();

      // Wait for the operation to complete.
      Operation operation =
          policiesClient
              .updatePolicyCallable()
              .futureCall(updatePolicyRequest)
              .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Error in updating the policy " + operation.getError());
        return;
      }

      System.out.println("Updated the deny policy: " + policyId);
    }
  }
}

Node.js

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Node.js API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';
// const etag = 'YOUR_ETAG';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

const denyRule = {
  // Add one or more principals who should be denied the permissions specified in this rule.
  // For more information on allowed values, see: https://cloud.google.com/iam/help/deny/principal-identifiers
  deniedPrincipals: ['principalSet://goog/public:all'],
  // Optionally, set the principals who should be exempted from the
  // list of denied principals. For example, if you want to deny certain permissions
  // to a group but exempt a few principals, then add those here.
  // exceptionPrincipals: ['principalSet://goog/group/project-admins@example.com'],
  // Set the permissions to deny.
  // The permission value is of the format: service_fqdn/resource.action
  // For the list of supported permissions, see: https://cloud.google.com/iam/help/deny/supported-permissions
  deniedPermissions: ['cloudresourcemanager.googleapis.com/projects.delete'],
  // Optionally, add the permissions to be exempted from this rule.
  // Meaning, the deny rule will not be applicable to these permissions.
  // exceptionPermissions: ['cloudresourcemanager.googleapis.com/projects.create']
  //
  // Set the condition which will enforce the deny rule.
  // If this condition is true, the deny rule will be applicable. Else, the rule will not be enforced.
  // The expression uses Common Expression Language syntax (CEL).
  // Here we block access based on tags.
  //
  // Here, we create a deny rule that denies the cloudresourcemanager.googleapis.com/projects.delete permission to everyone except project-admins@example.com for resources that are tagged test.
  // A tag is a key-value pair that can be attached to an organization, folder, or project.
  // For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
  denialCondition: {
    expression: '!resource.matchTag("12345678/env", "prod")',
  },
};

async function updateDenyPolicy() {
  const request = {
    policy: {
      name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
      etag,
      rules: [
        {
          description:
            'block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value prod',
          denyRule,
        },
      ],
    },
    policyId,
  };

  const [operation] = await iamClient.updatePolicy(request);
  const [policy] = await operation.promise();

  console.log(`Updated the deny policy: ${policy.name}`);
}

updateDenyPolicy();

Python

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Python API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

def update_deny_policy(project_id: str, policy_id: str, etag: str) -> None:
    """Update the deny rules and/ or its display name after policy creation.

    project_id: ID or number of the Google Cloud project you want to use.

    policy_id: The ID of the deny policy you want to retrieve.

    etag: Etag field that identifies the policy version. The etag changes each time
    you update the policy. Get the etag of an existing policy by performing a GetPolicy request.
    """

    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name.
    # Hence, replace the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    deny_rule = types.DenyRule()

    # Add one or more principals who should be denied the permissions
    # specified in this rule.
    # For more information on allowed values, see:
    # https://cloud.google.com/iam/help/deny/principal-identifiers
    deny_rule.denied_principals = ["principalSet://goog/public:all"]

    # Optionally, set the principals who should be exempted
    # from the list of principals added in "DeniedPrincipals".
    # Example, if you want to deny certain permissions to a group
    # but exempt a few principals, then add those here.
    # deny_rule.exception_principals = ["principalSet://goog/group/project-admins@example.com"]

    # Set the permissions to deny.
    # The permission value is of the format: service_fqdn/resource.action
    # For the list of supported permissions, see:
    # https://cloud.google.com/iam/help/deny/supported-permissions
    deny_rule.denied_permissions = [
        "cloudresourcemanager.googleapis.com/projects.delete"
    ]

    # Add the permissions to be exempted from this rule.
    # Meaning, the deny rule will not be applicable to these permissions.
    # deny_rule.exception_permissions = ["cloudresourcemanager.googleapis.com/projects.get"]

    # Set the condition which will enforce the deny rule.
    # If this condition is true, the deny rule will be applicable.
    # Else, the rule will not be enforced.
    #
    # The expression uses Common Expression Language syntax (CEL).
    # Here we block access based on tags.
    #
    # Here, we create a deny rule that denies the
    # cloudresourcemanager.googleapis.com/projects.delete permission to everyone
    # except project-admins@example.com for resources that are tagged prod.
    # A tag is a key-value pair that can be attached
    # to an organization, folder, or project.
    # For more info, see:
    # https://cloud.google.com/iam/docs/deny-access#create-deny-policy
    deny_rule.denial_condition = {
        "expression": "!resource.matchTag('12345678/env', 'prod')"
    }

    # Set the rule description and deny rule to update.
    policy_rule = types.PolicyRule()
    policy_rule.description = "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value prod"
    policy_rule.deny_rule = deny_rule

    # Set the policy resource path, version (etag) and the updated deny rules.
    policy = types.Policy()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    policy.name = f"policies/{attachment_point}/denypolicies/{policy_id}"
    policy.etag = etag
    policy.rules = [policy_rule]

    # Create the update policy request.
    request = types.UpdatePolicyRequest()
    request.policy = policy

    result = policies_client.update_policy(request=request).result()
    print(f"Updated the deny policy: {result.name.rsplit('/')[-1]}")


if __name__ == "__main__":
    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"
    # Get the etag by performing a Get policy request.
    etag = "etag"

    update_deny_policy(PROJECT_ID, policy_id, etag)

REST

השיטה policies.update מעדכנת מדיניות דחייה.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ENCODED_ATTACHMENT_POINT: מזהה בקידוד כתובת URL של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

  • POLICY_ID: מזהה של מדיניות הדחייה.
  • POLICY: מדיניות הדחייה העדכנית.

    לדוגמה, כדי להוסיף הרשאה למדיניות שצוינה בשלב הקודם, מחליפים את POLICY בערך הבא:

    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
      "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
      "kind": "DenyPolicy",
      "displayName": "My deny policy.",
      "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
      "createTime": "2022-06-05T19:22:26.770543Z",
      "updateTime": "2022-06-05T19:22:26.770543Z",
      "rules": [
        {
          "denyRule": {
            "deniedPrincipals": [
              "principal://goog/subject/lucian@example.com"
            ],
            "deniedPermissions": [
              "iam.googleapis.com/roles.create",
              "iam.googleapis.com/roles.delete"
            ]
          }
        }
      ]
    }

שיטת ה-HTTP וכתובת ה-URL:

PUT https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID

תוכן בקשת JSON:

POLICY

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אמורה להתקבל תגובת JSON שדומה לזו:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/8b2d0ab2daf1ff01",
  "metadata": {
    "@type": "type.googleapis.com/google.iam.v2.PolicyOperationMetadata",
    "createTime": "2021-10-05T22:26:21.968687Z"
  },
  "response": {
    "@type": "type.googleapis.com/google.iam.v2.Policy",
    "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
    "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
    "kind": "DenyPolicy",
    "displayName": "My deny policy.",
    "etag": "MTgxNTIxNDE3NTYxNjQxODYxMTI=",
    "createTime": "2022-06-05T19:22:26.770543Z",
    "updateTime": "2022-06-05T22:26:21.968687Z",
    "rules": [
      {
        "denyRule": {
          "deniedPrincipals": [
            "principal://goog/subject/lucian@example.com"
          ],
          "deniedPermissions": [
            "iam.googleapis.com/roles.create",
            "iam.googleapis.com/roles.delete"
          ]
        }
      }
    ]
  }
}

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

מחיקת מדיניות דחייה

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

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

אם משמיטים את השדה etag מהבקשה, תתבצע מחיקה מוחלטת של המדיניות מ-IAM.

המסוף

  1. במסוף Google Cloud , עוברים לכרטיסייה Deny בדף IAM.

    כניסה לדף IAM

  2. בוחרים פרויקט, תיקייה או ארגון.

  3. בעמודה מזהה המדיניות, לוחצים על המזהה של המדיניות שרוצים למחוק.

  4. לוחצים על מחיקה. בתיבת הדו-שיח לאישור, לוחצים על אישור.

gcloud

כדי למחוק מדיניות דחייה ממשאב, מריצים את הפקודה gcloud iam policies delete:

gcloud iam policies delete POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies

מציינים את הערכים הבאים:

  • POLICY_ID: המזהה של מדיניות הדחייה.

  • ATTACHMENT_POINT: מזהה של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

אפשר גם להוסיף את הדגל --etag=ETAG. מחליפים את הערך בשדה ETAG בערך שבשדה etag הנוכחי של מדיניות הדחייה.

כברירת מחדל, אם הפקודה הזו מצליחה, היא לא מדפיסה פלט. כדי להדפיס תגובה מפורטת, מוסיפים את הדגל --format=json לפקודה.

לדוגמה, באמצעות הפקודה הבאה אפשר למחוק מדיניות דחייה בשם my-deny-policy מהפרויקט my-project:

gcloud iam policies delete my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies

Go

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Go API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"

	"cloud.google.com/go/iam/apiv2/iampb"
)

// deleteDenyPolicy deletes the policy if you no longer want to enforce the rules in a deny policy.
func deleteDenyPolicy(w io.Writer, projectID, policyID string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.DeletePolicyRequest{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name: fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
	}
	op, err := policiesClient.DeletePolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to delete policy: %w", err)
	}

	policy, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Policy %s deleted\n", policy.GetName())

	return nil
}

Java

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Java API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.


import com.google.iam.v2.DeletePolicyRequest;
import com.google.iam.v2.PoliciesClient;
import com.google.longrunning.Operation;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteDenyPolicy {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    deleteDenyPolicy(projectId, policyId);
  }

  // Delete the policy if you no longer want to enforce the rules in a deny policy.
  public static void deleteDenyPolicy(String projectId, String policyId)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      // Create the DeletePolicy request.
      DeletePolicyRequest deletePolicyRequest =
          DeletePolicyRequest.newBuilder().setName(policyParent).build();

      // Delete the policy and wait for the operation to complete.
      Operation operation =
          policiesClient
              .deletePolicyCallable()
              .futureCall(deletePolicyRequest)
              .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Error in deleting the policy " + operation.getError());
        return;
      }

      System.out.println("Deleted the deny policy: " + policyId);
    }
  }
}

Node.js

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Node.js API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function deleteDenyPolicy() {
  const request = {
    name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
  };

  const [operation] = await iamClient.deletePolicy(request);
  const [policy] = await operation.promise();

  console.log(`Deleted the deny policy: ${policy.name}`);
}

deleteDenyPolicy();

Python

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Python API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף מופיע במאמר לפני שמתחילים.

def delete_deny_policy(project_id: str, policy_id: str) -> None:
    """Delete the policy if you no longer want to enforce the rules in a deny policy.

    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: The ID of the deny policy you want to retrieve.
    """

    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.DeletePolicyRequest()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    request.name = f"policies/{attachment_point}/denypolicies/{policy_id}"

    # Create the DeletePolicy request.
    result = policies_client.delete_policy(request=request).result()
    print(f"Deleted the deny policy: {result.name.rsplit('/')[-1]}")


if __name__ == "__main__":
    import uuid

    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    delete_deny_policy(PROJECT_ID, policy_id)

REST

השיטה policies.delete מוחקת מדיניות דחייה ממשאב.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ENCODED_ATTACHMENT_POINT: מזהה בקידוד כתובת URL של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

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

שיטת ה-HTTP וכתובת ה-URL:

DELETE https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID?etag=ETAG

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אמורה להתקבל תגובת JSON שדומה לזו:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/8223fe308bf1ff01",
  "metadata": {
    "@type": "type.googleapis.com/google.iam.v2.PolicyOperationMetadata",
    "createTime": "2021-10-05T19:45:00.133311Z"
  },
  "response": {
    "@type": "type.googleapis.com/google.iam.v2.Policy",
    "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
    "kind": "DenyPolicy",
    "displayName": "My deny policy.",
    "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
    "createTime": "2022-06-28T19:06:12.455151Z",
    "updateTime": "2022-07-05T19:45:00.133311Z",
    "deleteTime": "2022-07-05T19:45:00.133311Z",
    "rules": [
      {
        "denyRule": {
          "deniedPrincipals": [
            "principal://goog/subject/lucian@example.com"
          ],
          "deniedPermissions": [
            "iam.googleapis.com/roles.create"
          ]
        }
      }
    ]
  }
}

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

בדיקת הסטטוס של פעולה ממושכת

כשמשתמשים ב-API ל-REST או בספריות הלקוח, כל שיטה שמשנה מדיניות דחייה מחזירה פעולה ממושכת או LRO. הפעולה הממושכת עוקבת אחרי הסטטוס של הבקשה ומציינת אם השינוי במדיניות מושלם.

Go

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

Java

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

Node.js

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

Python

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

REST

השיטה policies.operations.get מחזירה את הסטטוס של פעולה ממושכת.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ENCODED_ATTACHMENT_POINT: מזהה בקידוד כתובת URL של המשאב שאליו מצורפת מדיניות הדחייה. אפשר לקרוא מידע על הפורמט של הערך הזה בקטע נקודת הצירוף.

  • OPERATION_ID: המזהה של הפעולה. המזהה הזה מופיע בתגובה לבקשה המקורית, כחלק משם הפעולה. צריך להשתמש בערך ההקסדצימלי בסוף שם הפעולה. לדוגמה: 89cb3e508bf1ff01.

שיטת ה-HTTP וכתובת ה-URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/operations/OPERATION_ID

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אמורה להתקבל תגובת JSON שדומה לזו:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/89cb3e508bf1ff01",
  "done": true
}

אם השדה done של הפעולה לא מופיע, אפשר לבצע את הפעולה שוב ושוב כדי להמשיך לעקוב אחר הסטטוס שלה. צריך להשתמש בהשהיה מעריכית (exponential backoff) קטועה לפני ניסיון חוזר כדי ליצור עיכוב בין כל בקשה. כשהערך של השדה done מוגדר בתור true, הפעולה הושלמה ואפשר להפסיק לבצע אותה.

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