リソースから IAM メンバーを削除する

リソースから IAM メンバーを削除する

もっと見る

このコードサンプルを含む詳細なドキュメントについては、以下をご覧ください。

コードサンプル

C#

Cloud KMS 用のクライアント ライブラリをインストールして使用する方法については、Cloud KMS クライアント ライブラリをご覧ください。

Cloud KMS に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


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

Cloud KMS 用のクライアント ライブラリをインストールして使用する方法については、Cloud KMS クライアント ライブラリをご覧ください。

Cloud KMS に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Cloud KMS 用のクライアント ライブラリをインストールして使用する方法については、Cloud KMS クライアント ライブラリをご覧ください。

Cloud KMS に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

Cloud KMS 用のクライアント ライブラリをインストールして使用する方法については、Cloud KMS クライアント ライブラリをご覧ください。

Cloud KMS に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

//
// 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 library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the resource name
const 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

Cloud KMS 用のクライアント ライブラリをインストールして使用する方法については、Cloud KMS クライアント ライブラリをご覧ください。

Cloud KMS に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

use Google\Cloud\Iam\V1\Binding;
use Google\Cloud\Iam\V1\Policy;
use Google\Cloud\Kms\V1\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.
    $policy = $client->getIamPolicy($resourceName);

    // 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.
    $updatedPolicy = $client->setIamPolicy($resourceName, $newPolicy);
    printf('Removed %s' . PHP_EOL, $member);

    return $updatedPolicy;
}

Python

Cloud KMS 用のクライアント ライブラリをインストールして使用する方法については、Cloud KMS クライアント ライブラリをご覧ください。

Cloud KMS に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

from google.cloud import kms
from google.iam.v1 import policy_pb2 as iam_policy

def 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

Cloud KMS 用のクライアント ライブラリをインストールして使用する方法については、Cloud KMS クライアント ライブラリをご覧ください。

Cloud KMS に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

# 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 bindings
policy.bindings.each do |bind|
  if bind.role == "roles/cloudkms.cryptoKeyEncrypterDecrypter"
    bind.members.delete member
  end
end

# Save the updated policy.
updated_policy = iam_client.set_iam_policy resource: resource_name, policy: policy
puts "Removed #{member}"

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。