맞춤 역할 수정

맞춤 역할 수정 방법을 보여줍니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

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 샘플 브라우저를 참조하세요.