更新政策

演示如何更新政策。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM C++ API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response =
      client.SetIamPolicy(name, [](google::iam::v1::Policy policy) {
        // change the policy, e.g., add/remove/edit a binding
        return policy;
      });
  if (!response) throw std::move(response).status();
  std::cout << "Policy successfully set: " << response->DebugString() << "\n";
}

C#

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM C# API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy SetPolicy(string projectId, Policy policy)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);
        var service = new CloudResourceManagerService(
            new CloudResourceManagerService.Initializer
            {
                HttpClientInitializer = credential
            });

        return service.Projects.SetIamPolicy(new SetIamPolicyRequest
        {
            Policy = policy
        }, projectId).Execute();
    }
}

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM Java API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.resourcemanager.v3.ProjectsClient;
import com.google.iam.admin.v1.ProjectName;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class SetProjectPolicy {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    // TODO: Replace with your project ID.
    String projectId = "your-project-id";
    // TODO: Replace with your policy, GetPolicy.getPolicy(projectId, serviceAccount).
    Policy policy = Policy.newBuilder().build();

    setProjectPolicy(policy, projectId);
  }

  // Sets a project's policy.
  public static Policy setProjectPolicy(Policy policy, String projectId)
          throws IOException {

    // Initialize client that will be used to send requests.
    // This client only needs to be created once, and can be reused for multiple requests.
    try (ProjectsClient projectsClient = ProjectsClient.create()) {
      List<String> paths = Arrays.asList("bindings", "etag");
      SetIamPolicyRequest request = SetIamPolicyRequest.newBuilder()
              .setResource(ProjectName.of(projectId).toString())
              .setPolicy(policy)
              // A FieldMask specifying which fields of the policy to modify. Only
              // the fields in the mask will be modified. If no mask is provided, the
              // following default mask is used:
              // `paths: "bindings, etag"`
              .setUpdateMask(FieldMask.newBuilder().addAllPaths(paths).build())
              .build();

      return projectsClient.setIamPolicy(request);
    }
  }
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM Python API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import resourcemanager_v3
from google.iam.v1 import iam_policy_pb2, policy_pb2


def set_project_policy(
    project_id: str, policy: policy_pb2.Policy, merge: bool = True
) -> policy_pb2.Policy:
    """
    Set policy for project. Pay attention that previous state will be completely rewritten.
    If you want to update only part of the policy follow the approach read->modify->write.
    For more details about policies check out https://cloud.google.com/iam/docs/policies

    project_id: ID or number of the Google Cloud project you want to use.
    policy: Policy which has to be set.
    merge: The strategy to be used forming the request. CopyFrom is clearing both mutable and immutable fields,
    when MergeFrom is replacing only immutable fields and extending mutable.
    https://googleapis.dev/python/protobuf/latest/google/protobuf/message.html#google.protobuf.message.Message.CopyFrom
    """
    client = resourcemanager_v3.ProjectsClient()

    request = iam_policy_pb2.GetIamPolicyRequest()
    request.resource = f"projects/{project_id}"
    current_policy = client.get_iam_policy(request)

    # Etag should as fresh as possible to lower chance of collisions
    policy.ClearField("etag")
    if merge:
        current_policy.MergeFrom(policy)
    else:
        current_policy.CopyFrom(policy)

    request = iam_policy_pb2.SetIamPolicyRequest()
    request.resource = f"projects/{project_id}"

    # request.etag field also will be merged which means you are secured from collision,
    # but it means that request may fail and you need to leverage exponential retries approach
    # to be sure policy has been updated.
    request.policy.CopyFrom(current_policy)

    policy = client.set_iam_policy(request)
    return policy

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器