创建和管理自定义角色

本页面介绍如何创建和管理 Identity and Access Management (IAM) 自定义角色。管理角色的操作包括修改、停用、列出、删除和取消删除角色。

准备工作

  • Enable the IAM API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  • 设置身份验证。

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    安装 Google Cloud CLI,然后使用联合身份登录 gcloud CLI。 登录后,运行以下命令来初始化 Google Cloud CLI:

    gcloud init

    C#

    如需在本地开发环境中使用本页面上的 .NET 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭证设置应用默认凭证。

      安装 Google Cloud CLI,然后使用联合身份登录 gcloud CLI

      Create local authentication credentials for your user account:

      gcloud auth application-default login

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Google Cloud

    C++

    如需在本地开发环境中使用本页面上的 C++ 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭证设置应用默认凭证。

      安装 Google Cloud CLI,然后使用联合身份登录 gcloud CLI

      Create local authentication credentials for your user account:

      gcloud auth application-default login

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    如需了解详情,请参阅 Google Cloud 身份验证文档中的为本地开发环境设置 ADC

    Go

    如需在本地开发环境中使用本页面上的 Go 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭证设置应用默认凭证。

      安装 Google Cloud CLI,然后使用联合身份登录 gcloud CLI

      Create local authentication credentials for your user account:

      gcloud auth application-default login

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Google Cloud

    Java

    如需在本地开发环境中使用本页面上的 Java 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭证设置应用默认凭证。

      安装 Google Cloud CLI,然后使用联合身份登录 gcloud CLI

      Create local authentication credentials for your user account:

      gcloud auth application-default login

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Google Cloud

    Python

    如需在本地开发环境中使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭证设置应用默认凭证。

      安装 Google Cloud CLI,然后使用联合身份登录 gcloud CLI

      Create local authentication credentials for your user account:

      gcloud auth application-default login

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Google Cloud

    REST

    如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭证。

      安装 Google Cloud CLI,然后使用联合身份登录 gcloud CLI

    如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证

  • 了解 Google Cloud 资源层次结构

  • 阅读了解 IAM 自定义角色

所需的角色

如需获得创建和管理自定义角色所需的权限,请让管理员向您授予以下 IAM 角色:

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

查看项目、文件夹和组织的可用权限

您可以为整个组织或该组织中的特定项目创建自定义角色。自定义角色可用的权限取决于您创建该角色的位置。例如,如果有某项权限只能在组织级层使用,那么您便无法在项目级层自定义角色中添加该权限。

如需检查组织级层和项目级自定义角色可以使用哪些权限,您可以使用 gcloud CLI 或 Identity and Access Management API,列出特定组织或项目中可用的权限。例如,您可以获取可用于在项目中创建的自定义角色的所有权限。

某些权限可能对您不可见或不可用于自定义角色,即使这些权限在自定义角色中受支持也是如此。例如,如果您尚未为服务启用 API,则可能无法在自定义角色中使用某项权限。

如需详细了解可以添加到自定义角色的权限,请参阅支持的权限

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 使用 gcloud iam list-testable-permissions 命令获取特定项目或组织中自定义角色可用的权限列表。响应会列出您可以在该项目或组织的自定义角色中使用的权限。

    要列出项目或组织的自定义角色中可用的权限,请运行此命令:

    gcloud iam list-testable-permissions FULL_RESOURCE_NAME \
        --filter="customRolesSupportLevel!=NOT_SUPPORTED"

    FULL_RESOURCE_NAME 替换为以下某个值:

    • 项目://cloudresourcemanager.googleapis.com/projects/PROJECT_ID(例如 //cloudresourcemanager.googleapis.com/projects/my-project

    • 组织://cloudresourcemanager.googleapis.com/organizations/NUMERIC_ID(例如 //cloudresourcemanager.googleapis.com/organizations/123456789012

    结果会指明自定义角色是否支持每个权限。 没有 customRolesSupportLevel 字段的权限完全受支持。

    list-testable-permissions 命令可能会返回数百个结果。以下部分示例显示了每个结果的格式:

    ---
    name: appengine.applications.create
    stage: GA
    ---
    customRolesSupportLevel: TESTING
    name: appengine.applications.disable
    stage: GA
    ---
    name: appengine.applications.get
    stage: GA
    ---
    name: appengine.applications.update
    stage: GA
    ---
    name: appengine.instances.delete
    stage: GA
    ---
    name: appengine.instances.get
    stage: GA
    ---
    
  3. C++

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

    如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

    namespace iam = ::google::cloud::iam_admin_v1;
    [](std::string const& resource) {
      iam::IAMClient client(iam::MakeIAMConnection());
      google::iam::admin::v1::QueryTestablePermissionsRequest request;
      request.set_full_resource_name(resource);
      int count = 0;
      for (auto& permission : client.QueryTestablePermissions(request)) {
        if (!permission) throw std::move(permission).status();
        std::cout << "Permission successfully retrieved: " << permission->name()
                  << "\n";
        ++count;
      }
      if (count == 0) {
        std::cout << "No testable permissions found in resource: " << resource
                  << "\n";
      }
    }

    C#

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

    如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

    
    using System;
    using System.Collections.Generic;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Iam.v1;
    using Google.Apis.Iam.v1.Data;
    
    public partial class CustomRoles
    {
        public static IList<Permission> QueryTestablePermissions(
            string fullResourceName)
        {
            var credential = GoogleCredential.GetApplicationDefault()
                .CreateScoped(IamService.Scope.CloudPlatform);
            var service = new IamService(new IamService.Initializer
            {
                HttpClientInitializer = credential
            });
    
            var request = new QueryTestablePermissionsRequest
            {
                FullResourceName = fullResourceName
            };
            var response = service.Permissions.QueryTestablePermissions(request)
                .Execute();
            foreach (var p in response.Permissions)
            {
                Console.WriteLine(p.Name);
            }
            return response.Permissions;
        }
    }
    

    Go

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

    如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

    import (
    	"context"
    	"fmt"
    	"io"
    
    	iam "google.golang.org/api/iam/v1"
    )
    
    // queryTestablePermissions lists testable permissions on a resource.
    func queryTestablePermissions(w io.Writer, fullResourceName string) ([]*iam.Permission, error) {
    	ctx := context.Background()
    	service, err := iam.NewService(ctx)
    	if err != nil {
    		return nil, fmt.Errorf("iam.NewService: %w", err)
    	}
    
    	request := &iam.QueryTestablePermissionsRequest{
    		FullResourceName: fullResourceName,
    	}
    	response, err := service.Permissions.QueryTestablePermissions(request).Do()
    	if err != nil {
    		return nil, fmt.Errorf("Permissions.QueryTestablePermissions: %w", err)
    	}
    	for _, p := range response.Permissions {
    		fmt.Fprintf(w, "Found permissions: %v", p.Name)
    	}
    	return response.Permissions, nil
    }
    

    Java

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

    如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

    
    import com.google.cloud.iam.admin.v1.IAMClient;
    import com.google.cloud.iam.admin.v1.IAMClient.QueryTestablePermissionsPagedResponse;
    import com.google.iam.admin.v1.QueryTestablePermissionsRequest;
    import java.io.IOException;
    
    /** View available permissions in a project. */
    public class QueryTestablePermissions {
      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace the variable before running the sample.
        // Full resource names can take one of the following forms:
        // cloudresourcemanager.googleapis.com/projects/PROJECT_ID
        // cloudresourcemanager.googleapis.com/organizations/NUMERIC_ID
        String fullResourceName = "your-full-resource-name";
    
        queryTestablePermissions(fullResourceName);
      }
    
      public static void queryTestablePermissions(String fullResourceName) throws IOException {
        QueryTestablePermissionsRequest queryTestablePermissionsRequest =
            QueryTestablePermissionsRequest.newBuilder().setFullResourceName(fullResourceName).build();
    
        try (IAMClient iamClient = IAMClient.create()) {
          QueryTestablePermissionsPagedResponse queryTestablePermissionsPagedResponse =
              iamClient.queryTestablePermissions(queryTestablePermissionsRequest);
          queryTestablePermissionsPagedResponse
              .iterateAll()
              .forEach(permission -> System.out.println(permission.getName()));
        }
      }
    }

    Python

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

    如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

    import os
    from typing import List
    
    from google.cloud import resourcemanager_v3
    from google.iam.v1 import iam_policy_pb2, policy_pb2
    
    
    def query_testable_permissions(
        project_id: str, permissions: List[str]
    ) -> policy_pb2.Policy:
        """Tests IAM permissions of the caller.
    
        project_id: ID or number of the Google Cloud project you want to use.
        permissions: List of permissions to get.
        """
    
        client = resourcemanager_v3.ProjectsClient()
        request = iam_policy_pb2.TestIamPermissionsRequest()
        request.resource = f"projects/{project_id}"
        request.permissions.extend(permissions)
    
        permissions_reponse = client.test_iam_permissions(request)
        print(permissions_reponse)
        return permissions_reponse.permissions

    REST

    permissions.queryTestablePermissions 方法可列出组织或项目可用的权限。

    在使用任何请求数据之前,请先进行以下替换:

    • FULL_RESOURCE_NAME:由服务名称和资源路径组成的 URI。如需查看示例,请参阅完整资源名称
    • PAGE_SIZE:可选。要包含在响应中的权限的数量。默认值为 100,最大值为 1000。如果权限数大于页面大小,则响应中会包含分页令牌,您可以使用该令牌检索下一页结果。
    • NEXT_PAGE_TOKEN:可选。此方法之前的响应中返回的分页令牌。如果已指定,则可测试权限列表将从上一个响应结束的位置开始。

    HTTP 方法和网址:

    POST https://iam.googleapis.com/v1/permissions:queryTestablePermissions

    请求 JSON 正文:

    {
      "fullResourceName": "FULL_RESOURCE_NAME"
      "pageSize": PAGE_SIZE,
      "pageToken": "NEXT_PAGE_TOKEN"
    }
    

    如需发送您的请求,请展开以下选项之一:

    响应包含权限列表。

    {
      "permissions": [
        {
          "name": "iam.serviceAccountKeys.create",
          "stage": "GA"
        },
        {
          "name": "iam.serviceAccountKeys.delete",
          "stage": "GA"
        },
        {
          "name": "iam.serviceAccountKeys.get",
          "stage": "GA"
        }
      ],
      "nextPageToken": "CgoHBajEfjUDQyABEPaIv5vIiMDTVhgDIhtpYW0uc2VydmljZUFjY291bnRLZXlzLmxpc3Q"
    }
    

获取角色元数据

在创建自定义角色之前,您应先获取预定义角色和自定义角色的元数据。角色元数据包括角色 ID 和角色所含的权限。您可以使用Google Cloud 控制台或 IAM API 查看元数据。

要查看角色元数据,请使用以下方法之一:

控制台

  1. 在 Google Cloud 控制台中,前往角色页面。

    转到“角色”页面

  2. 从页面顶部的下拉列表中选择您的组织或项目。

  3. 选中一个或多个角色对应的复选框以查看角色权限。 右侧面板会显示相应角色中所含的权限(如有)。

类型列中的图标表明这是自定义角色还是预定义角色

如果您想要查找包含特定权限的所有角色,请在“角色”列表顶部的过滤条件框中输入权限名称。

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 使用 gcloud iam roles describe 命令查看预定义角色和自定义角色的元数据。

    要查看预定义角色的元数据,请执行以下命令:

    gcloud iam roles describe ROLE_ID

    ROLE_ID 是角色的 ID。预定义角色的 ID 中包含 role 前缀,例如 roles/iam.roleViewer

    以下示例演示了针对预定义角色 roles/iam.roleViewer 执行 describe 命令时的输出结果:

    gcloud iam roles describe roles/iam.roleViewer

    description: Read access to all custom roles in the project.
    etag: AA==
    includedPermissions:
    - iam.roles.get
    - iam.roles.list
    - resourcemanager.projects.get
    - resourcemanager.projects.getIamPolicy
    name: roles/iam.roleViewer
    stage: GA
    title: Role Viewer

    要查看自定义角色的元数据,请执行以下命令之一:

    • 要查看在组织级层创建的自定义角色的元数据,请执行以下命令:

      gcloud iam roles describe --organization=ORGANIZATION_ID ROLE_ID
    • 要查看在项目级层创建的自定义角色的元数据,请执行以下命令:

      gcloud iam roles describe --project=PROJECT_ID ROLE_ID

    每个占位值的说明如下:

    • ORGANIZATION_ID 是组织的数字 ID,例如 123456789012

    • PROJECT_ID 是项目的名称,例如 my-project

    • ROLE_ID 是角色的 ID,不包括 projects/organizations/roles/ 等任何前缀。例如 myCompanyAdmin

    如需了解详情,请参阅 gcloud iam roles describe 的参考文档。

  3. C++

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

    如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

    namespace iam = ::google::cloud::iam_admin_v1;
    [](std::string const& name) {
      iam::IAMClient client(iam::MakeIAMConnection());
      google::iam::admin::v1::GetRoleRequest request;
      request.set_name(name);
      auto response = client.GetRole(request);
      if (!response) throw std::move(response).status();
      std::cout << "Role successfully retrieved: " << response->DebugString()
                << "\n";
    }

    C#

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

    如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

    
    using System;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Iam.v1;
    using Google.Apis.Iam.v1.Data;
    
    public partial class CustomRoles
    {
        public static Role GetRole(string name)
        {
            var credential = GoogleCredential.GetApplicationDefault()
                .CreateScoped(IamService.Scope.CloudPlatform);
            var service = new IamService(new IamService.Initializer
            {
                HttpClientInitializer = credential
            });
    
            var role = service.Roles.Get(name).Execute();
            Console.WriteLine(role.Name);
            Console.WriteLine(String.Join(", ", role.IncludedPermissions));
            return role;
        }
    }
    

    Go

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

    如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

    import (
    	"context"
    	"fmt"
    	"io"
    
    	iam "google.golang.org/api/iam/v1"
    )
    
    // getRole gets role metadata.
    func getRole(w io.Writer, name string) (*iam.Role, error) {
    	ctx := context.Background()
    	service, err := iam.NewService(ctx)
    	if err != nil {
    		return nil, fmt.Errorf("iam.NewService: %w", err)
    	}
    
    	role, err := service.Roles.Get(name).Do()
    	if err != nil {
    		return nil, fmt.Errorf("Roles.Get: %w", err)
    	}
    	fmt.Fprintf(w, "Got role: %v\n", role.Name)
    	for _, permission := range role.IncludedPermissions {
    		fmt.Fprintf(w, "Got permission: %v\n", permission)
    	}
    	return role, nil
    }
    

    Java

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

    如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

    
    import com.google.cloud.iam.admin.v1.IAMClient;
    import com.google.iam.admin.v1.GetRoleRequest;
    import com.google.iam.admin.v1.Role;
    import java.io.IOException;
    
    /** Get role metadata. Specifically, printing out role permissions. */
    public class GetRole {
    
      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace the variable before running the sample.
        String roleId = "a unique identifier (e.g. testViewer)";
    
        getRole(roleId);
      }
    
      public static void getRole(String roleId) throws IOException {
        GetRoleRequest getRoleRequest = GetRoleRequest.newBuilder().setName(roleId).build();
    
        // Initialize client for sending requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (IAMClient iamClient = IAMClient.create()) {
          Role role = iamClient.getRole(getRoleRequest);
          role.getIncludedPermissionsList().forEach(permission -> System.out.println(permission));
        }
      }
    }

    Python

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

    如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

    from google.api_core.exceptions import NotFound
    from google.cloud.iam_admin_v1 import GetRoleRequest, IAMClient, Role
    
    
    def get_role(project_id: str, role_id: str) -> Role:
        client = IAMClient()
        name = f"projects/{project_id}/roles/{role_id}"
        request = GetRoleRequest(name=name)
        try:
            role = client.get_role(request)
            print(f"Retrieved role: {role_id}: {role}")
            return role
        except NotFound as exc:
            raise NotFound(f"Role with id [{role_id}] not found, take some actions") from exc

    REST

    roles.get 方法可获取角色的定义。

    在使用任何请求数据之前,请先进行以下替换:

    • ROLE_NAME:完整的角色名称,包括任何 organizations/projects/roles/ 前缀。例如 organizations/123456789012/roles/myCompanyAdmin

    HTTP 方法和网址:

    GET https://iam.googleapis.com/v1/ROLE_NAME

    如需发送您的请求,请展开以下选项之一:

    响应中包含角色定义。

    {
      "name": "projects/my-project/roles/customRole",
      "title": "My Custom Role",
      "description": "My custom role description.",
      "includedPermissions": [
        "storage.buckets.get",
        "storage.buckets.list"
      ],
      "etag": "BwWiPg2fmDE="
    }
    
    

创建自定义角色

您可以在项目或组织级层创建自定义角色。

组织级层自定义角色可以包含自定义角色支持的任何 IAM 权限。项目级层自定义角色可以包含任何受支持的权限,但只能在组织或文件夹级层使用的权限除外,例如 resourcemanager.organizations.get。如果您尝试将这类权限添加到项目级层自定义角色,则会收到错误消息:

控制台

系统会显示以下警告消息:“不适用于项目级层自定义角色”。系统会从已包含权限列表中自动取消选择该权限,您可以继续创建此角色。

gcloud

系统会返回以下错误消息:INVALID_ARGUMENT: Permission PERMISSION is not valid。除非您先从角色定义中移除该权限并重试此操作,否则系统将不会创建该自定义角色。

REST API

系统会返回以下错误消息:Permission PERMISSION is not valid,以及 HTTP 400 错误代码和 INVALID_ARGUMENT 状态。除非您先从角色定义中移除该权限并重试此操作,否则系统将不会创建该自定义角色。

每个自定义角色最多可以包含 3000 个权限。此外,自定义角色的名称、描述和权限名称的总大小不得超过 64 KB。如果您需要创建更大的自定义角色,可以将权限拆分给多个自定义角色。请选择可显示自定义角色之间关系的角色名称,例如 Custom Admin (1 of 2)