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.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

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.