刪除自訂角色

示範如何刪除自訂角色。

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列內容:

程式碼範例

C++

如要瞭解如何安裝及使用 IAM 的用戶端程式庫,請參閱 IAM 用戶端程式庫。 詳情請參閱 IAM C++ API 參考說明文件

如要向 IAM 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::DeleteRoleRequest request;
  request.set_name(name);
  auto response = client.DeleteRole(request);
  if (!response) throw std::move(response).status();
  std::cout << "Role successfully deleted: " << response->DebugString()
            << "\n";
}

C#

如要瞭解如何安裝及使用 IAM 的用戶端程式庫,請參閱 IAM 用戶端程式庫。 詳情請參閱 IAM C# API 參考說明文件

如要向 IAM 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


using System;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

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

        service.Projects.Roles.Delete(
            $"projects/{projectId}/roles/{name}").Execute();
        Console.WriteLine("Deleted role: " + name);
    }
}

Go

如要瞭解如何安裝及使用 IAM 的用戶端程式庫,請參閱 IAM 用戶端程式庫。 詳情請參閱 IAM Go API 參考說明文件

如要向 IAM 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// deleteRole deletes a custom role.
func deleteRole(w io.Writer, projectID, name string) error {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %w", err)
	}

	_, err = service.Projects.Roles.Delete("projects/" + projectID + "/roles/" + name).Do()
	if err != nil {
		return fmt.Errorf("Projects.Roles.Delete: %w", err)
	}
	fmt.Fprintf(w, "Deleted role: %v", name)
	return nil
}

Java

如要瞭解如何安裝及使用 IAM 的用戶端程式庫,請參閱 IAM 用戶端程式庫。 詳情請參閱 IAM Java API 參考說明文件

如要向 IAM 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.DeleteRoleRequest;
import java.io.IOException;

/** Delete role. */
public class DeleteRole {

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

    deleteRole(projectId, roleId);
  }

  public static void deleteRole(String projectId, String roleId) throws IOException {
    String roleName = "projects/" + projectId + "/roles/" + roleId;
    DeleteRoleRequest deleteRoleRequest = DeleteRoleRequest.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()) {
      iamClient.deleteRole(deleteRoleRequest);
      System.out.println("Role deleted.");
    }
  }
}

Python

如要瞭解如何安裝及使用 IAM 的用戶端程式庫,請參閱 IAM 用戶端程式庫。 詳情請參閱 IAM Python API 參考說明文件

如要向 IAM 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.api_core.exceptions import FailedPrecondition, NotFound
from google.cloud.iam_admin_v1 import (
    DeleteRoleRequest,
    IAMClient,
    Role,
    UndeleteRoleRequest,
)
def delete_role(project_id: str, role_id: str) -> Role:
    """Deletes iam role in GCP project. Can be undeleted later.
    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 = DeleteRoleRequest(name=name)
    try:
        role = client.delete_role(request)
        print(f"Deleted 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}] already deleted, take some actions)", err)

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽器