Delete an HMAC key

Delete an HMAC key based on the access ID.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C++

For more information, see the Cloud Storage C++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& access_id) {
  google::cloud::Status status = client.DeleteHmacKey(access_id);
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The key is deleted, though it may still appear"
            << " in ListHmacKeys() results.\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


using Google.Cloud.Storage.V1;
using System;

public class DeleteHmacKeySample
{
    public void DeleteHmacKey(
        string projectId = "your-project-id",
        string accessId = "your-access-id")
    {
        var storage = StorageClient.Create();
        storage.DeleteHmacKey(projectId, accessId);

        Console.WriteLine($"Key {accessId} was deleted.");
    }
}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// deleteHMACKey deletes the HMAC key with the given access ID. Key must have state
// INACTIVE in order to succeed.
func deleteHMACKey(w io.Writer, accessID string, projectID string) error {
	ctx := context.Background()

	// Initialize client.
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	handle := client.HMACKeyHandle(projectID, accessID)
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	if err = handle.Delete(ctx); err != nil {
		return fmt.Errorf("Delete: %w", err)
	}

	fmt.Fprintln(w, "The key is deleted, though it may still appear in ListHMACKeys results.")

	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.cloud.storage.HmacKey;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

public class DeleteHmacKey {
  public static void deleteHmacKey(String accessId, String projectId) throws StorageException {

    // The access ID of the HMAC key.
    // String accessId = "GOOG0234230X00";

    // The ID of the project to which the service account belongs.
    // String projectId = "project-id";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    HmacKey.HmacKeyMetadata metadata =
        storage.getHmacKey(accessId, Storage.GetHmacKeyOption.projectId(projectId));
    storage.deleteHmacKey(metadata);

    System.out.println(
        "The key is deleted, though it will still appear in "
            + "getHmacKeys() results if called with showDeletedKey.");
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The access ID of the HMAC key
// const hmacKeyAccessId = 'GOOG0234230X00';

// The ID of the project to which the service account belongs
// const projectId = 'project-id';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

// Delete HMAC SA Key
async function deleteHmacKey() {
  const hmacKey = storage.hmacKey(hmacKeyAccessId, {projectId});
  await hmacKey.delete();

  console.log(
    'The key is deleted, though it may still appear in getHmacKeys() results.'
  );
}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an HMAC key.
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 *        (e.g. 'my-project-id')
 * @param string $accessId Access ID for an HMAC key. (e.g. 'GOOG0234230X00')
 */
function delete_hmac_key(string $projectId, string $accessId): void
{
    $storage = new StorageClient();
    // By default hmacKey will use the projectId used by StorageClient().
    $hmacKey = $storage->hmacKey($accessId, $projectId);

    $hmacKey->delete();
    print(
        'The key is deleted, though it may still appear in the results of calls ' .
        'to StorageClient.hmacKeys([\'showDeletedKeys\' => true])' . PHP_EOL
    );
}

Python

For more information, see the Cloud Storage Python API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import storage


def delete_key(access_id, project_id):
    """
    Delete the HMAC key with the given access ID. Key must have state INACTIVE
    in order to succeed.
    """
    # project_id = "Your Google Cloud project ID"
    # access_id = "ID of an HMAC key (must be in INACTIVE state)"

    storage_client = storage.Client(project=project_id)

    hmac_key = storage_client.get_hmac_key_metadata(
        access_id, project_id=project_id
    )
    hmac_key.delete()

    print(
        "The key is deleted, though it may still appear in list_hmac_keys()"
        " results."
    )

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

def delete_hmac_key access_id:
  # The access ID of the HMAC key
  # access_id = "GOOG0234230X00"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  # By default Storage#hmac_keys uses the Storage client project_id
  hmac_key = storage.hmac_key access_id

  hmac_key.delete!

  puts "The key is deleted, though it may still appear in Client#hmac_keys results."
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.