从角色绑定中移除成员

演示如何从 IAM 政策的角色绑定中移除成员。

包含此代码示例的文档页面

如需在实际用例中查看代码示例,请参阅以下文档:

代码示例

C#

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


using System.Linq;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy RemoveMember(Policy policy, string role, string member)
    {
        try
        {
            var binding = policy.Bindings.First(x => x.Role == role);
            if (binding.Members.Count != 0 && binding.Members.Contains(member))
            {
                binding.Members.Remove(member);
            }
            if (binding.Members.Count == 0)
            {
                policy.Bindings.Remove(binding);
            }
            return policy;
        }
        catch (System.InvalidOperationException e)
        {
            System.Diagnostics.Debug.WriteLine("Role does not exist in policy: \n" + e.ToString());
            return policy;
        }
    }
}

Java

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

import com.google.api.services.cloudresourcemanager.v3.model.Binding;
import com.google.api.services.cloudresourcemanager.v3.model.Policy;
import java.util.List;

public class RemoveMember {

  // Removes member from a role; removes binding if binding contains 0 members.
  public static void removeMember(Policy policy) {
    // policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();

    String role = "roles/existing-role";
    String member = "user:member-to-remove@example.com";

    List<Binding> bindings = policy.getBindings();
    Binding binding = null;
    for (Binding b : bindings) {
      if (b.getRole().equals(role)) {
        binding = b;
      }
    }
    if (binding.getMembers().contains(member)) {
      binding.getMembers().remove(member);
      System.out.println("Member " + member + " removed from " + role);
      if (binding.getMembers().isEmpty()) {
        policy.getBindings().remove(binding);
      }
      return;
    }

    System.out.println("Role not found in policy; member not removed");
    return;
  }
}

Python

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

def modify_policy_remove_member(policy, role, member):
    """Removes a  member from a role binding."""
    binding = next(b for b in policy["bindings"] if b["role"] == role)
    if "members" in binding and member in binding["members"]:
        binding["members"].remove(member)
    print(binding)
    return policy

后续步骤

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