ポリシーの作成後に拒否ルールまたはその表示名、あるいはその両方を更新します。
もっと見る
このコードサンプルを含む詳細なドキュメントについては、以下をご覧ください。
コードサンプル
Go
IAM のクライアント ライブラリをインストールして使用する方法については、IAM クライアント ライブラリをご覧ください。詳細については、IAM Go API のリファレンス ドキュメントをご覧ください。
IAM で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。
import (
"context"
"fmt"
"io"
iam "cloud.google.com/go/iam/apiv2"
iampb "google.golang.org/genproto/googleapis/iam/v2"
"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 で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。
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 で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。
/**
* 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 で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。
def update_deny_policy(project_id: str, policy_id: str, etag: str) -> None:
from google.cloud import iam_v2
from google.cloud.iam_v2 import types
"""
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.
"""
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__":
import uuid
# Your Google Cloud project ID.
project_id = "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)
次のステップ
他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。