シンクへのアクセスを構成する: Cloud Storage

Cloud Storage では、サービス エージェントと呼ばれる Google 管理のサービス アカウントを使用して、Cloud Storage バケットにデータを移動します。このサービス エージェントは、初めて googleServiceAccounts.get を呼び出すときに作成されます。

宛先バケットは、サービス エージェントと同じプロジェクトに属している必要はありません。バケットがどのプロジェクトにあっても手順は同じです。

ユーザー権限

サービス エージェントに必要な権限を付与するには、宛先バケットに関連する権限が必要です。

  • storage.buckets.getIamPolicy
  • storage.buckets.setIamPolicy

必要な権限は、ストレージのレガシー バケット オーナーロール(roles/storage.legacyBucketOwner)またはストレージ管理者ロール(roles/storage.admin)に含まれています。

Google Cloud コンソールでの権限の自動付与

Google Cloud コンソールを使用して転送を作成し、ユーザー権限に記載されている権限がある場合、サービス エージェントには、宛先バケットに必要な権限が自動的に付与されます。

このページの手順はスキップできます。必要に応じて、ソースへのアクセスを構成してから、転送を作成します。

必要な権限

サービス エージェントには、宛先バケットに対する次の権限が必要です。

権限 説明
storage.buckets.get サービス アカウントにバケット ロケーションの取得を許可します。
storage.objects.create サービス アカウントにバケットへのオブジェクトの追加を許可します。
storage.objects.delete

サービス アカウントにバケット内のオブジェクトの削除を許可します。overwriteObjectsAlreadyExistingInSink または deleteObjectsUniqueInSinktrue に設定する場合は必要。

宛先バケットでオブジェクトのバージョニングが有効になっている場合は、overwriteObjectsAlreadyExistingInSink または deleteObjectsUniqueInSink に設定しても、オブジェクトは完全に削除されません。関連するライブ オブジェクト バージョンが非現行になります。

storage.objects.list サービス アカウントにバケット内のオブジェクトの一覧表示を許可します。overwriteObjectsAlreadyExistingInSinkfalse に設定する場合、または deleteObjectsUniqueInSinktrue に設定する場合は必要。

次の事前定義ロールは必要な権限を付与します。

  • Storage レガシー バケット書き込みroles/storage.legacyBucketWriter

legacy ロールとしてマークされた Cloud Storage のロールは、バケットレベルでのみ付与できます。

Cloud Storage のロールと権限の一覧については、IAM ロールをご覧ください。

必要な権限を付与する

サービス エージェントに Storage レガシー バケット書き込みロールを付与するには、次の操作を行います。

サービス エージェントのメールアドレスを確認する

  1. googleServiceAccounts.get リファレンス ページに移動します。

    [Try this method] というインタラクティブ パネルが開きます。

  2. パネルの [Request parameters] にプロジェクト ID を入力します。ここで指定するプロジェクトは Storage Transfer Service の管理に使用しているプロジェクトで、これは、宛先バケットのプロジェクトとは異なる場合があります。

  3. [EXECUTE] をクリックします。

    サービス エージェントのメールアドレスが accountEmail の値として返されます。この値をコピーします。

    サービス エージェントのメールアドレスは project-PROJECT_NUMBER@storage-transfer-service.iam.gserviceaccount.com の形式です。

バケットレベルのポリシーにサービス エージェントを追加する

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. プリンシパルにロールを付与するバケットと関連付けられている [バケット オーバーフロー] メニュー()をクリックします。

  3. [アクセス権を編集] を選択します。

  4. [+ プリンシパルを追加] ボタンをクリックします。

  5. [新しいプリンシパル] フィールドに、サービス エージェント アカウントのメールアドレスを入力します。

  6. [ロールの選択] プルダウン メニューから Storage Legacy Bucket Writer を選択します。

  7. [保存] をクリックします。

gsutil

gsutil iam ch コマンドを使用します。

gsutil iam ch \
serviceAccount:YOUR_AGENT_EMAIL:legacyBucketWriter \
gs://BUCKET_NAME

ここで

コードサンプル

C++

Cloud Storage 用のクライアント ライブラリをインストールして使用する方法については、Cloud Storage のクライアント ライブラリをご覧ください。詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& role, std::string const& member) {
  auto policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));

  if (!policy) throw std::move(policy).status();

  policy->set_version(3);
  for (auto& binding : policy->bindings()) {
    if (binding.role() != role || binding.has_condition()) {
      continue;
    }
    auto& members = binding.members();
    if (std::find(members.begin(), members.end(), member) == members.end()) {
      members.emplace_back(member);
    }
  }

  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
  if (!updated) throw std::move(updated).status();

  std::cout << "Updated IAM policy bucket " << bucket_name
            << ". The new policy is " << *updated << "\n";
}

C#

Cloud Storage 用のクライアント ライブラリをインストールして使用する方法については、Cloud Storage のクライアント ライブラリをご覧ください。詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

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


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class AddBucketIamMemberSample
{
    public Policy AddBucketIamMember(
        string bucketName = "your-unique-bucket-name",
        string role = "roles/storage.objectViewer",
        string member = "serviceAccount:dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var policy = storage.GetBucketIamPolicy(bucketName, new GetBucketIamPolicyOptions
        {
            RequestedPolicyVersion = 3
        });
        // Set the policy schema version. For more information, please refer to https://cloud.google.com/iam/docs/policies#versions.
        policy.Version = 3;

        Policy.BindingsData bindingToAdd = new Policy.BindingsData
        {
            Role = role,
            Members = new List<string> { member }
        };

        policy.Bindings.Add(bindingToAdd);
        var bucketIamPolicy = storage.SetBucketIamPolicy(bucketName, policy);
        Console.WriteLine($"Added {member} with role {role} " + $"to {bucketName}");
        return bucketIamPolicy;
    }
}

Go

Cloud Storage 用のクライアント ライブラリをインストールして使用する方法については、Cloud Storage のクライアント ライブラリをご覧ください。詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

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

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/iam"
	"cloud.google.com/go/storage"
)

// addBucketIAMMember adds the bucket IAM member to permission role.
func addBucketIAMMember(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	policy, err := bucket.IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).IAM().Policy: %w", bucketName, err)
	}
	// Other valid prefixes are "serviceAccount:", "user:"
	// See the documentation for more values.
	// https://cloud.google.com/storage/docs/access-control/iam
	identity := "group:cloud-logs@google.com"
	var role iam.RoleName = "roles/storage.objectViewer"

	policy.Add(identity, role)
	if err := bucket.IAM().SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("Bucket(%q).IAM().SetPolicy: %w", bucketName, err)
	}
	// NOTE: It may be necessary to retry this operation if IAM policies are
	// being modified concurrently. SetPolicy will return an error if the policy
	// was modified since it was retrieved.
	fmt.Fprintf(w, "Added %v with role %v to %v\n", identity, role, bucketName)
	return nil
}

Java

Cloud Storage 用のクライアント ライブラリをインストールして使用する方法については、Cloud Storage のクライアント ライブラリをご覧ください。詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

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


import com.google.cloud.Binding;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AddBucketIamMember {
  /** Example of adding a member to the Bucket-level IAM */
  public static void addBucketIamMember(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // For more information please read:
    // https://cloud.google.com/storage/docs/access-control/iam
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Policy originalPolicy =
        storage.getIamPolicy(bucketName, Storage.BucketSourceOption.requestedPolicyVersion(3));

    String role = "roles/storage.objectViewer";
    String member = "group:example@google.com";

    // getBindingsList() returns an ImmutableList and copying over to an ArrayList so it's mutable.
    List<Binding> bindings = new ArrayList(originalPolicy.getBindingsList());

    // Create a new binding using role and member
    Binding.Builder newMemberBindingBuilder = Binding.newBuilder();
    newMemberBindingBuilder.setRole(role).setMembers(Arrays.asList(member));
    bindings.add(newMemberBindingBuilder.build());

    // Update policy to add member
    Policy.Builder updatedPolicyBuilder = originalPolicy.toBuilder();
    updatedPolicyBuilder.setBindings(bindings).setVersion(3);
    Policy updatedPolicy = storage.setIamPolicy(bucketName, updatedPolicyBuilder.build());

    System.out.printf("Added %s with role %s to %s\n", member, role, bucketName);
  }
}

Node.js

Cloud Storage 用のクライアント ライブラリをインストールして使用する方法については、Cloud Storage のクライアント ライブラリをご覧ください。詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The role to grant
// const roleName = 'roles/storage.objectViewer';

// The members to grant the new role to
// const members = [
//   'user:jdoe@example.com',
//   'group:admins@example.com',
// ];

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function addBucketIamMember() {
  // Get a reference to a Google Cloud Storage bucket
  const bucket = storage.bucket(bucketName);

  // For more information please read:
  // https://cloud.google.com/storage/docs/access-control/iam
  const [policy] = await bucket.iam.getPolicy({requestedPolicyVersion: 3});

  // Adds the new roles to the bucket's IAM policy
  policy.bindings.push({
    role: roleName,
    members: members,
  });

  // Updates the bucket's IAM policy
  await bucket.iam.setPolicy(policy);

  console.log(
    `Added the following member(s) with role ${roleName} to ${bucketName}:`
  );

  members.forEach(member => {
    console.log(`  ${member}`);
  });
}

addBucketIamMember().catch(console.error);

PHP

Cloud Storage 用のクライアント ライブラリをインストールして使用する方法については、Cloud Storage のクライアント ライブラリをご覧ください。詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

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

use Google\Cloud\Storage\StorageClient;

/**
 * Adds a new member / role IAM pair to a given Cloud Storage bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $role The role to which the given member should be added.
 *        (e.g. 'roles/storage.objectViewer')
 * @param string[] $members The member(s) to be added to the role.
 *        (e.g. ['group:example@google.com'])
 */
function add_bucket_iam_member(string $bucketName, string $role, array $members): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $policy = $bucket->iam()->policy(['requestedPolicyVersion' => 3]);
    $policy['version'] = 3;

    $policy['bindings'][] = [
        'role' => $role,
        'members' => $members
    ];

    $bucket->iam()->setPolicy($policy);

    printf('Added the following member(s) to role %s for bucket %s' . PHP_EOL, $role, $bucketName);
    foreach ($members as $member) {
        printf('    %s' . PHP_EOL, $member);
    }
}

Python

Cloud Storage 用のクライアント ライブラリをインストールして使用する方法については、Cloud Storage のクライアント ライブラリをご覧ください。詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

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

from google.cloud import storage

def add_bucket_iam_member(bucket_name, role, member):
    """Add a new member to an IAM Policy"""
    # bucket_name = "your-bucket-name"
    # role = "IAM role, e.g., roles/storage.objectViewer"
    # member = "IAM identity, e.g., user: name@example.com"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    policy = bucket.get_iam_policy(requested_policy_version=3)

    policy.bindings.append({"role": role, "members": {member}})

    bucket.set_iam_policy(policy)

    print(f"Added {member} with role {role} to {bucket_name}.")

Ruby

Cloud Storage 用のクライアント ライブラリをインストールして使用する方法については、Cloud Storage のクライアント ライブラリをご覧ください。詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

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

def add_bucket_iam_member bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  role   = "roles/storage.objectViewer"
  member = "group:example@google.com"

  bucket.policy requested_policy_version: 3 do |policy|
    policy.bindings.insert role: role, members: [member]
  end

  puts "Added #{member} with role #{role} to #{bucket_name}"
end

JSON

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. 次の情報が含まれる JSON ファイルを作成します。

    {
    "bindings":[
      {
        "role": "roles/storage.legacyBucketWriter",
        "members":[
          "YOUR_AGENT_EMAIL"
        ]
      }
    ]
    }

    ここで

  3. cURL を使用して、PUT setIamPolicy リクエストで JSON API を呼び出します。

    curl -X PUT --data-binary @JSON_FILE_NAME \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/iam"

    ここで

    • JSON_FILE_NAME は、手順 2 で作成したファイルのパスです。
    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • BUCKET_NAME は、プリンシパルのアクセス権を付与するバケットの名前です。例: my-bucket

Cloud Storage リソースへの IAM ロールの割り当てについては、Cloud Storage IAM のドキュメントをご覧ください。