创建自定义角色

演示如何创建自定义角色。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& parent, std::string const& role_id,
   std::vector<std::string> const& included_permissions) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::CreateRoleRequest request;
  request.set_parent("projects/" + parent);
  request.set_role_id(role_id);
  google::iam::admin::v1::Role role;
  role.set_stage(google::iam::admin::v1::Role::GA);
  for (auto const& permission : included_permissions) {
    *role.add_included_permissions() = permission;
  }
  *request.mutable_role() = role;
  auto response = client.CreateRole(request);
  if (!response) throw std::move(response).status();
  std::cout << "Role successfully created: " << response->DebugString()
            << "\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 Role CreateRole(string name, string projectId, string title,
        string description, IList<string> permissions, string stage)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var role = new Role
        {
            Title = title,
            Description = description,
            IncludedPermissions = permissions,
            Stage = stage
        };
        var request = new CreateRoleRequest
        {
            Role = role,
            RoleId = name
        };
        role = service.Projects.Roles.Create(request,
            "projects/" + projectId).Execute();
        Console.WriteLine("Created role: " + role.Name);
        return role;
    }
}

Go

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// createRole creates a custom role.
func createRole(w io.Writer, projectID, name, title, description, stage string, permissions []string) (*iam.Role, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	request := &iam.CreateRoleRequest{
		Role: &iam.Role{
			Title:               title,
			Description:         description,
			IncludedPermissions: permissions,
			Stage:               stage,
		},
		RoleId: name,
	}
	role, err := service.Projects.Roles.Create("projects/"+projectID, request).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.Roles.Create: %w", err)
	}
	fmt.Fprintf(w, "Created role: %v", role.Name)
	return role, nil
}

Java

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.CreateRoleRequest;
import com.google.iam.admin.v1.Role;
import com.google.iam.admin.v1.Role.RoleLaunchStage;
import java.io.IOException;
import java.util.Arrays;

/** Create role. */
public class CreateRole {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    String projectId = "your-project-id";
    String roleId = "a unique identifier (e.g. testViewer)";
    String title = "a title for your role (e.g. IAM Role Viewer)";
    String description = "a description of the role";
    Iterable<String> includedPermissions =
        Arrays.asList("roles/iam.roleViewer", "roles/logging.viewer");

    createRole(projectId, title, description, includedPermissions, roleId);
  }

  public static void createRole(
      String projectId,
      String title,
      String description,
      Iterable<String> includedPermissions,
      String roleId)
      throws IOException {
    Role.Builder roleBuilder =
        Role.newBuilder()
            .setTitle(title)
            .setDescription(description)
            .addAllIncludedPermissions(includedPermissions)
            // See launch stage enums at
            // https://cloud.google.com/iam/docs/reference/rpc/google.iam.admin.v1#rolelaunchstage
            .setStage(RoleLaunchStage.BETA);
    CreateRoleRequest createRoleRequest =
        CreateRoleRequest.newBuilder()
            .setParent("projects/" + projectId)
            .setRoleId(roleId)
            .setRole(roleBuilder)
            .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 result = iamClient.createRole(createRoleRequest);
      System.out.println("Created role: " + result.getName());
    }
  }
}

Python

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

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from typing import List, Optional

from google.api_core.exceptions import AlreadyExists, FailedPrecondition
from google.cloud.iam_admin_v1 import CreateRoleRequest, IAMClient, Role


def create_role(
    project_id: str, role_id: str, permissions: List[str], title: Optional[str] = None
) -> Role:
    """
    Creates iam role with given parameters.
    Args:
        project_id: GCP project id
        role_id: id of GCP iam role
        permissions: list of iam permissions to assign to role. f.e ["iam.roles.get", "iam.roles.list"]
        title: title for iam role. role_id will be used in case of None

    Returns: google.cloud.iam_admin_v1.Role object
    """
    client = IAMClient()

    parent = f"projects/{project_id}"

    request = CreateRoleRequest(
        parent=parent,
        role_id=role_id,
        role=Role(title=title, included_permissions=permissions),
    )
    try:
        role = client.create_role(request)
        print(f"Created iam role: {role_id}: {role}")
        return role
    except AlreadyExists:
        print(f"Role with id [{role_id}] already exists, take some actions")
    except FailedPrecondition:
        print(
            f"Role with id [{role_id}] already exists and in deleted state, take some actions"
        )

后续步骤

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