从角色绑定中移除成员

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

深入探索

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

代码示例

C#

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

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


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;
        }
    }
}

Go

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

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

import (
	"fmt"
	"io"

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

// removeMember removes a member from a role binding.
func removeMember(w io.Writer, policy *iam.Policy, role, member string) {
	bindings := policy.Bindings
	bindingIndex, memberIndex := -1, -1
	for bIdx := range bindings {
		if bindings[bIdx].Role != role {
			continue
		}
		bindingIndex = bIdx
		for mIdx := range bindings[bindingIndex].Members {
			if bindings[bindingIndex].Members[mIdx] != member {
				continue
			}
			memberIndex = mIdx
			break
		}
	}
	if bindingIndex == -1 {
		fmt.Fprintf(w, "Role %q not found. Member not removed.\n", role)
		return
	}
	if memberIndex == -1 {
		fmt.Fprintf(w, "Role %q found. Member not found.\n", role)
		return
	}

	members := removeIdx(bindings[bindingIndex].Members, memberIndex)
	bindings[bindingIndex].Members = members
	if len(members) == 0 {
		bindings = removeIdx(bindings, bindingIndex)
		policy.Bindings = bindings
	}
	fmt.Fprintf(w, "Role %q found. Member removed.\n", role)
}

// removeIdx removes arr[idx] from arr.
func removeIdx[T any](arr []T, idx int) []T {
	return append(arr[:idx], arr[idx+1:]...)
}

Java

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

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

import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class RemoveMember {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    // TODO: Replace with your policy, GetPolicy.getPolicy(projectId, serviceAccount).
    Policy policy = Policy.newBuilder().build();
    // TODO: Replace with your role.
    String role = "roles/existing-role";
    // TODO: Replace with your member.
    String member = "user:member-to-add@example.com";

    removeMember(policy, role, member);
  }

  // Removes member from a role; removes binding if binding contains no members.
  public static Policy removeMember(Policy policy, String role, String member) {
    // Creating new builder with all values copied from origin policy
    Policy.Builder policyBuilder = policy.toBuilder();

    // Getting binding with suitable role.
    Binding binding = null;
    for (Binding b : policy.getBindingsList()) {
      if (b.getRole().equals(role)) {
        binding = b;
        break;
      }
    }

    if (binding != null && binding.getMembersList().contains(member)) {
      List<String> newMemberList = new ArrayList<>(binding.getMembersList());
      // Removing member from a role
      newMemberList.remove(member);

      System.out.println("Member " + member + " removed from " + role);

      // Adding all remaining members to create new binding
      Binding newBinding = binding.toBuilder()
              .clearMembers()
              .addAllMembers(newMemberList)
              .build();

      List<Binding> newBindingList = new ArrayList<>(policyBuilder.getBindingsList());

      // Removing old binding to replace with new one
      newBindingList.remove(binding);

      // If binding has no more members, binding will not be added
      if (!newBinding.getMembersList().isEmpty()) {
        newBindingList.add(newBinding);
      }

      // Update the policy to remove the member.
      policyBuilder.clearBindings()
              .addAllBindings(newBindingList);
    }

    Policy updatedPolicy = policyBuilder.build();

    System.out.println("Exising members: " + updatedPolicy.getBindingsList());

    return updatedPolicy;
  }
}

Python

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

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

from google.iam.v1 import policy_pb2
from snippets.get_policy import get_project_policy
from snippets.set_policy import set_project_policy


def modify_policy_remove_member(
    project_id: str, role: str, member: str
) -> policy_pb2.Policy:
    """
    Remove a member from certain role in project policy.

    project_id: ID or number of the Google Cloud project you want to use.
    role: role to which member need to be added.
    member: The principals requesting access.

    Possible format for member:
        * user:{emailid}
        * serviceAccount:{emailid}
        * group:{emailid}
        * deleted:user:{emailid}?uid={uniqueid}
        * deleted:serviceAccount:{emailid}?uid={uniqueid}
        * deleted:group:{emailid}?uid={uniqueid}
        * domain:{domain}
    """
    policy = get_project_policy(project_id)

    for bind in policy.bindings:
        if bind.role == role:
            if member in bind.members:
                bind.members.remove(member)
            break

    return set_project_policy(project_id, policy, False)

后续步骤

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