These predefined roles contain
the permissions required to rotate keys. To see the exact permissions that are
required, expand the Required permissions section:
Required permissions
The following permissions are required to rotate keys:
A single user with a custom role containing all of these permissions can
rotate keys and re-encrypt data on their own. Users in the Cloud KMS Admin role
and Cloud KMS CryptoKey Encrypter/Decrypter role can work together to rotate
keys and re-encrypt data. Follow the principle of
least privilege when assigning
roles. For more details, see
Permissions and roles.
When you rotate a key, data that was encrypted with previous key versions isn't
automatically re-encrypted. To learn more, see decrypt and
re-encrypt. Rotating a key does not automatically
disable or destroy any
existing key versions. Destroying key versions that are no longer needed helps
to reduce costs.
Configure automatic rotation
Create a new key with a custom rotation schedule
To configure automatic rotation when creating a new key:
Console
When you use the Google Cloud console to create a key, Cloud KMS sets the
rotation period and next rotation time automatically. You can choose to use
the default values or specify different values.
To specify a different rotation period and starting time, when you're creating
your key, but before you click
the Create button:
For Key rotation period, select an option.
For Starting on, select the date when you want the first automatic
rotation to happen. You can leave Starting on at its default value to
start the first automatic rotation one key rotation period from when you
create the key.
KEY_RING: the name of the key ring that contains the key.
LOCATION: the Cloud KMS location of the key ring.
ROTATION_PERIOD: the interval to
rotate the key—for example, 30d to rotate the key every 30 days. The rotation
period must be at least 1 day and at most 100 years. For more information, see
CryptoKey.rotationPeriod.
NEXT_ROTATION_TIME: the timestamp at which to complete the first
rotation—for example, 2023-01-01T01:02:03. You can omit
--next-rotation-time to schedule the first rotation for one rotation
period from when you run the command. For more information, see
CryptoKey.nextRotationTime.
For information on all flags and possible values, run the command with the
--help flag.
import("context""fmt""io""time"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/timestamppb")// createKeyRotationSchedule creates a key with a rotation schedule.funccreateKeyRotationSchedule(wio.Writer,parent,idstring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring"// id := "my-key-with-rotation-schedule"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Build the request.req:=&kmspb.CreateCryptoKeyRequest{Parent:parent,CryptoKeyId:id,CryptoKey:&kmspb.CryptoKey{Purpose:kmspb.CryptoKey_ENCRYPT_DECRYPT,VersionTemplate:&kmspb.CryptoKeyVersionTemplate{Algorithm:kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,},// Rotate the key every 30 daysRotationSchedule:&kmspb.CryptoKey_RotationPeriod{RotationPeriod:&durationpb.Duration{Seconds:int64(60*60*24*30),// 30 days},},// Start the first rotation in 24 hoursNextRotationTime:×tamppb.Timestamp{Seconds:time.Now().Add(24*time.Hour).Unix(),},},}// Call the API.result,err:=client.CreateCryptoKey(ctx,req)iferr!=nil{returnfmt.Errorf("failed to create key: %w",err)}fmt.Fprintf(w,"Created key: %s\n",result.Name)returnnil}
importcom.google.cloud.kms.v1.CryptoKey;importcom.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;importcom.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;importcom.google.cloud.kms.v1.CryptoKeyVersionTemplate;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.cloud.kms.v1.KeyRingName;importcom.google.protobuf.Duration;importcom.google.protobuf.Timestamp;importjava.io.IOException;importjava.time.temporal.ChronoUnit;publicclassCreateKeyRotationSchedule{publicvoidcreateKeyRotationSchedule()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";Stringid="my-key";createKeyRotationSchedule(projectId,locationId,keyRingId,id);}// Create a new key that automatically rotates on a schedule.publicvoidcreateKeyRotationSchedule(StringprojectId,StringlocationId,StringkeyRingId,Stringid)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the parent name from the project, location, and key ring.KeyRingNamekeyRingName=KeyRingName.of(projectId,locationId,keyRingId);// Calculate the date 24 hours from now (this is used below).longtomorrow=java.time.Instant.now().plus(24,ChronoUnit.HOURS).getEpochSecond();// Build the key to create with a rotation schedule.CryptoKeykey=CryptoKey.newBuilder().setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT).setVersionTemplate(CryptoKeyVersionTemplate.newBuilder().setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))// Rotate every 30 days..setRotationPeriod(Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))// Start the first rotation in 24 hours..setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow)).build();// Create the key.CryptoKeycreatedKey=client.createCryptoKey(keyRingName,id,key);System.out.printf("Created key with rotation schedule %s%n",createdKey.getName());}}}
//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const id = 'my-rotating-encryption-key';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the parent key ring nameconstkeyRingName=client.keyRingPath(projectId,locationId,keyRingId);asyncfunctioncreateKeyRotationSchedule(){const[key]=awaitclient.createCryptoKey({parent:keyRingName,cryptoKeyId:id,cryptoKey:{purpose:'ENCRYPT_DECRYPT',versionTemplate:{algorithm:'GOOGLE_SYMMETRIC_ENCRYPTION',},// Rotate the key every 30 days.rotationPeriod:{seconds:60*60*24*30,},// Start the first rotation in 24 hours.nextRotationTime:{seconds:newDate().getTime()/1000+60*60*24,},},});console.log(`Created rotating key: ${key.name}`);returnkey;}returncreateKeyRotationSchedule();
importtimefromgoogle.cloudimportkmsdefcreate_key_rotation_schedule(project_id:str,location_id:str,key_ring_id:str,key_id:str)-> kms.CryptoKey:""" Creates a new key in Cloud KMS that automatically rotates. Args: project_id (string): Google Cloud project ID (e.g. 'my-project'). location_id (string): Cloud KMS location (e.g. 'us-east1'). key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring'). key_id (string): ID of the key to create (e.g. 'my-rotating-key'). Returns: CryptoKey: Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the parent key ring name.key_ring_name=client.key_ring_path(project_id,location_id,key_ring_id)# Build the key.purpose=kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPTalgorithm=(kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION)key={"purpose":purpose,"version_template":{"algorithm":algorithm,},# Rotate the key every 30 days."rotation_period":{"seconds":60*60*24*30},# Start the first rotation in 24 hours."next_rotation_time":{"seconds":int(time.time())+60*60*24},}# Call the API.created_key=client.create_crypto_key(request={"parent":key_ring_name,"crypto_key_id":key_id,"crypto_key":key})print(f"Created labeled key: {created_key.name}")returncreated_key
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# id = "my-key-with-rotation"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key ring name.key_ring_name=client.key_ring_pathproject:project_id,location:location_id,key_ring:key_ring_id# Build the key.key={purpose::ENCRYPT_DECRYPT,version_template:{algorithm::GOOGLE_SYMMETRIC_ENCRYPTION},# Rotate the key every 30 days.rotation_period:{seconds:60*60*24*30},# Start the first rotation in 24 hours.next_rotation_time:{seconds:(Time.now+(60*60*24)).to_i}}# Call the API.created_key=client.create_crypto_keyparent:key_ring_name,crypto_key_id:id,crypto_key:keyputs"Created rotating key: #{created_key.name}"
API
These examples use curl as an HTTP client
to demonstrate using the API. For more information about access control, see
Accessing the Cloud KMS API.
ROTATION_PERIOD: the interval to
rotate the key—for example, 30d to rotate the key every 30 days. The rotation
period must be at least 1 day and at most 100 years. For more information, see
CryptoKey.rotationPeriod.
NEXT_ROTATION_TIME: the timestamp at which to complete the first
rotation—for example, 2023-01-01T01:02:03. For more information, see
CryptoKey.nextRotationTime.
Update an existing key to add a rotation schedule
To configure automatic rotation on an existing key:
Console
Go to the Key Management page in the Google Cloud console.
KEY_RING: the name of the key ring that contains the key.
LOCATION: the Cloud KMS location of the key ring.
ROTATION_PERIOD: the interval to
rotate the key—for example, 30d to rotate the key every 30 days. The rotation
period must be at least 1 day and at most 100 years. For more information, see
CryptoKey.rotationPeriod.
NEXT_ROTATION_TIME: the timestamp at which to complete the next
rotation—for example, 2023-01-01T01:02:03. You can omit
--next-rotation-time to schedule the next rotation for one rotation
period from when you run the command. For more information, see
CryptoKey.nextRotationTime.
For information on all flags and possible values, run the command with the
--help flag.
usingGoogle.Cloud.Kms.V1;usingGoogle.Protobuf.WellKnownTypes;usingSystem;publicclassUpdateKeyAddRotationSample{publicCryptoKeyUpdateKeyAddRotation(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the key.CryptoKeykey=newCryptoKey{// Provide the name of the key to update.CryptoKeyName=newCryptoKeyName(projectId,locationId,keyRingId,keyId),// Rotate the key every 30 days.RotationPeriod=newDuration{Seconds=60*60*24*30,// 30 days},// Start the first rotation in 24 hours.NextRotationTime=newTimestamp{Seconds=newDateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),}};// Build the update mask.FieldMaskfieldMask=newFieldMask{Paths={"rotation_period","next_rotation_time"},};// Call the API.CryptoKeyresult=client.UpdateCryptoKey(key,fieldMask);// Return the updated key.returnresult;}}
import("context""fmt""io""time"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb"fieldmask"google.golang.org/genproto/protobuf/field_mask""google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/timestamppb")// addRotationSchedule updates a key to add a rotation schedule. If the key// already has a rotation schedule, it is overwritten.funcaddRotationSchedule(wio.Writer,namestring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Build the request.req:=&kmspb.UpdateCryptoKeyRequest{CryptoKey:&kmspb.CryptoKey{// Provide the name of the key to updateName:name,// Rotate the key every 30 daysRotationSchedule:&kmspb.CryptoKey_RotationPeriod{RotationPeriod:&durationpb.Duration{Seconds:int64(60*60*24*30),// 30 days},},// Start the first rotation in 24 hoursNextRotationTime:×tamppb.Timestamp{Seconds:time.Now().Add(24*time.Hour).Unix(),},},UpdateMask:&fieldmask.FieldMask{Paths:[]string{"rotation_period","next_rotation_time"},},}// Call the API.result,err:=client.UpdateCryptoKey(ctx,req)iferr!=nil{returnfmt.Errorf("failed to update key: %w",err)}fmt.Fprintf(w,"Updated key: %s\n",result.Name)returnnil}
importcom.google.cloud.kms.v1.CryptoKey;importcom.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;importcom.google.cloud.kms.v1.CryptoKeyVersionTemplate;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.protobuf.Duration;importcom.google.protobuf.FieldMask;importcom.google.protobuf.Timestamp;importcom.google.protobuf.util.FieldMaskUtil;importjava.io.IOException;importjava.time.temporal.ChronoUnit;publicclassUpdateKeyAddRotation{publicvoidupdateKeyAddRotation()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";updateKeyAddRotation(projectId,locationId,keyRingId,keyId);}// Update a key to add or change a rotation schedule.publicvoidupdateKeyAddRotation(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the name from the project, location, and key ring.CryptoKeyNamecryptoKeyName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// Calculate the date 24 hours from now (this is used below).longtomorrow=java.time.Instant.now().plus(24,ChronoUnit.HOURS).getEpochSecond();// Build the key to update with a rotation schedule.CryptoKeykey=CryptoKey.newBuilder().setName(cryptoKeyName.toString()).setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT).setVersionTemplate(CryptoKeyVersionTemplate.newBuilder().setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))// Rotate every 30 days..setRotationPeriod(Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))// Start the first rotation in 24 hours..setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow)).build();// Construct the field mask.FieldMaskfieldMask=FieldMaskUtil.fromString("rotation_period,next_rotation_time");// Update the key.CryptoKeyupdatedKey=client.updateCryptoKey(key,fieldMask);System.out.printf("Updated key %s%n",updatedKey.getName());}}}
importtimefromgoogle.cloudimportkmsdefupdate_key_add_rotation(project_id:str,location_id:str,key_ring_id:str,key_id:str)-> kms.CryptoKey:""" Add a rotation schedule to an existing key. Args: project_id (string): Google Cloud project ID (e.g. 'my-project'). location_id (string): Cloud KMS location (e.g. 'us-east1'). key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring'). key_id (string): ID of the key to use (e.g. 'my-key'). Returns: CryptoKey: Updated Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the key name.key_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)key={"name":key_name,"rotation_period":{"seconds":60*60*24*30# Rotate the key every 30 days.},"next_rotation_time":{"seconds":int(time.time())+60*60*24# Start the first rotation in 24 hours.},}# Build the update mask.update_mask={"paths":["rotation_period","next_rotation_time"]}# Call the API.updated_key=client.update_crypto_key(request={"crypto_key":key,"update_mask":update_mask})print(f"Updated key: {updated_key.name}")returnupdated_key
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# key_id = "my-key"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key name.key_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# Build the key.key={name:key_name,# Rotate the key every 30 days.rotation_period:{seconds:60*60*24*30},# Start the first rotation in 24 hours.next_rotation_time:{seconds:(Time.now+(60*60*24)).to_i}}# Build the field mask.update_mask={paths:["rotation_period","next_rotation_time"]}# Call the API.updated_key=client.update_crypto_keycrypto_key:key,update_mask:update_maskputs"Updated key: #{updated_key.name}"
API
These examples use curl as an HTTP client
to demonstrate using the API. For more information about access control, see
Accessing the Cloud KMS API.
ROTATION_PERIOD: the interval to
rotate the key—for example, 30d to rotate the key every 30 days. The rotation
period must be at least 1 day and at most 100 years. For more information, see
CryptoKey.rotationPeriod.
NEXT_ROTATION_TIME: the timestamp at which to complete the next
rotation—for example, 2023-01-01T01:02:03. For more information, see
CryptoKey.nextRotationTime.
Manually rotate a key
First, create a new key version:
Console
Go to the Key Management page in the Google Cloud console.
import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb")// createKeyVersion creates a new key version for the given key.funccreateKeyVersion(wio.Writer,parentstring)error{// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Build the request.req:=&kmspb.CreateCryptoKeyVersionRequest{Parent:parent,}// Call the API.result,err:=client.CreateCryptoKeyVersion(ctx,req)iferr!=nil{returnfmt.Errorf("failed to create key version: %w",err)}fmt.Fprintf(w,"Created key version: %s\n",result.Name)returnnil}
importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.CryptoKeyVersion;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importjava.io.IOException;publicclassCreateKeyVersion{publicvoidcreateKeyVersion()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";createKeyVersion(projectId,locationId,keyRingId,keyId);}// Create a new key version.publicvoidcreateKeyVersion(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the parent name from the project, location, and key ring.CryptoKeyNamecryptoKeyName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// Build the key version to create.CryptoKeyVersionkeyVersion=CryptoKeyVersion.newBuilder().build();// Create the key.CryptoKeyVersioncreatedVersion=client.createCryptoKeyVersion(cryptoKeyName,keyVersion);System.out.printf("Created key version %s%n",createdVersion.getName());}}}
fromgoogle.cloudimportkmsdefcreate_key_version(project_id:str,location_id:str,key_ring_id:str,key_id:str)-> kms.CryptoKey:""" Creates a new version of the given key. Args: project_id (string): Google Cloud project ID (e.g. 'my-project'). location_id (string): Cloud KMS location (e.g. 'us-east1'). key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring'). key_id (string): ID of the key for which to create a new version (e.g. 'my-key'). Returns: CryptoKeyVersion: Cloud KMS key version. """# Create the client.client=kms.KeyManagementServiceClient()# Build the parent key name.key_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)# Build the key version.version={}# Call the API.created_version=client.create_crypto_key_version(request={"parent":key_name,"crypto_key_version":version})print(f"Created key version: {created_version.name}")returncreated_version
If necessary, re-encrypt data that was encrypted
using the previous key version.
Set an existing version as the primary key version
To set different key version as the primary version for a key, update
the key with the new primary version information. A key version must be enabled
before you can configure it as the primary version.
Console
Go to the Key Management page in the Google Cloud console.
import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb")// updateKeySetPrimary updates the primary key version on a Cloud KMS key.funcupdateKeySetPrimary(wio.Writer,name,versionstring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// version := "123"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Build the request.req:=&kmspb.UpdateCryptoKeyPrimaryVersionRequest{Name:name,CryptoKeyVersionId:version,}// Call the API.result,err:=client.UpdateCryptoKeyPrimaryVersion(ctx,req)iferr!=nil{returnfmt.Errorf("failed to update key: %w",err)}fmt.Fprintf(w,"Updated key primary: %s\n",result.Name)returnnil}
importcom.google.cloud.kms.v1.CryptoKey;importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importjava.io.IOException;publicclassUpdateKeySetPrimary{publicvoidupdateKeySetPrimary()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";StringkeyVersionId="123";updateKeySetPrimary(projectId,locationId,keyRingId,keyId,keyVersionId);}// Update a key's primary version.publicvoidupdateKeySetPrimary(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,StringkeyVersionId)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the name from the project, location, key ring, and keyId.CryptoKeyNamecryptoKeyName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// Create the key.CryptoKeycreatedKey=client.updateCryptoKeyPrimaryVersion(cryptoKeyName,keyVersionId);System.out.printf("Updated key primary version %s%n",createdKey.getName());}}}
fromgoogle.cloudimportkmsdefupdate_key_set_primary(project_id:str,location_id:str,key_ring_id:str,key_id:str,version_id:str)-> kms.CryptoKey:""" Update the primary version of a key. Args: project_id (string): Google Cloud project ID (e.g. 'my-project'). location_id (string): Cloud KMS location (e.g. 'us-east1'). key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring'). key_id (string): ID of the key to use (e.g. 'my-key'). version_id (string): ID of the key to make primary (e.g. '2'). Returns: CryptoKey: Updated Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the key name.key_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)# Call the API.updated_key=client.update_crypto_key_primary_version(request={"name":key_name,"crypto_key_version_id":version_id})print(f"Updated {updated_key.name} primary to {version_id}")returnupdated_key
API
These examples use curl as an HTTP client
to demonstrate using the API. For more information about access control, see
Accessing the Cloud KMS API.
PROJECT_ID: the ID of the project that contains the key ring.
LOCATION: the Cloud KMS location of the key ring.
KEY_RING: the name of the key ring that contains the key.
KEY_NAME: the name of the key.
KEY_VERSION: the version number of the new primary key version.
When you change the primary key version, the change typically becomes consistent
within 1 minute. However, this change can take up to 3 hours to propagate in
exceptional cases. During this time, the prior primary version might be used to
encrypt data. For more information, see
Cloud KMS resource consistency.
Disable automatic rotation
To disable automatic rotation on a key, clear the rotation schedule of the key:
Console
Go to the Key Management page in the Google Cloud console.
import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb"fieldmask"google.golang.org/genproto/protobuf/field_mask")// removeRotationSchedule updates a key to remove a rotation schedule, if one// exists.funcremoveRotationSchedule(wio.Writer,namestring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Build the request.req:=&kmspb.UpdateCryptoKeyRequest{CryptoKey:&kmspb.CryptoKey{// Provide the name of the key to updateName:name,// Remove any rotation fields.RotationSchedule:nil,NextRotationTime:nil,},UpdateMask:&fieldmask.FieldMask{Paths:[]string{"rotation_period","next_rotation_time"},},}// Call the API.result,err:=client.UpdateCryptoKey(ctx,req)iferr!=nil{returnfmt.Errorf("failed to update key: %w",err)}fmt.Fprintf(w,"Updated key: %s\n",result.Name)returnnil}
importcom.google.cloud.kms.v1.CryptoKey;importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.protobuf.FieldMask;importcom.google.protobuf.util.FieldMaskUtil;importjava.io.IOException;publicclassUpdateKeyRemoveRotation{publicvoidupdateKeyRemoveRotation()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";updateKeyRemoveRotation(projectId,locationId,keyRingId,keyId);}// Update a key to remove all labels.publicvoidupdateKeyRemoveRotation(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the name from the project, location, key ring, and keyId.CryptoKeyNamecryptoKeyName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// Build an empty key with no labels.CryptoKeykey=CryptoKey.newBuilder().setName(cryptoKeyName.toString()).clearRotationPeriod().clearNextRotationTime().build();// Construct the field mask.FieldMaskfieldMask=FieldMaskUtil.fromString("rotation_period,next_rotation_time");// Create the key.CryptoKeycreatedKey=client.updateCryptoKey(key,fieldMask);System.out.printf("Updated key %s%n",createdKey.getName());}}}
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# key_id = "my-key"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key name.key_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# Build the key.key={name:key_name,rotation_period:nil,next_rotation_time:nil}# Build the field mask.update_mask={paths:["rotation_period","next_rotation_time"]}# Call the API.updated_key=client.update_crypto_keycrypto_key:key,update_mask:update_maskputs"Updated key: #{updated_key.name}"
fromgoogle.cloudimportkmsdefupdate_key_remove_rotation(project_id:str,location_id:str,key_ring_id:str,key_id:str)-> kms.CryptoKey:""" Remove a rotation schedule from an existing key. Args: project_id (string): Google Cloud project ID (e.g. 'my-project'). location_id (string): Cloud KMS location (e.g. 'us-east1'). key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring'). key_id (string): ID of the key to use (e.g. 'my-key'). Returns: CryptoKey: Updated Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the key name.key_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)key={"name":key_name}# Build the update mask.update_mask={"paths":["rotation_period","next_rotation_time"]}# Call the API.updated_key=client.update_crypto_key(request={"crypto_key":key,"update_mask":update_mask})print(f"Updated key: {updated_key.name}")returnupdated_key
API
These examples use curl as an HTTP client
to demonstrate using the API. For more information about access control, see
Accessing the Cloud KMS API.
For additional details about rotationPeriod and nextRotationTime, see
keyRings.cryptoKeys.
Rotate an external key
Rotate a coordinated external key
You can configure automatic rotation for symmetric coordinated
external keys. You can also manually create a new key version for symmetric or
asymmetric coordinated external keys.
Rotating or creating a new key version causes all newly created data protected
with that key to be encrypted with the new key version. Data protected with
a previous key version isn't re-encrypted. As a result, your external key
manager must continue to make the key material of the previous key version
available to be used.
To create a new key version for a coordinated external key, complete the following steps:
First, rotate the external key material on your external key manager. If that
results in a new key path, you need to rotate or create a new Cloud EKM
key version with the new key path. For symmetric encryption keys, rotate the
Cloud EKM key and specify the new key path from your external key
manager. For asymmetric keys, create a new key version and specify the new key
path.
Rotating or creating a new key version causes all newly created data protected
with that key to be encrypted with the new key version. Data protected with
a previous key version isn't re-encrypted. As a result, your external key
manager must continue to make the key material of the previous key version
available to be used.
If the key material in the external key management partner system doesn't change, but the key
path changes, you can update the key's external
path without rotating the key.
Console
In the Google Cloud console, go to the
Key Management page.
KEY_RING: the name of the key ring that contains the key.
LOCATION: the Cloud KMS location of the key ring.
EXTERNAL_KEY_PATH: the path to the new external
key version.
To create a new asymmetric key version or to create a new symmetric key
version that isn't the primary key version, use the kms keys versions
create command:
KEY_RING: the name of the key ring that contains the key.
LOCATION: the Cloud KMS location of the key ring.
EXTERNAL_KEY_PATH: the path to the new external
key version.
For information on all flags and possible values, run the command with the
--help flag.
After the key version is successfully created, you can use it just as you would
use any other Cloud KMS key version.
Rotate a manually managed Cloud EKM via internet key
First, rotate the external key material on your external key manager. If that
results in a new URI, you need to rotate or create a new Cloud EKM key
version with the new URI. For symmetric encryption keys, rotate the
Cloud EKM key and specify the new key URI from your external key
manager. For asymmetric keys, create a new key version and specify the new key
URI.
Rotating or creating a new key version causes all newly created data protected
with that key to be encrypted with the new key version. Data protected with
a previous key version isn't re-encrypted. As a result, your external key
manager must continue to make the key material of the previous key version
available to be used.
If the key material in the external key management partner system doesn't change, but the URI
changes, you can update the key's external
URI without rotating the key.
[[["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 2026-06-09 UTC."],[],[]]