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.

def edit_role(
    name: str, project: str, title: str, description: str, permissions: str, stage: str
) -> dict:
    """Creates a role."""

    # pylint: disable=no-member
    role = (
        service.projects()
        .roles()
        .patch(
            name="projects/" + project + "/roles/" + name,
            body={
                "title": title,
                "description": description,
                "includedPermissions": permissions,
                "stage": stage,
            },
        )
        .execute()
    )

    print("Updated role: " + role["name"])
    return role

What's next

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