Restore a deleted custom role

Demonstrates restoring 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) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::UndeleteRoleRequest request;
  request.set_name(name);
  auto response = client.UndeleteRole(request);
  if (!response) throw std::move(response).status();
  std::cout << "Role successfully undeleted: " << 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 Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class CustomRoles
{
    public static Role UndeleteRole(string name, string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        string resource = $"projects/{projectId}/roles/{name}";
        var role = service.Projects.Roles.Undelete(
            new UndeleteRoleRequest(), resource).Execute();
        Console.WriteLine("Undeleted 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"
)

// undeleteRole restores a deleted custom role.
func undeleteRole(w io.Writer, projectID, name 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
	request := &iam.UndeleteRoleRequest{}
	role, err := service.Projects.Roles.Undelete(resource, request).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.Roles.Undelete: %w", err)
	}
	fmt.Fprintf(w, "Undeleted 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.UndeleteRoleRequest;
import java.io.IOException;

/**
 * Undelete a role to return it to its previous state. Undeleting only works on roles that were
 * deleted in the past 7 days.
 */
public class UndeleteRole {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    // Role ID must point to a role that was deleted in the past 7 days.
    String projectId = "your-project-id";
    String roleId = "a unique identifier (e.g. testViewer)";

    undeleteRole(projectId, roleId);
  }

  public static void undeleteRole(String projectId, String roleId) throws IOException {
    String roleName = "projects/" + projectId + "/roles/" + roleId;
    UndeleteRoleRequest undeleteRoleRequest =
        UndeleteRoleRequest.newBuilder().setName(roleName).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.undeleteRole(undeleteRoleRequest);
      System.out.println("Undeleted 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 FailedPrecondition, NotFound
from google.cloud.iam_admin_v1 import (
    DeleteRoleRequest,
    IAMClient,
    Role,
    UndeleteRoleRequest,
)

def undelete_role(project_id: str, role_id: str) -> Role:
    """
    Undeleted deleted iam role in GCP project
    Args:
        project_id: GCP project id
        role_id: id of GCP iam role

    Returns: google.cloud.iam_admin_v1.Role object
    """
    client = IAMClient()
    name = f"projects/{project_id}/roles/{role_id}"
    request = UndeleteRoleRequest(name=name)
    try:
        role = client.undelete_role(request)
        print(f"Undeleted role: {role_id}: {role}")
        return role
    except NotFound:
        print(f"Role with id [{role_id}] not found, take some actions")
    except FailedPrecondition as err:
        print(f"Role with id [{role_id}] is not deleted, take some actions)", err)

What's next

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