删除服务账号密钥

演示如何删除服务账号密钥。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM C++ API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response = client.DeleteServiceAccountKey(name);
  if (!response.ok()) throw std::runtime_error(response.message());
  std::cout << "ServiceAccountKey successfully deleted.\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 ServiceAccountKeys
{
    public static void DeleteKey(string fullKeyName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        service.Projects.ServiceAccounts.Keys.Delete(fullKeyName).Execute();
        Console.WriteLine("Deleted key: " + fullKeyName);
    }
}

Go

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM Go API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

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

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

	_, err = service.Projects.ServiceAccounts.Keys.Delete(fullKeyName).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Keys.Delete: %w", err)
	}
	fmt.Fprintf(w, "Deleted key: %v", fullKeyName)
	return nil
}

Java

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM Java API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

public class DeleteServiceAccountKey {

  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";
    String serviceAccountKeyId = "service-account-key-id";

    deleteKey(projectId, serviceAccountName, serviceAccountKeyId);
  }

  // Deletes a service account key.
  public static void deleteKey(String projectId, String accountName,
                               String serviceAccountKeyId) 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 iamClient = IAMClient.create()) {

      //Construct the service account email.
      //You can modify the ".iam.gserviceaccount.com" to match the service account name in which
      //you want to delete the key.
      //See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys#deleting

      String accountEmail = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);

      String name = KeyName.of(projectId, accountEmail, serviceAccountKeyId).toString();

      DeleteServiceAccountKeyRequest request = DeleteServiceAccountKeyRequest.newBuilder()
              .setName(name)
              .build();

      // Then you can delete the key
      iamClient.deleteServiceAccountKey(request);

      System.out.println("Deleted key: " + serviceAccountKeyId);
    }
  }
}

Python

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。 如需了解详情,请参阅 IAM Python API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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


def delete_key(project_id: str, account: str, key_id: str) -> None:
    """
    Deletes a key for 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.
    key_id: unique ID of the key.
    """

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

    iam_admin_client.delete_service_account_key(request=request)
    print(f"Deleted key: {key_id}")

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器