Remover um membro de uma vinculação do papel

Demonstra a remoção de um membro de uma vinculação de papel em uma política do IAM.

Mais informações

Para ver a documentação detalhada que inclui este exemplo de código, consulte:

Exemplo de código

C#

Para saber como instalar e usar a biblioteca de cliente do IAM, consulte Bibliotecas de cliente do IAM. Para mais informações, consulte a documentação de referência da API C# do IAM.

Para autenticar no IAM, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


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

Para saber como instalar e usar a biblioteca de cliente do IAM, consulte Bibliotecas de cliente do IAM. Para mais informações, consulte a documentação de referência da API Go do IAM.

Para autenticar no IAM, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Para saber como instalar e usar a biblioteca de cliente do IAM, consulte Bibliotecas de cliente do IAM. Para mais informações, consulte a documentação de referência da API Java do IAM.

Para autenticar no IAM, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Para saber como instalar e usar a biblioteca de cliente do IAM, consulte Bibliotecas de cliente do IAM. Para mais informações, consulte a documentação de referência da API Python do IAM.

Para autenticar no IAM, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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)

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte a pesquisa de exemplos de código do Google Cloud.