修改自定义角色

演示了如何修改自定义角色。

深入探索

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

代码示例

C++

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

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

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name, std::string const& title) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::UpdateRoleRequest request;
  request.set_name(name);
  google::iam::admin::v1::Role role;
  role.set_title(title);
  google::protobuf::FieldMask update_mask;
  *update_mask.add_paths() = "title";
  *request.mutable_role() = role;
  *request.mutable_update_mask() = update_mask;
  auto response = client.UpdateRole(request);
  if (!response) throw std::move(response).status();
  std::cout << "Role successfully updated: " << 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 EditRole(string name, string projectId, string newTitle,
        string newDescription, IList<string> newPermissions, string newStage)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });
        // First, get a Role using List() or Get().
        string resource = $"projects/{projectId}/roles/{name}";
        var role = service.Projects.Roles.Get(resource).Execute();
        // Then you can update its fields.
        role.Title = newTitle;
        role.Description = newDescription;
        role.IncludedPermissions = newPermissions;
        role.Stage = newStage;
        role = service.Projects.Roles.Patch(role, resource).Execute();
        Console.WriteLine("Updated role: " + role.Name);
        return role;
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"

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

// editRole modifies a custom role.
func editRole(w io.Writer, projectID, name, newTitle, newDescription, newStage string, newPermissions []string) (*iam.Role, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	resource := "projects/" + projectID + "/roles/" + name
	role, err := service.Projects.Roles.Get(resource).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.Roles.Get: %w", err)
	}
	role.Title = newTitle
	role.Description = newDescription
	role.IncludedPermissions = newPermissions
	role.Stage = newStage
	role, err = service.Projects.Roles.Patch(resource, role).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.Roles.Patch: %w", err)
	}
	fmt.Fprintf(w, "Updated 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.Role;
import com.google.iam.admin.v1.Role.RoleLaunchStage;
import com.google.iam.admin.v1.UpdateRoleRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;

/** Edit role metadata. Specifically, update description and launch stage. */
public class EditRole {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    // Role ID must point to an existing role.
    String projectId = "your-project-id";
    String roleId = "a unique identifier (e.g. testViewer)";
    String description = "a new description of the role";

    editRole(projectId, roleId, description);
  }

  public static void editRole(String projectId, String roleId, String description)
      throws IOException {
    String roleName = "projects/" + projectId + "/roles/" + roleId;
    Role.Builder roleBuilder =
        Role.newBuilder()
            .setName(roleName)
            .setDescription(description)
            // See launch stage enums at
            // https://cloud.google.com/iam/docs/reference/rpc/google.iam.admin.v1#rolelaunchstage
            .setStage(RoleLaunchStage.GA);
    FieldMask fieldMask = FieldMask.newBuilder().addPaths("description").addPaths("stage").build();
    UpdateRoleRequest updateRoleRequest =
        UpdateRoleRequest.newBuilder()
            .setName(roleName)
            .setRole(roleBuilder)
            .setUpdateMask(fieldMask)
            .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.updateRole(updateRoleRequest);
      System.out.println("Edited role:\n" + result);
    }
  }
}

Python

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

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

from google.api_core.exceptions import NotFound
from google.cloud.iam_admin_v1 import IAMClient, Role, UpdateRoleRequest

from snippets.get_role import get_role


def edit_role(role: Role) -> Role:
    """
    Edits an existing IAM role in a GCP project.
    Args:
        role: google.cloud.iam_admin_v1.Role object to be updated

    Returns: Updated google.cloud.iam_admin_v1.Role object
    """
    client = IAMClient()
    request = UpdateRoleRequest(name=role.name, role=role)
    try:
        role = client.update_role(request)
        print(f"Edited role: {role.name}: {role}")
        return role
    except NotFound:
        print(f"Role [{role.name}] not found, take some actions")

后续步骤

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