מחיקה של חשבון שירות

הדגמת מחיקה של חשבון שירות.

המשך למידה

לקבלת הסבר מפורט שכולל את דוגמת הקוד הזו, כדאי לקרוא את המאמר:

דוגמת קוד

C++

כדי ללמוד איך מתקינים את ספריית הלקוח ואיך משתמשים בה ב-IAM, ראו: ספריות לקוח של IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM C++ API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response = client.DeleteServiceAccount(name);
  if (!response.ok()) throw std::runtime_error(response.message());
  std::cout << "ServiceAccount successfully deleted.\n";
}

C#

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM C# API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

public partial class ServiceAccounts
{
    public static void DeleteServiceAccount(string email)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        string resource = "projects/-/serviceAccounts/" + email;
        service.Projects.ServiceAccounts.Delete(resource).Execute();
        Console.WriteLine("Deleted service account: " + email);
    }
}

Go

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Go API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

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

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

	_, err = service.Projects.ServiceAccounts.Delete("projects/-/serviceAccounts/" + email).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Delete: %w", err)
	}
	fmt.Fprintf(w, "Deleted service account: %v", email)
	return nil
}

Java

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Java API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

public class DeleteServiceAccount {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    String projectId = "your-project-id";
    String serviceAccountName = "my-service-account-name";

    deleteServiceAccount(projectId, serviceAccountName);
  }

  // Deletes a service account.
  public static void deleteServiceAccount(String projectId, String serviceAccountName)
          throws IOException {
    // Initialize client that will be used to send requests.
    // This client only needs to be created once, and can be reused for multiple requests.
    try (IAMClient client = IAMClient.create()) {
      String accountName = ServiceAccountName.of(projectId, serviceAccountName).toString();
      String accountEmail = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);
      DeleteServiceAccountRequest request = DeleteServiceAccountRequest.newBuilder()
              .setName(accountEmail)
              .build();
      client.deleteServiceAccount(request);

      System.out.println("Deleted service account: " + serviceAccountName);
    }
  }
}

Python

במאמר ספריות הלקוח של IAM מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-IAM. למידע נוסף, קראו את מאמרי העזרה של ‎IAM Python API‎.

כדי לבצע אימות ב-IAM, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import iam_admin_v1
from google.cloud.iam_admin_v1 import types


def delete_service_account(project_id: str, account: str) -> None:
    """Deletes a service account.

    project_id: ID or number of the Google Cloud project you want to use.
    account: ID or email which is unique identifier of the service account.
    """

    iam_admin_client = iam_admin_v1.IAMClient()
    request = types.DeleteServiceAccountRequest()
    request.name = f"projects/{project_id}/serviceAccounts/{account}"

    iam_admin_client.delete_service_account(request=request)
    print(f"Deleted a service account: {account}")

המאמרים הבאים

כדי לחפש ולסנן דוגמאות קוד למוצרים אחרים של Google Cloud , אפשר להיעזר בדפדפן לדוגמאות שלGoogle Cloud .