Edit a custom role

Demonstrates editing a custom role.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C++

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM C++ API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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#

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM C# API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Go API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Java API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Python API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.