Access control with IAM  |  Cloud KMS Documentation  |  Google Cloud (2024)

Stay organized with collections Save and categorize content based on your preferences.

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 grant Identity 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, see Cloud 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.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the required API.

    Enable the API

  5. Install the Google Cloud CLI.
  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  8. Make sure that billing is enabled for your Google Cloud project.

  9. Enable the required API.

    Enable the API

  10. Install the Google Cloud CLI.
  11. To initialize the gcloud CLI, run the following command:

    gcloud init
  12. Create a resource, such as a key ring.
  13. 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-binding key \ --keyring key-ring \ --location location \ --member principal-type:principal-email \ --role roles/role

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

C#

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

using Google.Cloud.Iam.V1;using Google.Cloud.Kms.V1;public class IamAddMemberSample{ public Policy IamAddMember( 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 client. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // Build the resource name. CryptoKeyName resourceName = new CryptoKeyName(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. Policy policy = client.IAMPolicyClient.GetIamPolicy( new GetIamPolicyRequest {  ResourceAsResourceName = resourceName }); // Add the member to the policy. policy.AddRoleMember("roles/cloudkms.cryptoKeyEncrypterDecrypter", member); // Save the updated IAM policy. Policy result = client.IAMPolicyClient.SetIamPolicy( new SetIamPolicyRequest { ResourceAsResourceName = resourceName, Policy = policy }); // Return the resulting policy. return result; }}

Go

To run this code, first set 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 keyfunc iamAddMember(w io.Writer, name, member string) 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)if err != nil {return fmt.Errorf("failed to create kms client: %w", err)}defer client.Close()// Get the current IAM policy.handle := client.ResourceIAM(name)policy, err := handle.Policy(ctx)if err != nil {return fmt.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")if err := handle.SetPolicy(ctx, policy); err != nil {return fmt.Errorf("failed to save policy: %w", err)}fmt.Fprintf(w, "Updated IAM policy for %s\n", name)return nil}

Java

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

import com.google.cloud.kms.v1.CryptoKeyName;import com.google.cloud.kms.v1.KeyManagementServiceClient;import com.google.iam.v1.Binding;import com.google.iam.v1.Policy;import java.io.IOException;public class IamAddMember { public void iamAddMember() throws IOException { // TODO(developer): Replace these variables before running the sample. String projectId = "your-project-id"; String locationId = "us-east1"; String keyRingId = "my-key-ring"; String keyId = "my-key"; String member = "user:foo@example.com"; iamAddMember(projectId, locationId, keyRingId, keyId, member); } // Add the given IAM member to the key. public void iamAddMember( String projectId, String locationId, String keyRingId, String keyId, String member) throws IOException { // 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 (KeyManagementServiceClient client = KeyManagementServiceClient.create()) { // Build the key version name from the project, location, key ring, key, // and key version. CryptoKeyName resourceName = 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. Policy policy = client.getIamPolicy(resourceName); // Create a new IAM binding for the member and role. Binding binding = Binding.newBuilder() .setRole("roles/cloudkms.cryptoKeyEncrypterDecrypter") .addMembers(member) .build(); // Add the binding to the policy. Policy newPolicy = 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, first set 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 clientconst client = new KeyManagementServiceClient();// Build the resource nameconst resourceName = client.cryptoKeyPath( projectId, locationId, keyRingId, keyId);// The resource name could also be a key ring.// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);async function iamAddMember() { // Get the current IAM policy. const [policy] = await client.getIamPolicy({ resource: resourceName, }); // Add the member to the policy. policy.bindings.push({ role: 'roles/cloudkms.cryptoKeyEncrypterDecrypter', members: [member], }); // Save the updated policy. const [updatedPolicy] = await client.setIamPolicy({ resource: resourceName, policy: policy, }); console.log('Updated policy'); return updatedPolicy;}return iamAddMember();

PHP

To run this code, first learn about using 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, first set up a Python development environment andinstall the Cloud KMS Python SDK.

from google.cloud import kmsfrom google.iam.v1 import policy_pb2 as iam_policydef iam_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}") return updated_policy

Ruby

To run this code, first set 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_path project: 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_policy resource: 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_policy resource: 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-binding key \ --keyring key-ring \ --location location \ --member principal-type:principal-email \ --role roles/role-name

Replace key with the name of the key. Replace key-ringwith the name of the key ring where the key is located. Replacelocation with the Cloud KMS location for the key ring.Replace principal-type and principal-email with the typeof principal and the principal's email address. Replace role-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, first set up a C# development environment andinstall the Cloud KMS C# SDK.

using Google.Cloud.Iam.V1;using Google.Cloud.Kms.V1;public class IamRemoveMemberSample{ public Policy IamRemoveMember( 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 client. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // Build the resource name. CryptoKeyName resourceName = new CryptoKeyName(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. Policy policy = client.IAMPolicyClient.GetIamPolicy( new GetIamPolicyRequest { ResourceAsResourceName = resourceName }); // Add the member to the policy. policy.RemoveRoleMember("roles/cloudkms.cryptoKeyEncrypterDecrypter", member); // Save the updated IAM policy. Policy result = client.IAMPolicyClient.SetIamPolicy( new SetIamPolicyRequest { ResourceAsResourceName = resourceName, Policy = policy }); // Return the resulting policy. return result; }}

Go

To run this code, first set 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.func iamRemoveMember(w io.Writer, name, member string) 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)if err != nil {return fmt.Errorf("failed to create kms client: %w", err)}defer client.Close()// Get the current IAM policy.handle := client.ResourceIAM(name)policy, err := handle.Policy(ctx)if err != nil {return fmt.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")if err := handle.SetPolicy(ctx, policy); err != nil {return fmt.Errorf("failed to save policy: %w", err)}fmt.Fprintf(w, "Updated IAM policy for %s\n", name)return nil}

Java

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

import com.google.cloud.kms.v1.CryptoKeyName;import com.google.cloud.kms.v1.KeyManagementServiceClient;import com.google.iam.v1.Binding;import com.google.iam.v1.Policy;import java.io.IOException;public class IamRemoveMember { public void iamRemoveMember() throws IOException { // TODO(developer): Replace these variables before running the sample. String projectId = "your-project-id"; String locationId = "us-east1"; String keyRingId = "my-key-ring"; String keyId = "my-key"; String member = "user:foo@example.com"; iamRemoveMember(projectId, locationId, keyRingId, keyId, member); } // Remove the given IAM membership on the resource, if it exists. public void iamRemoveMember( String projectId, String locationId, String keyRingId, String keyId, String member) throws IOException { // 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 (KeyManagementServiceClient client = KeyManagementServiceClient.create()) { // Build the key version name from the project, location, key ring, key, // and key version. CryptoKeyName resourceName = 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. Policy policy = client.getIamPolicy(resourceName); // Search through the bindings and remove matches. String roleToFind = "roles/cloudkms.cryptoKeyEncrypterDecrypter"; for (Binding binding : 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, first set 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 clientconst client = new KeyManagementServiceClient();// Build the resource nameconst resourceName = client.cryptoKeyPath( projectId, locationId, keyRingId, keyId);// The resource name could also be a key ring.// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);async function iamRemoveMember() { // Get the current IAM policy. const [policy] = await client.getIamPolicy({ resource: resourceName, }); // Build a new list of policy bindings with the user excluded. for (const i in policy.bindings) { const binding = policy.bindings[i]; if (binding.role !== 'roles/cloudkms.cryptoKeyEncrypterDecrypter') { continue; } const idx = binding.members.indexOf(member); if (idx !== -1) { binding.members.splice(idx, 1); } } // Save the updated IAM policy. const [updatedPolicy] = await client.setIamPolicy({ resource: resourceName, policy: policy, }); console.log('Updated policy'); return updatedPolicy;}return iamRemoveMember();

PHP

To run this code, first learn about using 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, first set up a Python development environment andinstall the Cloud KMS Python SDK.

from google.cloud import kmsfrom google.iam.v1 import policy_pb2 as iam_policydef iam_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. for binding in policy.bindings: if binding.role == "roles/cloudkms.cryptoKeyEncrypterDecrypter": if member in binding.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}") return updated_policy

Ruby

To run this code, first set 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_path project: 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_policy resource: resource_name# Remove the member from the current bindingspolicy.bindings.each do |bind| if bind.role == "roles/cloudkms.cryptoKeyEncrypterDecrypter" bind.members.delete member endend# Save the updated policy.updated_policy = iam_client.set_iam_policy resource: 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-policy key \ --keyring key-ring \ --location location

Replace key with the name of the key. Replace key-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, first set up a C# development environment andinstall the Cloud KMS C# SDK.

using Google.Cloud.Iam.V1;using Google.Cloud.Kms.V1;using System;public class IamGetPolicySample{ public Policy IamGetPolicy( string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key") { // Create the client. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // Build the resource name. CryptoKeyName resourceName = new CryptoKeyName(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. Policy policy = client.IAMPolicyClient.GetIamPolicy( new GetIamPolicyRequest { ResourceAsResourceName = resourceName }); // Print the policy. foreach (Binding b in policy.Bindings) { String role = b.Role; foreach (String member in b.Members) { // ... } } // Return the policy. return policy; }}

Go

To run this code, first set 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.func iamGetPolicy(w io.Writer, name string) 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)if err != nil {return fmt.Errorf("failed to create kms client: %w", err)}defer client.Close()// Get the current policy.policy, err := client.ResourceIAM(name).Policy(ctx)if err != nil {return fmt.Errorf("failed to get IAM policy: %w", err)}// Print the policy members.for _, role := range policy.Roles() {fmt.Fprintf(w, "%s\n", role)for _, member := range policy.Members(role) {fmt.Fprintf(w, "- %s\n", member)}fmt.Fprintf(w, "\n")}return nil}

Java

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

import com.google.cloud.kms.v1.CryptoKeyName;import com.google.cloud.kms.v1.KeyManagementServiceClient;import com.google.iam.v1.Binding;import com.google.iam.v1.Policy;import java.io.IOException;public class IamGetPolicy { public void iamGetPolicy() throws IOException { // TODO(developer): Replace these variables before running the sample. String projectId = "your-project-id"; String locationId = "us-east1"; String keyRingId = "my-key-ring"; String keyId = "my-key"; iamGetPolicy(projectId, locationId, keyRingId, keyId); } // Get the IAM policy for the given key. public void iamGetPolicy(String projectId, String locationId, String keyRingId, String keyId) throws IOException { // 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 (KeyManagementServiceClient client = KeyManagementServiceClient.create()) { // Build the key version name from the project, location, key ring, key, // and key version. CryptoKeyName resourceName = 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. Policy policy = client.getIamPolicy(resourceName); // Print the policy. System.out.printf("IAM policy:%n"); for (Binding binding : policy.getBindingsList()) { System.out.printf("%s%n", binding.getRole()); for (String member : binding.getMembersList()) { System.out.printf("- %s%n", member); } } } }}

Node.js

To run this code, first set 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 clientconst client = new KeyManagementServiceClient();// Build the resource nameconst resourceName = client.cryptoKeyPath( projectId, locationId, keyRingId, keyId);// The resource name could also be a key ring.// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);async function iamGetPolicy() { const [policy] = await client.getIamPolicy({ resource: resourceName, }); for (const binding of policy.bindings) { console.log(`Role: ${binding.role}`); for (const member of binding.members) { console.log(` - ${member}`); } } return policy;}return iamGetPolicy();

PHP

To run this code, first learn about using 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, first set up a Python development environment andinstall the Cloud KMS Python SDK.

from google.cloud import kmsfrom google.iam.v1 import policy_pb2 as iam_policydef iam_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 policy print(f"IAM policy for {resource_name}") for binding in policy.bindings: print(binding.role) for member in binding.members: print(f"- {member}") return policy

Ruby

To run this code, first set 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_path project: 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_policy resource: resource_name# Print the policy.puts "Policy for #{resource_name}"policy.bindings.each do |bind| puts bind.role bind.members.each do |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, grantthe roles/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 an owner on all the key rings and keys in thatproject. Similarly, if a user is granted the cloudkms.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.

What's next

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

Last updated 2024-09-12 UTC.

Access control with IAM  |  Cloud KMS Documentation  |  Google Cloud (2024)

FAQs

How do you control access to KMS? ›

To manage access to Cloud KMS resources, such as keys and key rings, you grant Identity and Access Management (IAM) roles. You can grant or restrict the ability to perform specific cryptographic operations, such as rotating a key or encrypting data. You can grant IAM roles on: A key directly.

How do you give IAM role access to KMS key? ›

To use an IAM policy to control access to a KMS key, the key policy for the KMS key must give the account permission to use IAM policies. Specifically, the key policy must include the policy statement that enables IAM policies. IAM policies can control access to any AWS KMS operation.

Which way of accessing Google Cloud lets you control services through the code you write answer? ›

The correct answer is c. APIS. APIs (Application Programming Interfaces) allow you to access and control Google Cloud services through code that you write.

Which would be a best practice when using Google Cloud IAM? ›

One of the most common and most critically important best practices is applying the principle of least privilege. IAM least privilege refers to an information security concept in which users are given the minimum levels of access or permissions without interfering with users' daily workflows.

Who has access to KMS keys? ›

KMS keys belong to the AWS account in which they were created. However, no identity or principal, including the AWS account root user, has permission to use or manage a KMS key unless that permission is explicitly provided in a key policy, IAM policy or grant.

How do I check my KMS settings? ›

Android MMS Settings
  1. Go to Settings from your Android home screen.
  2. Scroll down to mobile networks.
  3. Click on Access Point Names.
  4. Click Add in the top right corner and then follow the below settings.

How does IAM control user access? ›

An IAM framework enables IT to control user access to critical information within their organizations. IAM products offer role-based access control, which lets system administrators regulate access to systems or networks based on the roles of individual users within the enterprise.

How do I generate an access key and secret key for IAM role? ›

If your goal is to generate IAM access keys for a new user, login to the AWS console, go to IAM, go to users, Add User, click "Programmatic access", then Set permissions for the user and finish by creating the user. On the next screen will be the access keys.

Where do I find my IAM access key? ›

How to Retrieve IAM Access Keys. 1 Go to Amazon Web Services console and click on the name of your account (it is located in the top right corner of the console). In the expanded drop-down list, select Security Credentials. 2 Click the Get Started with IAM Users button.

What are the three services that can be accessed in the cloud? ›

Cloud computing is offered in three different service models which each satisfy a unique set of business requirements. These three models are known as Software as a Service (SaaS), Platform as a Service (PaaS), and Infrastructure as a Service (IaaS).

What are the 3 basic ways to interact with Google Cloud? ›

The following are example interaction methods: Google Cloud console: Use a web-based graphical user interface. Google Cloud CLI: Write commands and scripts. Cloud Client Libraries: Create your own application.

How do I give access to Google Cloud? ›

Grant the roles
  1. In the Google Cloud console, go to the IAM page. Go to IAM.
  2. Select the project.
  3. Click person_add Grant access.
  4. In the New principals field, enter your user identifier. ...
  5. In the Select a role list, select a role.
  6. To grant additional roles, click add Add another role and add each additional role.
  7. Click Save.

Which Google Cloud service should you use to enforce access control policies for applications and resources? ›

Use IAP when you want to enforce access control policies for applications and resources. IAP works with signed headers or the App Engine standard environment Users API to secure your app.

Which of the following are best practices to secure your account using IAM? ›

AWS IAM best practices
  • Delete unused entities. Keep your IAM entities tidy. ...
  • Enable multi-factor authentication. ...
  • Use secure password policies and password rotation. ...
  • Implement customer-managed policies. ...
  • Use inline policies to prevent shared permissions. ...
  • Use service control policies at the organizational level.
May 2, 2024

What is the difference between cloud identity and IAM in GCP? ›

With IAM, users only get access to what they need to get the job done. Cloud IAM enables you to grant access to cloud resources at fine-grained levels, well beyond project-level access. You can leverage Cloud Identity to easily create or sync user accounts across applications and projects.

How do I create a KMS customer managed key? ›

Sign in to the AWS Management Console and open the AWS Key Management Service (AWS KMS) console at https://console.aws.amazon.com/kms . To change the AWS Region, use the Region selector in the upper-right corner of the page. In the navigation pane, choose Customer managed keys. Choose Create key.

How do I turn off KMS? ›

Enabling and disabling KMS keys (console)

In the navigation pane, choose Customer managed keys. Choose the check box for the KMS keys that you want to enable or disable. To enable a KMS key, choose Key actions, Enable. To disable a KMS key, choose Key actions, Disable.

How do I stop KMS server? ›

To do this, press the Windows key + X and select "Command Prompt (Admin)" from the menu. Run the following command to stop the KMS service: net stop sppsvc. Run the following command to uninstall KMS: slmgr. vbs /upk.

How do I connect to KMS? ›

To activate KMS on a client version of Windows, follow these steps:
  1. Open an elevated Command Prompt window.
  2. In the elevated Command Prompt window, run the following command to install the KMS key: cscript.exe slmgr.vbs /ipk <KMS_Key>
Mar 29, 2024

Top Articles
How to Earn Passive Income with Crypto Staking in 2022
How To Invest During A Recession
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Selly Medaline
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 5927

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.