Remove a member from a role binding

Demonstrates removing a member from a role binding in an IAM policy.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM C# API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Go API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Java API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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 != null && 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

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Python API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

def modify_policy_remove_member(policy: dict, role: str, member: str) -> dict:
    """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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.