将成员添加到角色绑定

演示如何将成员添加到 IAM 政策中的现有角色绑定。

包含此代码示例的文档页面

如需在实际用例中查看代码示例,请参阅以下文档:

代码示例

C#

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


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

Java

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

import com.google.api.services.cloudresourcemanager.v3.model.Binding;
import com.google.api.services.cloudresourcemanager.v3.model.Policy;
import java.util.List;

public class AddMember {

  // Adds a member to a preexisting role.
  public static void addMember(Policy policy) {
    // policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();

    String role = "roles/existing-role";
    String member = "user:member-to-add@example.com";

    List<Binding> bindings = policy.getBindings();

    for (Binding b : bindings) {
      if (b.getRole().equals(role)) {
        b.getMembers().add(member);
        System.out.println("Member " + member + " added to role " + role);
        return;
      }
    }

    System.out.println("Role not found in policy; member not added");
  }
}

Python

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

def modify_policy_add_member(policy, role, member):
    """Adds a new member to a role binding."""

    binding = next(b for b in policy["bindings"] if b["role"] == role)
    binding["members"].append(member)
    print(binding)
    return policy

后续步骤

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