This page shows you how to create, disable, and delete Hash-based Message
Authentication Code (HMAC) keys associated with service accounts in your
project.
Before you begin
Before using this feature in Cloud Storage, you must meet the following
requirements:
Have sufficient permission to work with HMAC keys in the selected project:
If you own the project, you most likely have the necessary permissions.
You should have the IAM permissions that are prefixed withstorage.hmacKeysfor the project. SeeUsing IAM Permissionsfor
instructions on how to get a role, such asStorage HMAC Key Admin,
that has these permissions.
Have a service account in your project that you intend to create HMAC keys
for. SeeCreating a service accountif you don't currently have one.
Make sure the following organization policy constraints are disabled:
WhereSERVICE_ACCOUNT_EMAILis the email address
associated with your service account. For example,service-7550275089395@my-pet-project.iam.gserviceaccount.com.
If successful, the response contains anHMAC key resource,
including values for theaccessIdandsecret.
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;return[](gcs::Clientclient,std::stringconst&service_account_email){StatusOr<std::pair<gcs::HmacKeyMetadata,std::string>>key_info=client.CreateHmacKey(service_account_email);if(!key_info)throwstd::move(key_info).status();std::cout<<"The base64 encoded secret is: "<<key_info->second<<"\nDo not miss that secret, there is no API to recover it."<<"\nThe HMAC key metadata is: "<<key_info->first<<"\n";returnkey_info->first.access_id();}
usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassCreateHmacKeySample{publicHmacKeyCreateHmacKey(stringprojectId="your-project-id",stringserviceAccountEmail="dev@iam.gserviceaccount.com"){varstorage=StorageClient.Create();varkey=storage.CreateHmacKey(projectId,serviceAccountEmail);varsecret=key.Secret;varmetadata=key.Metadata;Console.WriteLine($"The Base64 encoded secret is: {secret}");Console.WriteLine("Make sure to save that secret, there's no API to recover it.");Console.WriteLine("The HMAC key metadata is:");Console.WriteLine($"ID: {metadata.Id}");Console.WriteLine($"Access ID: {metadata.AccessId}");Console.WriteLine($"Project ID: {metadata.ProjectId}");Console.WriteLine($"Service Account Email: {metadata.ServiceAccountEmail}");Console.WriteLine($"State: {metadata.State}");Console.WriteLine($"Time Created: {metadata.TimeCreated}");Console.WriteLine($"Time Updated: {metadata.Updated}");Console.WriteLine($"ETag: {metadata.ETag}");returnkey;}}
import("context""fmt""io""time""cloud.google.com/go/storage")// createHMACKey creates a new HMAC key using the given project and service account.funccreateHMACKey(wio.Writer,projectIDstring,serviceAccountEmailstring)(*storage.HMACKey,error){ctx:=context.Background()// Initialize client.client,err:=storage.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()// Closing the client safely cleans up background resources.ctx,cancel:=context.WithTimeout(ctx,time.Minute)defercancel()key,err:=client.CreateHMACKey(ctx,projectID,serviceAccountEmail)iferr!=nil{returnnil,fmt.Errorf("CreateHMACKey: %w",err)}fmt.Fprintf(w,"%s\n",key)fmt.Fprintf(w,"The base64 encoded secret is %s\n",key.Secret)fmt.Fprintln(w,"Do not miss that secret, there is no API to recover it.")fmt.Fprintln(w,"The HMAC key metadata is")fmt.Fprintf(w,"%+v",key)returnkey,nil}
importcom.google.cloud.storage.HmacKey;importcom.google.cloud.storage.ServiceAccount;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;importjava.util.Date;publicclassCreateHmacKey{publicstaticvoidcreateHmacKey(StringserviceAccountEmail,StringprojectId)throwsStorageException{// The service account email for which the new HMAC key will be created.// String serviceAccountEmail = "service-account@iam.gserviceaccount.com";// The ID of the project to which the service account belongs.// String projectId = "project-id";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();ServiceAccountaccount=ServiceAccount.of(serviceAccountEmail);HmacKeyhmacKey=storage.createHmacKey(account,Storage.CreateHmacKeyOption.projectId(projectId));Stringsecret=hmacKey.getSecretKey();HmacKey.HmacKeyMetadatametadata=hmacKey.getMetadata();System.out.println("The Base64 encoded secret is: "+secret);System.out.println("Do not lose that secret, there is no API to recover it.");System.out.println("The HMAC key metadata is:");System.out.println("ID: "+metadata.getId());System.out.println("Access ID: "+metadata.getAccessId());System.out.println("Project ID: "+metadata.getProjectId());System.out.println("Service Account Email: "+metadata.getServiceAccount().getEmail());System.out.println("State: "+metadata.getState().toString());System.out.println("Time Created: "+newDate(metadata.getCreateTime()).toString());System.out.println("Time Updated: "+newDate(metadata.getUpdateTime()).toString());System.out.println("ETag: "+metadata.getEtag());}}
/*** TODO(developer): Uncomment the following lines before running the sample.*/// The service account email for which the new HMAC key will be created// const serviceAccountEmail = 'service-account@iam.gserviceaccount.com';// The ID of the project to which the service account belongs// const projectId = 'project-id';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();// Create HMAC SA KeyasyncfunctioncreateHmacKey(){const[hmacKey,secret]=awaitstorage.createHmacKey(serviceAccountEmail,{projectId,});console.log(`The base64 encoded secret is:${secret}`);console.log('Do not miss that secret, there is no API to recover it.');console.log('The HMAC key metadata is:');for(const[key,value]ofObject.entries(hmacKey.metadata)){console.log(`${key}:${value}`);}}
use Google\Cloud\Storage\StorageClient;/*** Create a new HMAC key.** @param string $projectId The ID of your Google Cloud Platform project.* (e.g. 'my-project-id')* @param string $serviceAccountEmail Service account email to associate with the new HMAC key.* (e.g. 'service-account@iam.gserviceaccount.com')*/function create_hmac_key(string $projectId, string $serviceAccountEmail): void{$storage = new StorageClient();// By default createHmacKey will use the projectId used by StorageClient().$hmacKeyCreated = $storage->createHmacKey($serviceAccountEmail, ['projectId' => $projectId]);printf('The base64 encoded secret is: %s' . PHP_EOL, $hmacKeyCreated->secret());print('Do not miss that secret, there is no API to recover it.' . PHP_EOL);printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKeyCreated->hmacKey()->info(), true));}
fromgoogle.cloudimportstoragedefcreate_key(project_id,service_account_email):"""Create a new HMAC key using the given project and service account."""# project_id = 'Your Google Cloud project ID'# service_account_email = 'Service account used to generate the HMAC key'storage_client=storage.Client(project=project_id)hmac_key,secret=storage_client.create_hmac_key(service_account_email=service_account_email,project_id=project_id)print(f"The base64 encoded secret is{secret}")print("Do not miss that secret, there is no API to recover it.")print("The HMAC key metadata is:")print(f"Service Account Email:{hmac_key.service_account_email}")print(f"Key ID:{hmac_key.id}")print(f"Access ID:{hmac_key.access_id}")print(f"Project ID:{hmac_key.project}")print(f"State:{hmac_key.state}")print(f"Created At:{hmac_key.time_created}")print(f"Updated At:{hmac_key.updated}")print(f"Etag:{hmac_key.etag}")returnhmac_key
defcreate_hmac_keyservice_account_email:# The service account email used to generate an HMAC key# service_account_email = "service-my-project-number@gs-project-accounts.iam.gserviceaccount.com"require"google/cloud/storage"storage=Google::Cloud::Storage.new# By default Storage#create_hmac_key uses the Storage client project_idhmac_key=storage.create_hmac_keyservice_account_emailputs"The base64 encoded secret is:#{hmac_key.secret}"puts"Do not miss that secret, there is no API to recover it."puts"\nThe HMAC key metadata is:"puts"Key ID:#{hmac_key.id}"puts"Service Account Email:#{hmac_key.service_account_email}"puts"Access ID:#{hmac_key.access_id}"puts"Project ID:#{hmac_key.project_id}"puts"Active:#{hmac_key.active?}"puts"Created At:#{hmac_key.created_at}"puts"Updated At:#{hmac_key.updated_at}"puts"Etag:#{hmac_key.etag}"end
# Create a new service account
resource "google_service_account" "service_account" {
account_id = "my-svc-acc"
}
# Create the HMAC key for the associated service account
resource "google_storage_hmac_key" "key" {
service_account_email = google_service_account.service_account.email
}
PROJECT_IDENTIFIERis the ID or number for
the project associated with the key you want to create. For
example,my-pet-project.
SERVICE_ACCOUNT_EMAILis the email
address associated with your service account. For example,service-7550275089395@my-pet-project.iam.gserviceaccount.com.
WhereSERVICE_ACCOUNT_EMAILis the email
address associated with your service account. For example,service-7550275089395@my-pet-project.iam.gserviceaccount.com.
Get HMAC key information
To list the HMAC keys for a project, and get information about the keys:
Console
In the Google Cloud console, go to the Cloud StorageSettingspage.
The following sample retrieves a list of HMAC keys associated with a project:
import("context""fmt""io""time""cloud.google.com/go/storage""google.golang.org/api/iterator")// listHMACKeys lists all HMAC keys associated with the project.funclistHMACKeys(wio.Writer,projectIDstring)([]*storage.HMACKey,error){ctx:=context.Background()// Initialize client.client,err:=storage.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()// Closing the client safely cleans up background resources.ctx,cancel:=context.WithTimeout(ctx,time.Minute)defercancel()iter:=client.ListHMACKeys(ctx,projectID)varkeys[]*storage.HMACKeyfor{key,err:=iter.Next()iferr==iterator.Done{break}iferr!=nil{returnnil,fmt.Errorf("ListHMACKeys: %w",err)}fmt.Fprintf(w,"Service Account Email: %s\n",key.ServiceAccountEmail)fmt.Fprintf(w,"Access ID: %s\n",key.AccessID)keys=append(keys,key)}returnkeys,nil}
The following sample retrieves information for a specific HMAC key:
import("context""fmt""io""time""cloud.google.com/go/storage")// getHMACKey retrieves the HMACKeyMetadata with the given access id.funcgetHMACKey(wio.Writer,accessIDstring,projectIDstring)(*storage.HMACKey,error){ctx:=context.Background()// Initialize client.client,err:=storage.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()// Closing the client safely cleans up background resources.handle:=client.HMACKeyHandle(projectID,accessID)ctx,cancel:=context.WithTimeout(ctx,time.Minute)defercancel()key,err:=handle.Get(ctx)iferr!=nil{returnnil,fmt.Errorf("Get: %w",err)}fmt.Fprintln(w,"The HMAC key metadata is:")fmt.Fprintf(w,"%+v",key)returnkey,nil}
The following sample retrieves a list of HMAC keys associated with a project:
importcom.google.api.gax.paging.Page;importcom.google.cloud.storage.HmacKey;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassListHmacKeys{publicstaticvoidlistHmacKeys(StringprojectId)throwsStorageException{// The ID of the project to which the service account belongs.// String projectId = "project-id";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Page<HmacKey.HmacKeyMetadata>page=storage.listHmacKeys(Storage.ListHmacKeysOption.projectId(projectId));for(HmacKey.HmacKeyMetadatametadata:page.iterateAll()){System.out.println("Service Account Email: "+metadata.getServiceAccount().getEmail());System.out.println("Access ID: "+metadata.getAccessId());}}}
The following sample retrieves information for a specific HMAC key:
importcom.google.cloud.storage.HmacKey;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;importjava.util.Date;publicclassGetHmacKey{publicstaticvoidgetHmacKey(StringaccessId,StringprojectId)throwsStorageException{// 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";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();HmacKey.HmacKeyMetadatametadata=storage.getHmacKey(accessId,Storage.GetHmacKeyOption.projectId(projectId));System.out.println("The HMAC key metadata is:");System.out.println("ID: "+metadata.getId());System.out.println("Access ID: "+metadata.getAccessId());System.out.println("Project ID: "+metadata.getProjectId());System.out.println("Service Account Email: "+metadata.getServiceAccount().getEmail());System.out.println("State: "+metadata.getState().toString());System.out.println("Time Created: "+newDate(metadata.getCreateTime()).toString());System.out.println("Time Updated: "+newDate(metadata.getUpdateTime()).toString());System.out.println("ETag: "+metadata.getEtag());}}
The following sample retrieves a list of HMAC keys associated with a project:
/*** TODO(developer): Uncomment the following lines before running the sample.*/// The ID of the project to which the service account belongs// const projectId = 'project-id';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();// List HMAC SA Keys' MetadataasyncfunctionlistHmacKeys(){const[hmacKeys]=awaitstorage.getHmacKeys({projectId});// hmacKeys is an array of HmacKey objects.for(consthmacKeyofhmacKeys){console.log(`Service Account Email:${hmacKey.metadata.serviceAccountEmail}`);console.log(`Access Id:${hmacKey.metadata.accessId}`);}}
The following sample retrieves information for a specific HMAC key:
/*** 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();// Get HMAC SA Key MetadataasyncfunctiongetHmacKey(){consthmacKey=storage.hmacKey(hmacKeyAccessId,{projectId});// Populate the hmacKey object with metadata from server.awaithmacKey.getMetadata();console.log('The HMAC key metadata is:');for(const[key,value]ofObject.entries(hmacKey.metadata)){console.log(`${key}:${value}`);}}
The following sample retrieves a list of HMAC keys associated with a project:
use Google\Cloud\Storage\StorageClient;/*** List HMAC keys.** @param string $projectId The ID of your Google Cloud Platform project.* (e.g. 'my-project-id')*/function list_hmac_keys(string $projectId): void{$storage = new StorageClient();// By default hmacKeys will use the projectId used by StorageClient() to list HMAC Keys.$hmacKeys = $storage->hmacKeys(['projectId' => $projectId]);printf('HMAC Key\'s:' . PHP_EOL);foreach ($hmacKeys as $hmacKey) {printf('Service Account Email: %s' . PHP_EOL, $hmacKey->info()['serviceAccountEmail']);printf('Access Id: %s' . PHP_EOL, $hmacKey->info()['accessId']);}}
The following sample retrieves information for a specific HMAC key:
use Google\Cloud\Storage\StorageClient;/*** Get 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 get_hmac_key(string $projectId, string $accessId): void{$storage = new StorageClient();$hmacKey = $storage->hmacKey($accessId, $projectId);printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKey->info(), true));}
The following sample retrieves a list of HMAC keys associated with a project:
fromgoogle.cloudimportstoragedeflist_keys(project_id):"""List all HMAC keys associated with the project."""# project_id = "Your Google Cloud project ID"storage_client=storage.Client(project=project_id)hmac_keys=storage_client.list_hmac_keys(project_id=project_id)print("HMAC Keys:")forhmac_keyinhmac_keys:print(f"Service Account Email:{hmac_key.service_account_email}")print(f"Access ID:{hmac_key.access_id}")returnhmac_keys
The following sample retrieves information for a specific HMAC key:
fromgoogle.cloudimportstoragedefget_key(access_id,project_id):"""Retrieve the HMACKeyMetadata with the given access id."""# project_id = "Your Google Cloud project ID"# access_id = "ID of an HMAC key"storage_client=storage.Client(project=project_id)hmac_key=storage_client.get_hmac_key_metadata(access_id,project_id=project_id)print("The HMAC key metadata is:")print(f"Service Account Email:{hmac_key.service_account_email}")print(f"Key ID:{hmac_key.id}")print(f"Access ID:{hmac_key.access_id}")print(f"Project ID:{hmac_key.project}")print(f"State:{hmac_key.state}")print(f"Created At:{hmac_key.time_created}")print(f"Updated At:{hmac_key.updated}")print(f"Etag:{hmac_key.etag}")returnhmac_key
The following sample retrieves a list of HMAC keys associated with a project:
deflist_hmac_keysrequire"google/cloud/storage"storage=Google::Cloud::Storage.new# By default Storage#hmac_keys uses the Storage client project_idhmac_keys=storage.hmac_keysputs"HMAC Keys:"hmac_keys.alldo|hmac_key|puts"Service Account Email:#{hmac_key.service_account_email}"puts"Access ID:#{hmac_key.access_id}"endend
The following sample retrieves information for a specific HMAC key:
defget_hmac_keyaccess_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_idhmac_key=storage.hmac_keyaccess_idputs"The HMAC key metadata is:"puts"Key ID:#{hmac_key.id}"puts"Service Account Email:#{hmac_key.service_account_email}"puts"Access ID:#{hmac_key.access_id}"puts"Project ID:#{hmac_key.project_id}"puts"Active:#{hmac_key.active?}"puts"Created At:#{hmac_key.created_at}"puts"Updated At:#{hmac_key.updated_at}"puts"Etag:#{hmac_key.etag}"end
WhereSERVICE_ACCOUNT_EMAILis the email
address associated with your service account. For example,service-7550275089395@my-pet-project.iam.gserviceaccount.com.
Update the state of an HMAC key
To switch an HMAC key between being active and inactive:
Console
In the Google Cloud console, go to the Cloud StorageSettingspage.
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&access_id){StatusOr<gcs::HmacKeyMetadata>updated=client.UpdateHmacKey(access_id,gcs::HmacKeyMetadata().set_state(gcs::HmacKeyMetadata::state_inactive()));if(!updated)throwstd::move(updated).status();if(updated->state()!=gcs::HmacKeyMetadata::state_inactive()){throwstd::runtime_error("The HMAC key is active, this is unexpected");}std::cout<<"The HMAC key is now inactive\nFull metadata: "<<*updated<<"\n";}
The following sample activates an HMAC key:
namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&access_id){StatusOr<gcs::HmacKeyMetadata>updated=client.UpdateHmacKey(access_id,gcs::HmacKeyMetadata().set_state(gcs::HmacKeyMetadata::state_active()));if(!updated)throwstd::move(updated).status();if(updated->state()!=gcs::HmacKeyMetadata::state_active()){throwstd::runtime_error("The HMAC key is NOT active, this is unexpected");}std::cout<<"The HMAC key is now active\nFull metadata: "<<*updated<<"\n";}
import("context""fmt""io""time""cloud.google.com/go/storage")// deactivateHMACKey deactivates the HMAC key with the given access ID.funcdeactivateHMACKey(wio.Writer,accessIDstring,projectIDstring)(*storage.HMACKey,error){ctx:=context.Background()// Initialize client.client,err:=storage.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()// Closing the client safely cleans up background resources.ctx,cancel:=context.WithTimeout(ctx,time.Minute)defercancel()handle:=client.HMACKeyHandle(projectID,accessID)key,err:=handle.Update(ctx,storage.HMACKeyAttrsToUpdate{State:"INACTIVE"})iferr!=nil{returnnil,fmt.Errorf("Update: %w",err)}fmt.Fprintln(w,"The HMAC key metadata is:")fmt.Fprintf(w,"%+v",key)returnkey,nil}
The following sample activates an HMAC key:
import("context""fmt""io""time""cloud.google.com/go/storage")// activateHMACKey activates the HMAC key with the given access ID.funcactivateHMACKey(wio.Writer,accessIDstring,projectIDstring)(*storage.HMACKey,error){ctx:=context.Background()// Initialize client.client,err:=storage.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()// Closing the client safely cleans up background resources.handle:=client.HMACKeyHandle(projectID,accessID)ctx,cancel:=context.WithTimeout(ctx,time.Minute)defercancel()key,err:=handle.Update(ctx,storage.HMACKeyAttrsToUpdate{State:"ACTIVE"})iferr!=nil{returnnil,fmt.Errorf("Update: %w",err)}fmt.Fprintln(w,"The HMAC key metadata is:")fmt.Fprintf(w,"%+v",key)returnkey,nil}
importcom.google.cloud.storage.HmacKey;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;importjava.util.Date;publicclassDeactivateHmacKey{publicstaticvoiddeactivateHmacKey(StringaccessId,StringprojectId)throwsStorageException{// 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";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();HmacKey.HmacKeyMetadatametadata=storage.getHmacKey(accessId,Storage.GetHmacKeyOption.projectId(projectId));HmacKey.HmacKeyMetadatanewMetadata=storage.updateHmacKeyState(metadata,HmacKey.HmacKeyState.INACTIVE);System.out.println("The HMAC key is now inactive.");System.out.println("The HMAC key metadata is:");System.out.println("ID: "+newMetadata.getId());System.out.println("Access ID: "+newMetadata.getAccessId());System.out.println("Project ID: "+newMetadata.getProjectId());System.out.println("Service Account Email: "+newMetadata.getServiceAccount().getEmail());System.out.println("State: "+newMetadata.getState().toString());System.out.println("Time Created: "+newDate(newMetadata.getCreateTime()).toString());System.out.println("Time Updated: "+newDate(newMetadata.getUpdateTime()).toString());System.out.println("ETag: "+newMetadata.getEtag());}}
The following sample activates an HMAC key:
importcom.google.cloud.storage.HmacKey;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;importjava.util.Date;publicclassActivateHmacKey{publicstaticvoidactivateHmacKey(StringaccessId,StringprojectId)throwsStorageException{// 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";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();HmacKey.HmacKeyMetadatametadata=storage.getHmacKey(accessId,Storage.GetHmacKeyOption.projectId(projectId));HmacKey.HmacKeyMetadatanewMetadata=storage.updateHmacKeyState(metadata,HmacKey.HmacKeyState.ACTIVE);System.out.println("The HMAC key is now active.");System.out.println("The HMAC key metadata is:");System.out.println("ID: "+newMetadata.getId());System.out.println("Access ID: "+newMetadata.getAccessId());System.out.println("Project ID: "+newMetadata.getProjectId());System.out.println("Service Account Email: "+newMetadata.getServiceAccount().getEmail());System.out.println("State: "+newMetadata.getState().toString());System.out.println("Time Created: "+newDate(newMetadata.getCreateTime()).toString());System.out.println("Time Updated: "+newDate(newMetadata.getUpdateTime()).toString());System.out.println("ETag: "+newMetadata.getEtag());}}
/*** 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();// Deactivate HMAC SA KeyasyncfunctiondeactivateHmacKey(){consthmacKey=storage.hmacKey(hmacKeyAccessId,{projectId});const[hmacKeyMetadata]=awaithmacKey.setMetadata({state:'INACTIVE'});console.log('The HMAC key is now inactive.');console.log('The HMAC key metadata is:');for(const[key,value]ofObject.entries(hmacKeyMetadata)){console.log(`${key}:${value}`);}}
The following sample activates an HMAC key:
/*** 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();// Activate HMAC SA KeyasyncfunctionactivateHmacKey(){consthmacKey=storage.hmacKey(hmacKeyAccessId,{projectId});const[hmacKeyMetadata]=awaithmacKey.setMetadata({state:'ACTIVE'});console.log('The HMAC key is now active.');console.log('The HMAC key metadata is:');for(const[key,value]ofObject.entries(hmacKeyMetadata)){console.log(`${key}:${value}`);}}
use Google\Cloud\Storage\StorageClient;/*** Deactivate 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 inactive HMAC key.* (e.g. 'GOOG0234230X00')*/function deactivate_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->update('INACTIVE');print('The HMAC key is now inactive.' . PHP_EOL);printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKey->info(), true));}
The following sample activates an HMAC key:
use Google\Cloud\Storage\StorageClient;/*** Activate 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 inactive HMAC key.* (e.g. 'GOOG0234230X00')*/function activate_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->update('ACTIVE');print('The HMAC key is now active.' . PHP_EOL);printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKey->info(), true));}
fromgoogle.cloudimportstoragedefdeactivate_key(access_id,project_id):"""Deactivate the HMAC key with the given access ID."""# project_id = "Your Google Cloud project ID"# access_id = "ID of an active HMAC key"storage_client=storage.Client(project=project_id)hmac_key=storage_client.get_hmac_key_metadata(access_id,project_id=project_id)hmac_key.state="INACTIVE"hmac_key.update()print("The HMAC key is now inactive.")print("The HMAC key metadata is:")print(f"Service Account Email:{hmac_key.service_account_email}")print(f"Key ID:{hmac_key.id}")print(f"Access ID:{hmac_key.access_id}")print(f"Project ID:{hmac_key.project}")print(f"State:{hmac_key.state}")print(f"Created At:{hmac_key.time_created}")print(f"Updated At:{hmac_key.updated}")print(f"Etag:{hmac_key.etag}")returnhmac_key
The following sample activates an HMAC key:
fromgoogle.cloudimportstoragedefactivate_key(access_id,project_id):"""Activate the HMAC key with the given access ID."""# project_id = "Your Google Cloud project ID"# access_id = "ID of an inactive HMAC key"storage_client=storage.Client(project=project_id)hmac_key=storage_client.get_hmac_key_metadata(access_id,project_id=project_id)hmac_key.state="ACTIVE"hmac_key.update()print("The HMAC key metadata is:")print(f"Service Account Email:{hmac_key.service_account_email}")print(f"Key ID:{hmac_key.id}")print(f"Access ID:{hmac_key.access_id}")print(f"Project ID:{hmac_key.project}")print(f"State:{hmac_key.state}")print(f"Created At:{hmac_key.time_created}")print(f"Updated At:{hmac_key.updated}")print(f"Etag:{hmac_key.etag}")returnhmac_key
defdeactivate_hmac_keyaccess_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_idhmac_key=storage.hmac_keyaccess_idhmac_key.inactive!puts"The HMAC key is now inactive."puts"The HMAC key metadata is:"puts"Key ID:#{hmac_key.id}"puts"Service Account Email:#{hmac_key.service_account_email}"puts"Access ID:#{hmac_key.access_id}"puts"Project ID:#{hmac_key.project_id}"puts"Active:#{hmac_key.active?}"puts"Created At:#{hmac_key.created_at}"puts"Updated At:#{hmac_key.updated_at}"puts"Etag:#{hmac_key.etag}"end
The following sample activates an HMAC key:
defactivate_hmac_keyaccess_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_idhmac_key=storage.hmac_keyaccess_idhmac_key.active!puts"The HMAC key is now active."puts"The HMAC key metadata is:"puts"Key ID:#{hmac_key.id}"puts"Service Account Email:#{hmac_key.service_account_email}"puts"Access ID:#{hmac_key.access_id}"puts"Project ID:#{hmac_key.project_id}"puts"Active:#{hmac_key.active?}"puts"Created At:#{hmac_key.created_at}"puts"Updated At:#{hmac_key.updated_at}"puts"Etag:#{hmac_key.etag}"end
ACCESS_KEY_IDis the access ID associated
with the key you are updating.
STATUSis the desiredstatusfor the
key. For example,Inactive.
When you change the state of an HMAC key, it takes up to 3 minutes for the
state change to propagate through the Cloud Storage system. For this
reason, you should wait at least 3 minutes between making an HMAC key inactive
and deleting the key.
Delete an HMAC key
An HMAC key must be in an inactive state in order to delete it.
To delete an inactive HMAC key:
Console
In the Google Cloud console, go to the Cloud StorageSettingspage.
namespacegcs=::google::cloud::storage;[](gcs::Clientclient,std::stringconst&access_id){google::cloud::Statusstatus=client.DeleteHmacKey(access_id);if(!status.ok())throwstd::runtime_error(status.message());std::cout<<"The key is deleted, though it may still appear"<<" in ListHmacKeys() results.\n";}
usingGoogle.Cloud.Storage.V1;usingSystem;publicclassDeleteHmacKeySample{publicvoidDeleteHmacKey(stringprojectId="your-project-id",stringaccessId="your-access-id"){varstorage=StorageClient.Create();storage.DeleteHmacKey(projectId,accessId);Console.WriteLine($"Key {accessId} was deleted.");}}
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.funcdeleteHMACKey(wio.Writer,accessIDstring,projectIDstring)error{ctx:=context.Background()// Initialize client.client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()// Closing the client safely cleans up background resources.handle:=client.HMACKeyHandle(projectID,accessID)ctx,cancel:=context.WithTimeout(ctx,time.Minute)defercancel()iferr=handle.Delete(ctx);err!=nil{returnfmt.Errorf("Delete: %w",err)}fmt.Fprintln(w,"The key is deleted, though it may still appear in ListHMACKeys results.")returnnil}
importcom.google.cloud.storage.HmacKey;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassDeleteHmacKey{publicstaticvoiddeleteHmacKey(StringaccessId,StringprojectId)throwsStorageException{// 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";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();HmacKey.HmacKeyMetadatametadata=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.");}}
/*** 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();// Delete HMAC SA KeyasyncfunctiondeleteHmacKey(){consthmacKey=storage.hmacKey(hmacKeyAccessId,{projectId});awaithmacKey.delete();console.log('The key is deleted, though it may still appear in getHmacKeys() results.');}
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);}
fromgoogle.cloudimportstoragedefdelete_key(access_id,project_id):"""Delete the HMAC key with the given access ID. Key must have state INACTIVEin 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.")
defdelete_hmac_keyaccess_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_idhmac_key=storage.hmac_keyaccess_idhmac_key.delete!puts"The key is deleted, though it may still appear in Client#hmac_keys results."end
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[],[],null,[]]