ソースへのアクセスを構成する: Cloud Storage

Storage Transfer Service は、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.list サービス エージェントにバケット内のオブジェクトの一覧表示を許可します。
storage.objects.get サービス エージェントにバケット内のオブジェクトの読み取りを許可します。
storage.objects.create

サービス エージェントにバケット内のオブジェクトの作成を許可します。ファイル システムに転送される場合は必須です。

Storage Transfer Service は、ソースバケット内に 2 つのフォルダを作成してデータを挿入します。cloud-ingest/ にはファイル システム情報が含まれ、storage-transfer/ には転送ログが含まれます。

storage.objects.delete サービス エージェントにバケット内のオブジェクトの削除を許可します。deleteObjectsFromSourceAfterTransfertrue に設定する場合は必須です。

次の事前定義ロールを使用すると、必要な権限を付与できます。

  • 次のいずれか:
    • Storage オブジェクト閲覧者roles/storage.objectViewer)。別の Cloud Storage バケットに転送される場合。
    • Storage オブジェクト作成者roles/storage.objectCreator): ファイル システムに転送される場合。
  • さらに、次のいずれか:
    • ストレージのレガシー バケット書き込みroles/storage.legacyBucketWriter): オブジェクト削除権限が必要な場合。
    • Storage レガシー バケット読み取りroles/storage.legacyBucketReader): オブジェクト削除権限が必要ない場合。

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

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

オブジェクトの ACLACL_PRESERVE が設定されている場合、ソース オブジェクトには Storage レガシー オブジェクト オーナーのロール(roles/storage.legacyObjectOwner)も必要です。ACL_PRESERVE の場合は、サービス アカウントに手動で Storage レガシー オブジェクト オーナーのロールを追加し、ソース オブジェクトの権限 storage.objects.getIamPolicy を付与します。

必要な権限を付与する

サービス エージェントに必要な権限を付与するには、次の手順を行います。

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

  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 Object Viewer または Storage Object Creator を選択します。

  7. [別のロールを追加] をクリックします。

  8. Storage Legacy Bucket Writer または Storage Legacy Bucket Reader を選択します。

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

gsutil

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

gsutil iam ch \
serviceAccount:YOUR_AGENT_EMAIL:objectViewer,legacyBucketReader \
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:[email protected]")
    {
        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:[email protected]"
	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:[email protected]";

    // 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:[email protected]',
//   'group:[email protected]',
// ];

// 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:[email protected]'])
 */
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: [email protected]"

    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:[email protected]"

  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. Authorization ヘッダーのアクセス トークンを生成するには、gcloud CLI のインストールと初期化を行います。

    OAuth 2.0 Playground を使用してアクセス トークンを作成し、Authorization ヘッダーに含めることもできます。

  2. 次の情報が含まれる JSON ファイルを作成します。

    {
    "bindings":[
      {
        "role": "roles/storage.objectViewer",
        "members":[
          "YOUR_AGENT_EMAIL"
        ]
      },
      {
        "role": "roles/storage.legacyBucketReader",
        "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