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.

def undelete_role(name: str, project: str) -> dict:
    """Undeletes a role."""

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

    print("Disabled 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.