Add a principal to a role binding

Demonstrates adding a principal to an existing 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 AddMember(Policy policy, string role, string member)
    {
        var binding = policy.Bindings.First(x => x.Role == role);
        binding.Members.Add(member);
        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"
)

// addMember adds a member to a role binding.
func addMember(w io.Writer, policy *iam.Policy, role, member string) {
	for _, binding := range policy.Bindings {
		if binding.Role != role {
			continue
		}
		for _, m := range binding.Members {
			if m != member {
				continue
			}
			fmt.Fprintf(w, "Role %q found. Member already exists.\n", role)
			return
		}
		binding.Members = append(binding.Members, member)
		fmt.Fprintf(w, "Role %q found. Member added.\n", role)
		return
	}
	fmt.Fprintf(w, "Role %q not found. Member not added.\n", role)
}

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.util.ArrayList;
import java.util.List;

public class AddMember {
  public static void main(String[] args) {
    // 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";

    addMember(policy, role, member);
  }

  // Adds a member to a pre-existing role.
  public static Policy addMember(Policy policy, String role, String member) {
    List<Binding> newBindingsList = new ArrayList<>();

    for (Binding b : policy.getBindingsList()) {
      if (b.getRole().equals(role)) {
        newBindingsList.add(b.toBuilder().addMembers(member).build());
      } else {
        newBindingsList.add(b);
      }
    }

    // Update the policy to add the member.
    Policy updatedPolicy = policy.toBuilder()
            .clearBindings()
            .addAllBindings(newBindingsList)
            .build();

    System.out.println("Added member: " + 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.

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_add_member(
    project_id: str, role: str, member: str
) -> policy_pb2.Policy:
    """
    Add a member to 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:
            bind.members.append(member)
            break

    return set_project_policy(project_id, policy)

What's next

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