Access control with IAM

This topic shows how to manage access to Cloud KMS resources.

Overview

To manage access to Cloud KMS resources, such as keys and keyrings, you grantIdentity and Access Management (IAM) roles. You can grant orrestrict the ability to perform specific cryptographic operations, such asrotating a key or encrypting data. You can grant IAM roles on:

  • A key directly
  • A key ring, inherited by all keys in that key ring
  • A Google Cloud project, inherited by all keys in the project
  • A Google Cloud folder, inherited by all keys in all projects in thefolder
  • A Google Cloud organization, inherited by all keys in folders in theorganization

For a complete list of Cloud KMS actions and IAMroles and permissions, seePermissions and roles. For acomplete list of Cloud KMS resources and how they relate to eachother, seeCloud KMS resources.

Before you begin

To complete these tasks, you need permission to administer Cloud KMSresources in the Google Cloud project. The Cloud KMS Admin role(roles/cloudkms.admin) includes the required permissions.

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the required API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the API

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. Toinitialize the gcloud CLI, run the following command:

    gcloudinit
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the required API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the API

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. Toinitialize the gcloud CLI, run the following command:

    gcloudinit
  14. Create a resource, such as a key ring.
  15. Get the resource IDs for theresources created, such as a key ring, key, and key version.

Only IAM principals with Owner (roles/owner) or Cloud KMS Admin(roles/cloudkms.admin) roles can grant or revoke access to Cloud KMSresources.

Granting roles on a resource

The following example grants a role that provides access to a Cloud KMSkey:

gcloud

To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.

gcloud kms keys add-iam-policy-bindingkey \    --keyringkey-ring \    --locationlocation \    --memberprincipal-type:principal-email \    --role roles/role

Replacekey with the name of the key. Replacekey-ringwith the name of the key ring where the key is located. Replacelocation with the Cloud KMS location for the key ring.Replaceprincipal-type andprincipal-email with the typeof principal and the principal's email address. Replacerole with thename of the role to add.

C#

To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.

usingGoogle.Cloud.Iam.V1;usingGoogle.Cloud.Kms.V1;publicclassIamAddMemberSample{publicPolicyIamAddMember(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key",stringmember="user:foo@example.com"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the resource name.CryptoKeyNameresourceName=newCryptoKeyName(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// var resourceName = new KeyRingName(projectId, locationId, keyRingId);// Get the current IAM policy.Policypolicy=client.IAMPolicyClient.GetIamPolicy(newGetIamPolicyRequest{ResourceAsResourceName=resourceName});// Add the member to the policy.policy.AddRoleMember("roles/cloudkms.cryptoKeyEncrypterDecrypter",member);// Save the updated IAM policy.Policyresult=client.IAMPolicyClient.SetIamPolicy(newSetIamPolicyRequest{ResourceAsResourceName=resourceName,Policy=policy});// Return the resulting policy.returnresult;}}

Go

To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.

import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1")// iamAddMember adds a new IAM member to the Cloud KMS keyfunciamAddMember(wio.Writer,name,memberstring)error{// NOTE: The resource name can be either a key or a key ring. If IAM// permissions are granted on the key ring, the permissions apply to all keys// in the key ring.//// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// member := "user:foo@example.com"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Get the current IAM policy.handle:=client.ResourceIAM(name)policy,err:=handle.Policy(ctx)iferr!=nil{returnfmt.Errorf("failed to get IAM policy: %w",err)}// Grant the member permissions. This example grants permission to use the key// to encrypt data.policy.Add(member,"roles/cloudkms.cryptoKeyEncrypterDecrypter")iferr:=handle.SetPolicy(ctx,policy);err!=nil{returnfmt.Errorf("failed to save policy: %w",err)}fmt.Fprintf(w,"Updated IAM policy for %s\n",name)returnnil}

Java

To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.

importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.iam.v1.Binding;importcom.google.iam.v1.Policy;importjava.io.IOException;publicclassIamAddMember{publicvoidiamAddMember()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";Stringmember="user:foo@example.com";iamAddMember(projectId,locationId,keyRingId,keyId,member);}// Add the given IAM member to the key.publicvoidiamAddMember(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,Stringmember)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 key version name from the project, location, key ring, key,// and key version.CryptoKeyNameresourceName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// KeyRingName resourceName = KeyRingName.of(projectId, locationId, keyRingId);// Get the current policy.Policypolicy=client.getIamPolicy(resourceName);// Create a new IAM binding for the member and role.Bindingbinding=Binding.newBuilder().setRole("roles/cloudkms.cryptoKeyEncrypterDecrypter").addMembers(member).build();// Add the binding to the policy.PolicynewPolicy=policy.toBuilder().addBindings(binding).build();client.setIamPolicy(resourceName,newPolicy);System.out.printf("Updated IAM policy for %s%n",resourceName.toString());}}}

Node.js

To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.

//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const keyId = 'my-key';// const member = 'user:foo@example.com';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the resource nameconstresourceName=client.cryptoKeyPath(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);asyncfunctioniamAddMember(){// Get the current IAM policy.const[policy]=awaitclient.getIamPolicy({resource:resourceName,});// Add the member to the policy.policy.bindings.push({role:'roles/cloudkms.cryptoKeyEncrypterDecrypter',members:[member],});// Save the updated policy.const[updatedPolicy]=awaitclient.setIamPolicy({resource:resourceName,policy:policy,});console.log('Updated policy');returnupdatedPolicy;}returniamAddMember();

PHP

To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.

use Google\Cloud\Iam\V1\Binding;use Google\Cloud\Iam\V1\GetIamPolicyRequest;use Google\Cloud\Iam\V1\SetIamPolicyRequest;use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;function iam_add_member(    string $projectId = 'my-project',    string $locationId = 'us-east1',    string $keyRingId = 'my-key-ring',    string $keyId = 'my-key',    string $member = 'user:foo@example.com') {    // Create the Cloud KMS client.    $client = new KeyManagementServiceClient();    // Build the resource name.    $resourceName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);    // The resource name could also be a key ring.    // $resourceName = $client->keyRingName($projectId, $locationId, $keyRingId);    // Get the current IAM policy.    $getIamPolicyRequest = (new GetIamPolicyRequest())        ->setResource($resourceName);    $policy = $client->getIamPolicy($getIamPolicyRequest);    // Add the member to the policy.    $bindings = $policy->getBindings();    $bindings[] = (new Binding())        ->setRole('roles/cloudkms.cryptoKeyEncrypterDecrypter')        ->setMembers([$member]);    $policy->setBindings($bindings);    // Save the updated IAM policy.    $setIamPolicyRequest = (new SetIamPolicyRequest())        ->setResource($resourceName)        ->setPolicy($policy);    $updatedPolicy = $client->setIamPolicy($setIamPolicyRequest);    printf('Added %s' . PHP_EOL, $member);    return $updatedPolicy;}

Python

To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.

fromgoogle.cloudimportkmsfromgoogle.iam.v1importpolicy_pb2asiam_policydefiam_add_member(project_id:str,location_id:str,key_ring_id:str,key_id:str,member:str)->iam_policy.Policy:"""    Add an IAM member to a resource.    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').        member (string): Member to add (e.g. 'user:foo@example.com')    Returns:        Policy: Updated Cloud IAM policy.    """# Create the client.client=kms.KeyManagementServiceClient()# Build the resource name.resource_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)# The resource name could also be a key ring.# resource_name = client.key_ring_path(project_id, location_id, key_ring_id);# Get the current policy.policy=client.get_iam_policy(request={"resource":resource_name})# Add the member to the policy.policy.bindings.add(role="roles/cloudkms.cryptoKeyEncrypterDecrypter",members=[member])# Save the updated IAM policy.request={"resource":resource_name,"policy":policy}updated_policy=client.set_iam_policy(request=request)print(f"Added{member} to{resource_name}")returnupdated_policy

Ruby

To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.

# 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"# member      = "user:foo@example.com"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the resource name.resource_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# The resource name could also be a key ring.# resource_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id# Create the IAM client.iam_client=Google::Cloud::Kms::V1::IAMPolicy::Client.new# Get the current IAM policy.policy=iam_client.get_iam_policyresource:resource_name# Add the member to the policy.policy.bindings <<Google::Iam::V1::Binding.new(members:[member],role:"roles/cloudkms.cryptoKeyEncrypterDecrypter")# Save the updated policy.updated_policy=iam_client.set_iam_policyresource:resource_name,policy:policyputs"Added#{member}"

Revoking access to a resource

To remove a principal's access to a Cloud KMS key:

gcloud

To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.

gcloud kms keys remove-iam-policy-bindingkey \    --keyringkey-ring \    --locationlocation \    --memberprincipal-type:principal-email \    --role roles/role-name

Replacekey with the name of the key. Replacekey-ringwith the name of the key ring where the key is located. Replacelocation with the Cloud KMS location for the key ring.Replaceprincipal-type andprincipal-email with the typeof principal and the principal's email address. Replacerole-namewith the name of the role to remove.

For information on all flags and possible values, run the command with the--help flag.

C#

To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.

usingGoogle.Cloud.Iam.V1;usingGoogle.Cloud.Kms.V1;publicclassIamRemoveMemberSample{publicPolicyIamRemoveMember(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key",stringmember="user:foo@example.com"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the resource name.CryptoKeyNameresourceName=newCryptoKeyName(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// var resourceName = new KeyRingName(projectId, locationId, keyRingId);// Get the current IAM policy.Policypolicy=client.IAMPolicyClient.GetIamPolicy(newGetIamPolicyRequest{ResourceAsResourceName=resourceName});// Add the member to the policy.policy.RemoveRoleMember("roles/cloudkms.cryptoKeyEncrypterDecrypter",member);// Save the updated IAM policy.Policyresult=client.IAMPolicyClient.SetIamPolicy(newSetIamPolicyRequest{ResourceAsResourceName=resourceName,Policy=policy});// Return the resulting policy.returnresult;}}

Go

To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.

import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1")// iamRemoveMember removes the IAM member from the Cloud KMS key, if they exist.funciamRemoveMember(wio.Writer,name,memberstring)error{// NOTE: The resource name can be either a key or a key ring.//// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// member := "user:foo@example.com"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Get the current IAM policy.handle:=client.ResourceIAM(name)policy,err:=handle.Policy(ctx)iferr!=nil{returnfmt.Errorf("failed to get IAM policy: %w",err)}// Grant the member permissions. This example grants permission to use the key// to encrypt data.policy.Remove(member,"roles/cloudkms.cryptoKeyEncrypterDecrypter")iferr:=handle.SetPolicy(ctx,policy);err!=nil{returnfmt.Errorf("failed to save policy: %w",err)}fmt.Fprintf(w,"Updated IAM policy for %s\n",name)returnnil}

Java

To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.

importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.iam.v1.Binding;importcom.google.iam.v1.Policy;importjava.io.IOException;publicclassIamRemoveMember{publicvoidiamRemoveMember()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";Stringmember="user:foo@example.com";iamRemoveMember(projectId,locationId,keyRingId,keyId,member);}// Remove the given IAM membership on the resource, if it exists.publicvoidiamRemoveMember(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,Stringmember)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 key version name from the project, location, key ring, key,// and key version.CryptoKeyNameresourceName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// KeyRingName resourceName = KeyRingName.of(projectId, locationId, keyRingId);// Get the current policy.Policypolicy=client.getIamPolicy(resourceName);// Search through the bindings and remove matches.StringroleToFind="roles/cloudkms.cryptoKeyEncrypterDecrypter";for(Bindingbinding:policy.getBindingsList()){if(binding.getRole().equals(roleToFind) &&binding.getMembersList().contains(member)){binding.getMembersList().remove(member);}}client.setIamPolicy(resourceName,policy);System.out.printf("Updated IAM policy for %s%n",resourceName.toString());}}}

Node.js

To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.

//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const keyId = 'my-key';// const member = 'user:foo@example.com';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the resource nameconstresourceName=client.cryptoKeyPath(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);asyncfunctioniamRemoveMember(){// Get the current IAM policy.const[policy]=awaitclient.getIamPolicy({resource:resourceName,});// Build a new list of policy bindings with the user excluded.for(constiinpolicy.bindings){constbinding=policy.bindings[i];if(binding.role!=='roles/cloudkms.cryptoKeyEncrypterDecrypter'){continue;}constidx=binding.members.indexOf(member);if(idx!==-1){binding.members.splice(idx,1);}}// Save the updated IAM policy.const[updatedPolicy]=awaitclient.setIamPolicy({resource:resourceName,policy:policy,});console.log('Updated policy');returnupdatedPolicy;}returniamRemoveMember();

PHP

To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.

use Google\Cloud\Iam\V1\Binding;use Google\Cloud\Iam\V1\GetIamPolicyRequest;use Google\Cloud\Iam\V1\Policy;use Google\Cloud\Iam\V1\SetIamPolicyRequest;use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;function iam_remove_member(    string $projectId = 'my-project',    string $locationId = 'us-east1',    string $keyRingId = 'my-key-ring',    string $keyId = 'my-key',    string $member = 'user:foo@example.com'): Policy {    // Create the Cloud KMS client.    $client = new KeyManagementServiceClient();    // Build the resource name.    $resourceName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);    // The resource name could also be a key ring.    // $resourceName = $client->keyRingName($projectId, $locationId, $keyRingId);    // Get the current IAM policy.    $getIamPolicyRequest = (new GetIamPolicyRequest())        ->setResource($resourceName);    $policy = $client->getIamPolicy($getIamPolicyRequest);    // Remove the member from the policy by creating a new policy with everyone    // but the member to remove.    $newPolicy = new Policy();    foreach ($policy->getBindings() as $binding) {        if ($binding->getRole() !== 'roles/cloudkms.cryptoKeyEncrypterDecrypter') {            $newPolicy->getBindings()[] = $binding;        } else {            $newBinding = (new Binding())              ->setRole($binding->getRole());            $newMembers = [];            foreach ($binding->getMembers() as $existingMember) {                if ($member !== $existingMember) {                    $newMembers[] = $existingMember;                }            }            $newPolicy->getBindings()[] = (new Binding())              ->setRole($binding->getRole())              ->setMembers($newMembers);        }    }    // Save the updated IAM policy.    $setIamPolicyRequest = (new SetIamPolicyRequest())        ->setResource($resourceName)        ->setPolicy($newPolicy);    $updatedPolicy = $client->setIamPolicy($setIamPolicyRequest);    printf('Removed %s' . PHP_EOL, $member);    return $updatedPolicy;}

Python

To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.

fromgoogle.cloudimportkmsfromgoogle.iam.v1importpolicy_pb2asiam_policydefiam_remove_member(project_id:str,location_id:str,key_ring_id:str,key_id:str,member:str)->iam_policy.Policy:"""    Remove an IAM member from a resource.    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').        member (string): Member to remove (e.g. 'user:foo@example.com')    Returns:        Policy: Updated Cloud IAM policy.    """# Create the client.client=kms.KeyManagementServiceClient()# Build the resource name.resource_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)# The resource name could also be a key ring.# resource_name = client.key_ring_path(project_id, location_id, key_ring_id);# Get the current policy.policy=client.get_iam_policy(request={"resource":resource_name})# Remove the member from the policy.forbindinginpolicy.bindings:ifbinding.role=="roles/cloudkms.cryptoKeyEncrypterDecrypter":ifmemberinbinding.members:binding.members.remove(member)# Save the updated IAM policy.request={"resource":resource_name,"policy":policy}updated_policy=client.set_iam_policy(request=request)print(f"Removed{member} from{resource_name}")returnupdated_policy

Ruby

To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.

# 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"# member      = "user:foo@example.com"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the resource name.resource_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# The resource name could also be a key ring.# resource_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id# Create the IAM client.iam_client=Google::Cloud::Kms::V1::IAMPolicy::Client.new# Get the current IAM policy.policy=iam_client.get_iam_policyresource:resource_name# Remove the member from the current bindingspolicy.bindings.eachdo|bind|ifbind.role=="roles/cloudkms.cryptoKeyEncrypterDecrypter"bind.members.deletememberendend# Save the updated policy.updated_policy=iam_client.set_iam_policyresource:resource_name,policy:policyputs"Removed#{member}"

Viewing permissions on a resource

To view the IAM policy for a Cloud KMS key:

gcloud

To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.

gcloud kms keys get-iam-policykey \    --keyringkey-ring \    --locationlocation

Replacekey with the name of the key. Replacekey-ringwith the name of the key ring where the key is located. Replacelocation with the Cloud KMS location for the key ring.

For information on all flags and possible values, run the command with the--help flag.

C#

To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.

usingGoogle.Cloud.Iam.V1;usingGoogle.Cloud.Kms.V1;usingSystem;publicclassIamGetPolicySample{publicPolicyIamGetPolicy(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the resource name.CryptoKeyNameresourceName=newCryptoKeyName(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// var resourceName = new KeyRingName(projectId, locationId, keyRingId);// Get the current IAM policy.Policypolicy=client.IAMPolicyClient.GetIamPolicy(newGetIamPolicyRequest{ResourceAsResourceName=resourceName});// Print the policy.foreach(Bindingbinpolicy.Bindings){Stringrole=b.Role;foreach(Stringmemberinb.Members){// ...}}// Return the policy.returnpolicy;}}

Go

To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.

import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1")// iamGetPolicy retrieves and prints the Cloud IAM policy associated with the// Cloud KMS key.funciamGetPolicy(wio.Writer,namestring)error{// NOTE: The resource name can be either a key or a key ring.//// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Get the current policy.policy,err:=client.ResourceIAM(name).Policy(ctx)iferr!=nil{returnfmt.Errorf("failed to get IAM policy: %w",err)}// Print the policy members.for_,role:=rangepolicy.Roles(){fmt.Fprintf(w,"%s\n",role)for_,member:=rangepolicy.Members(role){fmt.Fprintf(w,"- %s\n",member)}fmt.Fprintf(w,"\n")}returnnil}

Java

To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.

importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.iam.v1.Binding;importcom.google.iam.v1.Policy;importjava.io.IOException;publicclassIamGetPolicy{publicvoidiamGetPolicy()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";iamGetPolicy(projectId,locationId,keyRingId,keyId);}// Get the IAM policy for the given key.publicvoidiamGetPolicy(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 key version name from the project, location, key ring, key,// and key version.CryptoKeyNameresourceName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// KeyRingName resourceName = KeyRingName.of(projectId, locationId, keyRingId);// Get the current policy.Policypolicy=client.getIamPolicy(resourceName);// Print the policy.System.out.printf("IAM policy:%n");for(Bindingbinding:policy.getBindingsList()){System.out.printf("%s%n",binding.getRole());for(Stringmember:binding.getMembersList()){System.out.printf("- %s%n",member);}}}}}

Node.js

To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.

//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const keyId = 'my-key';// const member = 'user:foo@example.com';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the resource nameconstresourceName=client.cryptoKeyPath(projectId,locationId,keyRingId,keyId);// The resource name could also be a key ring.// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);asyncfunctioniamGetPolicy(){const[policy]=awaitclient.getIamPolicy({resource:resourceName,});for(constbindingofpolicy.bindings){console.log(`Role:${binding.role}`);for(constmemberofbinding.members){console.log(`  -${member}`);}}returnpolicy;}returniamGetPolicy();

PHP

To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.

use Google\Cloud\Iam\V1\GetIamPolicyRequest;use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;function iam_get_policy(    string $projectId = 'my-project',    string $locationId = 'us-east1',    string $keyRingId = 'my-key-ring',    string $keyId = 'my-key') {    // Create the Cloud KMS client.    $client = new KeyManagementServiceClient();    // Build the resource name.    $resourceName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);    // The resource name could also be a key ring.    // $resourceName = $client->keyRingName($projectId, $locationId, $keyRingId);    // Get the current IAM policy.    $getIamPolicyRequest = (new GetIamPolicyRequest())        ->setResource($resourceName);    $policy = $client->getIamPolicy($getIamPolicyRequest);    // Print the policy.    printf('IAM policy for %s' . PHP_EOL, $resourceName);    foreach ($policy->getBindings() as $binding) {        printf('%s' . PHP_EOL, $binding->getRole());        foreach ($binding->getMembers() as $member) {            printf('- %s' . PHP_EOL, $member);        }    }    return $policy;}

Python

To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.

fromgoogle.cloudimportkmsfromgoogle.iam.v1importpolicy_pb2asiam_policydefiam_get_policy(project_id:str,location_id:str,key_ring_id:str,key_id:str)->iam_policy.Policy:"""    Get the IAM policy for a resource.    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:        Policy: Cloud IAM policy.    """# Create the client.client=kms.KeyManagementServiceClient()# Build the resource name.resource_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)# The resource name could also be a key ring.# resource_name = client.key_ring_path(project_id, location_id, key_ring_id);# Get the current policy.policy=client.get_iam_policy(request={"resource":resource_name})# Print the policyprint(f"IAM policy for{resource_name}")forbindinginpolicy.bindings:print(binding.role)formemberinbinding.members:print(f"-{member}")returnpolicy

Ruby

To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.

# 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 resource name.resource_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# The resource name could also be a key ring.# resource_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id# Create the IAM client.iam_client=Google::Cloud::Kms::V1::IAMPolicy::Client.new# Get the current IAM policy.policy=iam_client.get_iam_policyresource:resource_name# Print the policy.puts"Policy for#{resource_name}"policy.bindings.eachdo|bind|putsbind.rolebind.members.eachdo|member|puts"-#{member}"endend

Principle of least privilege

To practice the principle of least privilege, grant the most limited set of permissions to the lowest object in the resource hierarchy.

  • To grant a principal permissions to encrypt (but not decrypt) data, granttheroles/cloudkms.cryptoKeyEncrypter role on the key.

  • To grant a principal permissions to encrypt and decrypt data, grant theroles/cloudkms.cryptoKeyEncrypterDecrypter role on the key.

  • To grant a principal permissions to verify (but not sign) data, grant theroles/cloudkms.publicKeyViewer role on the key.

  • To grant a principal permissions to sign and verify data, grant theroles/cloudkms.signerVerifier role on the key.

  • To grant a principal permissions to manage a key, grant theroles/cloudkms.admin role on the key.

This is not an exhaustive list. SeeCloud KMS permissions and roles for a full list of permissions and roles.

Hierarchy and inheritance

Policy bindings can be specified on the project, key ring, key, import job, andother Cloud KMS resources.

Since keys belong to key rings, and key rings belong to projects, a principalwith a specific role or permission at a higher level in that hierarchy inheritsthe same permissions on the child resources. That is, a user who has the role ofowner on a project is also anowner on all the key rings and keys in thatproject. Similarly, if a user is granted thecloudkms.admin role on a keyring, they have the associated permissions on all the keys in that key ring.

The inverse is not true; that is, a user who has a permission on a key but doesnot have the permission on the parent key ring has no permissions on that keyring.

Note: A user that only has permissions on key rings or keys, but not on theproject itself, will not be able to manage key resources in theGoogle Cloud console. To enable their use of the Google Cloud console, dependingon security requirements, one option might be to also grant that user abrowser role on the project.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-19 UTC.