Borre una clave de cuenta de servicio

Se muestra cómo borrar una clave de cuenta de servicio.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

C++

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM C++.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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#

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM C#.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Go.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Java.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class DeleteServiceAccountKey {

  // Deletes a service account key.
  public static void deleteKey(String projectId, String serviceAccountName,
      String serviceAccountKey) {
    // String projectId = "my-project-id";
    // String serviceAccountName = "my-service-account-name";
    // String serviceAccountKey = "key-name";

    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e);
      return;
    }

    // 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?hl=en#deleting
    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      String keyToDelete = String.format("projects/-/serviceAccounts/%s/keys/%s",
          serviceAccountEmail, serviceAccountKey);

      // Then you can delete the key
      service.projects().serviceAccounts().keys().delete(keyToDelete).execute();

      System.out.println("Deleted key: " + keyToDelete);
    } catch (IOException e) {
      System.out.println("Unable to delete service account key: \n" + e);
    }
  }

  private static Iam initService() throws GeneralSecurityException, IOException {
    // Use the Application Default Credentials strategy for authentication. For more info, see:
    // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-account-keys")
            .build();
    return service;
  }
}

Python

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Python.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import os

from google.oauth2 import service_account
import googleapiclient.discovery  # type: ignore

def delete_key(full_key_name: str) -> None:
    """Deletes a service account key."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )

    service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)

    service.projects().serviceAccounts().keys().delete(name=full_key_name).execute()

    print("Deleted key: " + full_key_name)

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.