転送の作成

このページでは、転送ジョブを作成して開始する方法について説明します。

ソースと宛先(シンクとも呼ばれます)が Storage Transfer Service でサポートされているかどうかを確認するには、サポートされているソースとシンクをご覧ください。

エージェントとエージェント プール

ソースと宛先によっては、エージェント プールの作成と構成を行い、転送元または転送先にアクセスできるマシンにエージェントをインストールする必要がある場合があります。

  • Amazon S3、Microsoft Azure、URL リスト、Cloud Storage から Cloud Storage への転送には、エージェントとエージェント プールは必要ありません

  • ソースと宛先がファイル システムである転送、または S3 互換ストレージからの転送には、エージェントとエージェント プールが必要です。手順については、エージェント プールの管理をご覧ください。

始める前に

転送を構成する前に、次のアクセス権が構成されていることを確認してください。

gcloud コマンドを使用している場合は、gcloud CLI をインストールしてください。

転送を作成

転送ジョブ名に、個人を特定できる情報(PII)やセキュリティ データなどの機密情報を含めないでください。リソース名は、他の Google Cloud リソースの名前に反映され、プロジェクト外部の Google 内部システムに公開される場合があります。

Google Cloud コンソール

  1. Google Cloud コンソールのストレージの [Data Transfer] ページに移動します。

    Storage Transfer Service に移動

  2. [転送ジョブを作成] をクリックします。[転送ジョブの作成] ページが表示されます。

  3. ソースを選択します。

    Cloud Storage

    ソースバケットと宛先バケットを選択するには、ユーザー アカウントに storage.buckets.get 権限が必要です。バケットの名前を直接入力することもできます。詳細については、アクセスのトラブルシューティングをご覧ください。

    1. [参照元の種類] で、[Google Cloud Storage] を選択します。

    2. [宛先の種類] を選択します。

    3. 移行先が Cloud Storage の場合は、[スケジュール モード] を選択します。バッチ転送は、1 回限りまたはスケジュールに基づいて実行されます。イベント ドリブン転送は、ソースを継続的にモニタリングし、追加や変更が行われるとデータを転送します。

      イベント ドリブン転送を構成するには、イベント ドリブン転送の手順を実施します。

    4. [次のステップ] をクリックします。

    5. 次のいずれかの方法で、バケットとそのバケット内のフォルダ(必要に応じて)を選択します。

      • [バケットまたはフォルダ] フィールドに、接頭辞 gs:// を付けずに既存の Cloud Storage バケット名とパスを入力します。例: my-test-bucket/path/to/files。別のプロジェクトの Cloud Storage バケットを指定するには、[バケット名] フィールドに名前を正確に入力します。

      • [参照] をクリックしてバケットを選択し、プロジェクト内の既存のバケットのリストを選択します。

        [参照] をクリックし、[プロジェクト ID] をクリックして新しいプロジェクト ID とバケットを選択すると、他のプロジェクトのバケットを選択できます。

      • 新しいバケットを作成するには、[新しいバケットを作成] をクリックします。

    6. イベント ドリブン転送の場合は、Pub/Sub サブスクリプション名を入力します。これは、次の形式になります。

      projects/PROJECT_NAME/subscriptions/SUBSCRIPTION_ID
      
    7. 必要に応じて、オブジェクトを接頭辞でフィルタするか、最終更新日でフィルタします。ソースの場所としてフォルダを指定した場合、接頭辞フィルタはそのフォルダを基準とします。たとえば、ソースが my-test-bucket/path/ の場合、file の一致フィルタには my-test-bucket/path/file で始まるすべてのファイルが含まれます。
    8. [次のステップ] をクリックします。

    Amazon S3

    1. [参照元の種類] で [Amazon S3] を選択します。

    2. [宛先の種類] として [Google Cloud Storage] を選択します。

    3. スケジュール モードを選択します。バッチ転送は、1 回限りまたはスケジュールに基づいて実行されます。イベント ドリブン転送は、ソースを継続的にモニタリングし、追加や変更が行われるとデータを転送します。

      イベント ドリブン転送を構成するには、イベント ドリブン転送の手順を実施します。

    4. [次のステップ] をクリックします。

    5. [Bucket or folder name] フィールドに、ソースバケットの名前を入力します。

      このバケット名は、AWS Management Console に表示される名前です。

    6. CloudFront ディストリビューションを使用して S3 から転送する場合は、[CloudFront ドメイン] フィールドにディストリビューション ドメイン名を入力します。たとえば、https://dy1h2n3l4ob56.cloudfront.net のようにします。CloudFront ディストリビューションを構成するには、CloudFront 経由で S3 から転送するをご覧ください。

    7. アマゾン ウェブ サービス(AWS)の認証方法を選択します。ID 連携のために AWS アクセスキーや Amazon Resource Name(ARN)を指定できます。

      • アクセスキー: [アクセスキー ID] フィールドにアクセスキーを入力し、[シークレット アクセスキー] フィールドにアクセス キーに関連付けられたシークレットを入力します。

      • ARN: [AWS IAM ロールの ARN] フィールドに次の構文で ARN を入力します。

        arn:aws:iam::ACCOUNT:role/ROLE-NAME-WITH-PATH
        

        ここで

        • ACCOUNT: ハイフンのない AWS アカウント ID。
        • ROLE-NAME-WITH-PATH: パスを含む AWS ロール名。

        ARN の詳細については、IAM ARN をご覧ください。

    8. イベント ドリブン転送の場合は、Amazon SQS キューの ARN を入力します。これは、次の形式になります。

      arn:aws:sqs:us-east-1:1234567890:event-queue
      
    9. 必要に応じて、オブジェクトを接頭辞でフィルタするか、最終更新日でフィルタします。ソースの場所としてフォルダを指定した場合、接頭辞フィルタはそのフォルダを基準とします。たとえば、ソースが my-test-bucket/path/ の場合、file の一致フィルタには my-test-bucket/path/file で始まるすべてのファイルが含まれます。
    10. [次のステップ] をクリックします。

    S3 互換ストレージ

    1. [ソースタイプ] で、[S3 互換のオブジェクト ストレージ] を選択します。

    2. [次のステップ] をクリックします。

    3. この転送に必要な情報を指定します。

      1. この転送に構成したエージェント プールを選択します。

      2. エンドポイントに対応するバケット名を入力します。たとえば、データが次の場所に存在するとします。

        https://us-east-1.example.com/folder1/bucket_a

        folder1/bucket_a」と入力します。

      3. エンドポイントを入力します。プロトコル(http:// または https://)は含めないでください。前の手順の例では、次のように入力します。

        us-east-1.example.com

    4. この転送の任意の属性を指定します。

      1. リクエストの署名に使用する署名のリージョンを入力します。ソースで署名のリージョンが必要ない場合は、このフィールドを空のままにします。

      2. このリクエストの署名プロセスを選択します。

      3. アドレス指定スタイルを選択します。これにより、バケット名がパススタイル(https://s3.region.example.com/bucket-name/key-name など)で提供されるのか、仮想ホストタイプ(https://bucket-name.s3.region.example.com/key-name)で提供されるのかが決まります。詳しくは、Amazon のドキュメントの[バケットの仮想ホスティング]をご覧ください。

      4. ネットワーク プロトコルを選択します。

      5. 使用する Listing API のバージョンを選択します。詳細については、ListObjectsV2ListObjects のドキュメントをご覧ください。

    5. [次のステップ] をクリックします。

    Microsoft Azure Blob Storage

    1. [参照元の種類] で、[Azure Blob Storage または Data Lake Storage Gen2] を選択します。

    2. [次のステップ] をクリックします。

    3. 以下を指定します。

      1. ストレージ アカウント名 - ソースの Microsoft Azure Storage アカウント名。

        ストレージ アカウント名は、Microsoft Azure Storage ポータルの [すべてのサービス] > [ストレージ] > [ストレージ アカウント] に表示されます。

      2. コンテナ名 - Microsoft Azure Storage のコンテナ名。

        コンテナ名は、Microsoft Azure Storage ポータルの [ストレージ エクスプローラー] > [BLOB コンテナー] に表示されます。

      3. Shared Access Signature(SAS) - 格納されているアクセス ポリシーから作成された Microsoft Azure Storage SAS のトークン。詳細については、Shared Access Signature(SAS)を使用した Azure Storage リソースへのアクセスの制限を付与するをご覧ください。

        SAS トークンのデフォルトの有効期限は 8 時間です。SAS トークンを作成する際は、転送を正常に完了できるように、十分な有効期限を設定してください。
    4. 必要に応じて、オブジェクトを接頭辞でフィルタするか、最終更新日でフィルタします。ソースの場所としてフォルダを指定した場合、接頭辞フィルタはそのフォルダを基準とします。たとえば、ソースが my-test-bucket/path/ の場合、file の一致フィルタには my-test-bucket/path/file で始まるすべてのファイルが含まれます。
    5. [次のステップ] をクリックします。

    ファイル システム

    1. [ソースタイプ] で、[POSIX ファイル システム] を選択します。

    2. [宛先の種類] を選択して、[次のステップ] をクリックします。

    3. 既存のエージェント プールを選択するか、[エージェント プールの作成] を選択し、手順に沿って新しいプールを作成します。

    4. ファイル システム ディレクトリの完全修飾パスを指定します。

    5. [次のステップ] をクリックします。

    HDFS

    HDFS から Cloud Storage に転送するをご覧ください。

    URL リスト

    1. [参照元の種類] で、[URL リスト] を選択し、[次のステップ] をクリックします。

    2. [TSV ファイルの URL] で、タブ区切りの値(TSV)ファイルの URL を指定します。TSV ファイルを作成する方法について詳しくは、URL リストの作成をご覧ください。

    3. 必要に応じて、オブジェクトを接頭辞でフィルタするか、最終更新日でフィルタします。ソースの場所としてフォルダを指定した場合、接頭辞フィルタはそのフォルダを基準とします。たとえば、ソースが my-test-bucket/path/ の場合、file の一致フィルタには my-test-bucket/path/file で始まるすべてのファイルが含まれます。
    4. [次のステップ] をクリックします。

  4. 宛先を選択します。

    Cloud Storage

    1. [バケットまたはフォルダ] フィールドに、ソースバケットと(必要に応じて)フォルダ名を入力するか、[参照] をクリックして、現在のプロジェクトにある既存のバケットリストからバケットを選択します。新しいバケットを作成するには、[新しいバケットを作成] をクリックします。

    2. [次のステップ] をクリックします。

    3. 転送ジョブの設定を選択します。一部のオプションは、特定のソースとシンクの組み合わせでのみ使用できます。

      1. [説明] フィールドに、転送の説明を入力します。ジョブを区別できるように、意味のある一意の説明を入力することをおすすめします。

      2. [メタデータのオプション] で、デフォルトのオプションを使用するか、[オプションを表示して選択する] をクリックして、サポートされているすべてのメタデータの値を指定します。詳細については、メタデータの保持をご覧ください。

      3. [上書きの条件] で、次のいずれかを選択します。

        • 異なる場合: ソースファイルの名前が同じで ETag またはチェックサムの値が異なる場合、宛先ファイルを上書きします。

        • 常に: ソースファイルが同じ名前の場合、同一であっても常に宛先ファイルを上書きします。

      4. [削除のタイミング] で、次のいずれかを選択します。

        • なし: ソースと宛先のどちらからもファイルを削除しません。

        • 転送後にソースからファイルを削除する: 転送先に移行した後、ソースからファイルを削除します。

        • 転送元にもないファイルを転送先から削除する: 転送先の Cloud Storage バケット内のファイルが転送元にもない場合は、Cloud Storage バケットからファイルを削除します。

          このオプションにより、宛先の Cloud Storage バケットが移行元と完全に一致することが保証されます。

      5. [通知オプション] で、Pub/Sub トピックと通知するイベントを選択します。詳細については、Pub/Sub 通知をご覧ください。

    4. [次のステップ] をクリックします。

    ファイル システム

    1. 既存のエージェント プールを選択するか、[エージェント プールの作成] を選択し、手順に沿って新しいプールを作成します。

    2. 宛先ディレクトリの完全修飾パスを指定します。

    3. [次のステップ] をクリックします。

  5. スケジュール オプションを選択します。

    1. [1 回だけ実行] プルダウン リストから、次のいずれかを選択します。

      • 1 回だけ実行: 選択した時間に、1 回だけ転送を行います。

      • 毎日実行: 転送は毎日、選択した時刻に開始されます。

        オプションの [終了日] を入力することも、[終了日] を空白のままにして転送を継続的に実行することもできます。

      • 毎週実行: 選択した時間に毎週転送を実行します。

      • カスタム頻度で実行: 選択した頻度で転送を実行します。転送は、時間の間隔で定期的に繰り返すように設定できます。

        オプションの [終了日] を入力することも、[終了日] を空白のままにして転送を継続的に実行することもできます。

    2. [今すぐ開始] プルダウン リストから、次のいずれかを選択します。

      • 今すぐ開始: [作成] をクリックすると転送が開始されます。

      • 開始日: 選択した日時に転送を開始します。[カレンダー] をクリックして、カレンダーから開始日を選択します。

    3. 転送ジョブを作成するには、[作成] をクリックします。

gcloud CLI

新しい転送ジョブを作成するには、gcloud transfer jobs create コマンドを使用します。スケジュールまたは --do-not-run が指定されていない限り、新しいジョブを作成すると、指定された転送が開始します。

gcloud transfer jobs create \
  SOURCE DESTINATION

ここで

  • SOURCE は、この転送のデータソースです。各ソースの形式は次のとおりです。

    • Cloud Storage: gs://BUCKET_NAME。特定のフォルダから転送するには、末尾のスラッシュを含めて gs://BUCKET_NAME/FOLDER_PATH/ を指定します。
    • Amazon S3: s3://BUCKET_NAME/FOLDER_PATH
    • S3 互換ストレージ: s3://BUCKET_NAMEバケット名はエンドポイントからの相対名です。たとえば、データが https://us-east-1.example.com/folder1/bucket_a に存在する場合は「s3://folder1/bucket_a」と入力します。
    • Microsoft Azure Storage: https://myaccount.blob.core.windows.net/CONTAINER_NAME
    • URL リスト: https://PATH_TO_URL_LIST または http://PATH_TO_URL_LIST
    • POSIX ファイル システム: posix:///PATH。これは、エージェント ホストマシンのルートからの絶対パスである必要があります。
    • HDFS: hdfs:///PATH
  • DESTINATION は次のいずれかです。

    • Cloud Storage: gs://BUCKET_NAME。特定のディレクトリに転送するには、末尾のスラッシュを含めて gs://BUCKET_NAME/FOLDER_PATH/ を指定します。
    • POSIX ファイル システム: posix:///PATH。これは、エージェント ホストマシンのルートからの絶対パスである必要があります。

転送で転送エージェントが必要な場合、次のオプションを使用できます。

  • --source-agent-pool には、この転送に使用するソース エージェント プールを指定します。ファイル システムからの転送の場合は必須。

  • --destination-agent-pool には、この転送に使用する転送先エージェント プールを指定します。ファイル システムへの転送の場合は必須。

  • --intermediate-storage-path は、Cloud Storage バケットへのパスです(形式は gs://my-intermediary-bucket)。2 つのファイル システム間の転送の場合は必須。中間バケットの作成の詳細については、中間ストレージとして Cloud Storage バケットを作成するをご覧ください。

上記以外に次のようなオプションがあります。

  • --source-creds-file には、転送元の AWS または Azure 認証情報を含むマシン上のローカル ファイルへの相対パスを指定します。認証情報ファイルの形式については、TransferSpec のリファレンスをご覧ください。

  • --do-not-run は、コマンドの送信時に Storage Transfer Service がジョブを実行しないようにします。ジョブを実行するには、更新してスケジュールを追加するか、jobs run を使用して手動で開始します。

  • --manifest-file には、ソースから転送するファイルのリストを含む Cloud Storage 内の CSV ファイルのパスを指定します。マニフェスト ファイルの形式については、マニフェストを使用して特定のファイルまたはオブジェクトを転送するをご覧ください。

  • ジョブ情報: --name--description--source-creds-file を指定できます。

  • スケジュール: --schedule-starts--schedule-repeats-every--schedule-repeats-until、または --do-not-run を指定します。

  • オブジェクト条件: 条件を使用して、転送するオブジェクトを決定します。これには、--include-prefixes--exclude-prefixes--include-modified-[before | after]-[absolute | relative] の時間ベースの条件が含まれます。ソースでフォルダを指定した場合、接頭辞フィルタはそのフォルダを基準とします。詳細については、ソース オブジェクトを前方一致でフィルタするをご覧ください。

    オブジェクト条件は、ファイル システムに関連する転送ではサポートされません。

  • 転送オプション: 宛先ファイルを上書きするかどうか(--overwrite-when=different または always)、転送中または転送後に特定のファイルを削除するかどうか(--delete-from=destination-if-unique または source-after-transfer)を指定します。保持するメタデータ値--preserve-metadata)を指定することや、転送されたオブジェクトにストレージ クラスを設定することもできます(--custom-storage-class)。

  • 通知: --notification-pubsub-topic--notification-event-types--notification-payload-format を使用して、転送の Pub/Sub 通知を構成します。

  • Cloud Logging: --log-actions--log-action-states を使用して、エージェントレス転送または S3 互換ソースからの転送に対して Cloud Logging を有効にします。詳細については、Storage Transfer Service の Cloud Logging をご覧ください。

S3 互換ソースからの転送でも、次のオプションが使用されます。

  • --source-endpoint(必須)には、ストレージ システムのエンドポイントを指定します。例: s3.example.com。正しい形式についてはプロバイダにお問い合わせください。プロトコル(http:// または https://)は指定しないでください。
  • --source-signing-region には、リクエストに署名するリージョンを指定します。ストレージ プロバイダが署名のリージョンを必要としない場合は、このフラグを省略します。
  • --source-auth-method には、使用する認証方法を指定します。有効な値は AWS_SIGNATURE_V2 または AWS_SIGNATURE_V4 です。詳しくは、Amazon の SigV4SigV2 のドキュメントをご覧ください。
  • --source-request-model には、使用するアドレス指定スタイルを指定します。有効な値は PATH_STYLE または VIRTUAL_HOSTED_STYLE です。パススタイルには https://s3.example.com/BUCKET_NAME/KEY_NAME の形式を使用します。仮想ホストスタイルでは、https://BUCKET_NAME.s3.example.com/KEY_NAME の形式を使用します。
  • --source-network-protocol には、エージェントがこのジョブに使用するネットワーク プロトコルを指定します。有効な値は HTTP または HTTPS です。
  • --source-list-api には、バケットからオブジェクトを返すための S3 Listing API のバージョンを指定します。有効な値は LIST_OBJECTS または LIST_OBJECTS_V2 です。詳しくは、Amazon の ListObjectsV2ListObjects のドキュメントをご覧ください。

すべてのオプションを表示するには、gcloud transfer jobs create --help を実行するか、gcloud リファレンス ドキュメントをご覧ください。

Amazon S3 から Cloud Storage

次のコマンドを実行して、毎日の転送ジョブを作成し、過去 1 日間に変更されたデータを s3://my-s3-bucket から my-storage-bucket という Cloud Storage バケットに移動します。

gcloud transfer jobs create \
  s3://my-s3-bucket gs://my-storage-bucket \
  --source-creds-file=/examplefolder/creds.txt \
  --include-modified-after-relative=1d \
  --schedule-repeats-every=1d

S3 互換ストレージから Cloud Storage

S3 互換ソースから Cloud Storage バケットに転送するには:

gcloud transfer jobs create s3://my-s3-compat-bucket gs://my-storage-bucket \
  --source-agent-pool=my-source-agent-pool
  --source-endpoint=us-east-1.example.com/ \
  --source-auth-method=AWS_SIGNATURE_V2 \
  --source-request-model=PATH_STYLE \
  --source-network-protocol=HTTPS \
  --source-list-api=LIST_OBJECTS_V2

ファイル システムから Cloud Storage

ファイル システムから Cloud Storage バケットに転送するには、次のように指定します。

gcloud transfer jobs create \
  posix:///tmp/source gs://my-storage-bucket \
  --source-agent-pool=my-source-agent-pool

Cloud Storage からファイル システム

Cloud Storage バケットからファイル システムに転送するには、次のように指定します。

gcloud transfer jobs create \
  gs://my-storage-bucket posix:///tmp/destination \
  --destination-agent-pool=my-destination-agent-pool

ファイル システム間

2 つのファイル システム間で転送するには、ソース エージェント プール、宛先エージェント プール、およびデータが通過する中間 Cloud Storage バケットを指定する必要があります。

中間バケットの詳細については、中間ストレージとして Cloud Storage バケットを作成するをご覧ください。

transfer jobs create を呼び出すときに、次の 3 つのリソースを指定します。

gcloud transfer jobs create \
  posix:///tmp/source/on/systemA posix:///tmp/destination/on/systemB \
  --source-agent-pool=source_agent_pool \
  --destination-agent-pool=destination_agent_pool \
  --intermediate-storage-path=gs://my-intermediary-bucket

REST

次のサンプルは、REST API を介して Storage Transfer Service を使用する方法を示しています。

Storage Transfer Service API を使用して転送ジョブを構成または編集する場合は、時刻を UTC で設定してください。転送ジョブのスケジュールの指定方法については、スケジュールをご覧ください。

Cloud Storage バケット間の転送

この例では、Cloud Storage バケット間でファイルを移動する方法について説明します。たとえば、別のロケーションのバケットにデータを移動できます。

transferJobs create を使ってリクエストします。

POST https://storagetransfer.googleapis.com/v1/transferJobs
{
  "description": "YOUR DESCRIPTION",
  "status": "ENABLED",
  "projectId": "PROJECT_ID",
  "schedule": {
      "scheduleStartDate": {
          "day": 1,
          "month": 1,
          "year": 2015
      },
      "startTimeOfDay": {
          "hours": 1,
          "minutes": 1
      }
  },
  "transferSpec": {
      "gcsDataSource": {
          "bucketName": "GCS_SOURCE_NAME"
      },
      "gcsDataSink": {
          "bucketName": "GCS_SINK_NAME"
      },
      "transferOptions": {
          "deleteObjectsFromSourceAfterTransfer": true
      }
  }
}
レスポンス:
200 OK
{
  "transferJob": [
      {
          "creationTime": "2015-01-01T01:01:00.000000000Z",
          "description": "YOUR DESCRIPTION",
          "name": "transferJobs/JOB_ID",
          "status": "ENABLED",
          "lastModificationTime": "2015-01-01T01:01:00.000000000Z",
          "projectId": "PROJECT_ID",
          "schedule": {
              "scheduleStartDate": {
                  "day": 1,
                  "month": 1,
                  "year": 2015
              },
              "startTimeOfDay": {
                  "hours": 1,
                  "minutes": 1
              }
          },
          "transferSpec": {
              "gcsDataSource": {
                  "bucketName": "GCS_SOURCE_NAME",
              },
              "gcsDataSink": {
                  "bucketName": "GCS_NEARLINE_SINK_NAME"
              },
              "objectConditions": {
                  "minTimeElapsedSinceLastModification": "2592000.000s"
              },
              "transferOptions": {
                  "deleteObjectsFromSourceAfterTransfer": true
              }
          }
      }
  ]
}

Amazon S3 から Cloud Storage への転送

この例では、Amazon S3 から Cloud Storage バケットにファイルを移動します。Amazon S3 から Cloud Storage にデータを移動した場合にどのような影響があるかを理解するために、Amazon S3 へのアクセスを構成する料金の記事を必ずご確認ください。

転送ジョブを作成する場合は、Amazon S3 バケットソース名に bucketNames3:// 接頭辞を含めないでください。

transferJobs create を使ってリクエストします。

POST https://storagetransfer.googleapis.com/v1/transferJobs
{
  "description": "YOUR DESCRIPTION",
  "status": "ENABLED",
  "projectId": "PROJECT_ID",
  "schedule": {
      "scheduleStartDate": {
          "day": 1,
          "month": 1,
          "year": 2015
      },
      "scheduleEndDate": {
          "day": 1,
          "month": 1,
          "year": 2015
      },
      "startTimeOfDay": {
          "hours": 1,
          "minutes": 1
      }
  },
  "transferSpec": {
      "awsS3DataSource": {
          "bucketName": "AWS_SOURCE_NAME",
          "awsAccessKey": {
              "accessKeyId": "AWS_ACCESS_KEY_ID",
              "secretAccessKey": "AWS_SECRET_ACCESS_KEY"
          }
      },
      "gcsDataSink": {
          "bucketName": "GCS_SINK_NAME"
      }
  }
}
レスポンス:
200 OK
{
  "transferJob": [
      {
          "creationTime": "2015-01-01T01:01:00.000000000Z",
          "description": "YOUR DESCRIPTION",
          "name": "transferJobs/JOB_ID",
          "status": "ENABLED",
          "lastModificationTime": "2015-01-01T01:01:00.000000000Z",
          "projectId": "PROJECT_ID",
          "schedule": {
              "scheduleStartDate": {
                  "day": 1,
                  "month": 1,
                  "year": 2015
              },
              "scheduleEndDate": {
                  "day": 1,
                  "month": 1,
                  "year": 2015
              },
              "startTimeOfDay": {
                  "hours": 1,
                  "minutes": 1
              }
          },
          "transferSpec": {
              "awsS3DataSource": {
                  "bucketName": "AWS_SOURCE_NAME"
              },
              "gcsDataSink": {
                  "bucketName": "GCS_SINK_NAME"
              },
              "objectConditions": {},
              "transferOptions": {}
          }
      }
  ]
}

CloudFront ディストリビューションを介して S3 から転送する場合は、ディストリビューション ドメイン名を transferSpec.awsS3DataSource.cloudfrontDomain フィールドの値として指定します。

"transferSpec": {
  "awsS3DataSource": {
    "bucketName": "AWS_SOURCE_NAME",
    "cloudfrontDomain": "https://dy1h2n3l4ob56.cloudfront.net",
    "awsAccessKey": {
      "accessKeyId": "AWS_ACCESS_KEY_ID",
      "secretAccessKey": "AWS_SECRET_ACCESS_KEY"
    }
  },
  ...
}

Microsoft Azure Blob Storage と Cloud Storage の間の転送

この例では、Microsoft Azure Storage の共有アクセス署名(SAS)トークンを使用して、Microsoft Azure Storage から Cloud Storage バケットにファイルを移動する方法について学習します。

Microsoft Azure Storage SAS の詳細については、Shared Access Signature(SAS)を使用した Azure Storage リソースへのアクセスの制限を付与するをご覧ください。

開始する前に、Microsoft Azure Storage へのアクセスを構成する料金を確認して、Microsoft Azure Storage から Cloud Storage にデータを移動した場合にどのような影響があるかを把握してください。

transferJobs create を使ってリクエストします。

POST https://storagetransfer.googleapis.com/v1/transferJobs
{
  "description": "YOUR DESCRIPTION",
  "status": "ENABLED",
  "projectId": "PROJECT_ID",
  "schedule": {
      "scheduleStartDate": {
          "day": 14,
          "month": 2,
          "year": 2020
      },
      "scheduleEndDate": {
          "day": 14
          "month": 2,
          "year": 2020
      },
      "startTimeOfDay": {
          "hours": 1,
          "minutes": 1
      }
  },
  "transferSpec": {
      "azureBlobStorageDataSource": {
          "storageAccount": "AZURE_SOURCE_NAME",
          "azureCredentials": {
              "sasToken": "AZURE_SAS_TOKEN",
          },
          "container": "AZURE_CONTAINER",
      },
      "gcsDataSink": {
          "bucketName": "GCS_SINK_NAME"
      }
  }
}
レスポンス:
200 OK
{
  "transferJob": [
      {
          "creationTime": "2020-02-14T01:01:00.000000000Z",
          "description": "YOUR DESCRIPTION",
          "name": "transferJobs/JOB_ID",
          "status": "ENABLED",
          "lastModificationTime": "2020-02-14T01:01:00.000000000Z",
          "projectId": "PROJECT_ID",
          "schedule": {
              "scheduleStartDate": {
                  "day": 14
                  "month": 2,
                  "year": 2020
              },
              "scheduleEndDate": {
                  "day": 14,
                  "month": 2,
                  "year": 2020
              },
              "startTimeOfDay": {
                  "hours": 1,
                  "minutes": 1
              }
          },
          "transferSpec": {
              "azureBlobStorageDataSource": {
                  "storageAccount": "AZURE_SOURCE_NAME",
                  "azureCredentials": {
                      "sasToken": "AZURE_SAS_TOKEN",
                  },
                  "container": "AZURE_CONTAINER",
              },
              "objectConditions": {},
              "transferOptions": {}
          }
      }
  ]
}

ファイル システムから転送する

この例では、POSIX ファイル システムから Cloud Storage バケットにファイルを移動する方法について学習します。

posixDataSourcetransferJobs.create を使用します。

POST https://storagetransfer.googleapis.com/v1/transferJobs
{
 "name":"transferJobs/sample_transfer",
 "description": "My First Transfer",
 "status": "ENABLED",
 "projectId": "my_transfer_project_id",
 "schedule": {
     "scheduleStartDate": {
         "year": 2022,
         "month": 5,
         "day": 2
     },
     "startTimeOfDay": {
         "hours": 22,
         "minutes": 30,
         "seconds": 0,
         "nanos": 0
     }
     "scheduleEndDate": {
         "year": 2022,
         "month": 12,
         "day": 31
     },
     "repeatInterval": {
         "259200s"
     },
 },
 "transferSpec": {
     "posixDataSource": {
          "rootDirectory": "/bar/",
     },
     "sourceAgentPoolName": "my_example_pool",
     "gcsDataSink": {
          "bucketName": "destination_bucket"
          "path": "foo/bar/"
     },
  }
}

schedule フィールドは省略可能です。省略した場合は、transferJobs.run リクエストで転送ジョブを開始する必要があります。

ジョブの作成後に転送のステータスを確認するには、transferJobs.get を使用します。

GET https://storagetransfer.googleapis.com/v1/transferJobs/sample_transfer?project_id=my_transfer_project_id

ソースパスと宛先パスの指定

ソースと宛先のパスを使用すると、Cloud Storage バケットにデータを転送するときに、ソースと宛先のディレクトリを指定できます。たとえば、file1.txtfile2.txt というファイルと、B という Cloud Storage バケットがあるとします。my-stuff という宛先パスを設定した場合、転送の完了後、ファイルは gs://B/my-stuff/file1.txtgs://B/my-stuff/file2.txt に配置されます。

ソースパスの指定

転送ジョブを作成するときにソースパスを指定するには、TransferSpec 仕様の gcsDataSource フィールドに path フィールドを追加します。

{
gcsDataSource: {
  bucketName: "SOURCE_BUCKET",
  path: "SOURCE_PATH/",
},
}

この例では次のようになります。

  • SOURCE_BUCKET: 転送元の Cloud Storage バケット。
  • SOURCE_PATH: 転送元の Cloud Storage のパス。

転送先のパスの指定

転送ジョブを作成するときに転送先フォルダを指定するには、TransferSpec 仕様の gcsDataSink フィールドに path フィールドを追加します。

{
gcsDataSink: {
  bucketName: "DESTINATION_BUCKET",
  path: "DESTINATION_PATH/",
},
}

この例では以下の情報が表示されます。

  • DESTINATION_BUCKET: 転送先の Cloud Storage バケット。
  • DESTINATION_PATH: 転送先の Cloud Storage のパス。

完全なリクエストの例

次に、完全なリクエストの例を示します。

POST https://storagetransfer.googleapis.com/v1/transferJobs
{
  "description": "YOUR DESCRIPTION",
  "status": "ENABLED",
  "projectId": "PROJECT_ID",
  "schedule": {
      "scheduleStartDate": {
          "day": 1,
          "month": 1,
          "year": 2015
      },
      "startTimeOfDay": {
          "hours": 1,
          "minutes": 1
      }
  },
  "transferSpec": {
      "gcsDataSource": {
          "bucketName": "GCS_SOURCE_NAME",
          "path": "GCS_SOURCE_PATH",
      },
      "gcsDataSink": {
          "bucketName": "GCS_SINK_NAME",
          "path": "GCS_SINK_PATH",
      },
      "objectConditions": {
          "minTimeElapsedSinceLastModification": "2592000s"
      },
      "transferOptions": {
          "deleteObjectsFromSourceAfterTransfer": true
      }
  }

}

クライアント ライブラリ

次のサンプルは、Go、Java、Node.js、Python のプログラムで Storage Transfer Service を使用する方法を示しています。

転送ジョブをプログラムで構成または編集する場合は、時刻を UTC で設定してください。転送ジョブのスケジュールの指定方法について詳しくは、スケジュールをご覧ください。

Storage Transfer Service クライアント ライブラリの詳細については、Storage Transfer Service クライアント ライブラリ スタートガイドをご覧ください。

Cloud Storage バケット間の転送

この例では、Cloud Storage バケット間でファイルを移動する方法について説明します。たとえば、別のロケーションのバケットにデータを移動できます。

Go

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

	"google.golang.org/genproto/googleapis/type/date"
	"google.golang.org/genproto/googleapis/type/timeofday"
	"google.golang.org/protobuf/types/known/durationpb"

	storagetransfer "cloud.google.com/go/storagetransfer/apiv1"
	"cloud.google.com/go/storagetransfer/apiv1/storagetransferpb"
)

func transferToNearline(w io.Writer, projectID string, gcsSourceBucket string, gcsNearlineSinkBucket string) (*storagetransferpb.TransferJob, error) {
	// Your Google Cloud Project ID
	// projectID := "my-project-id"

	// The name of the GCS bucket to transfer objects from
	// gcsSourceBucket := "my-source-bucket"

	// The name of the Nearline GCS bucket to transfer objects to
	// gcsNearlineSinkBucket := "my-sink-bucket"

	ctx := context.Background()
	client, err := storagetransfer.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storagetransfer.NewClient: %w", err)
	}
	defer client.Close()

	// A description of this job
	jobDescription := "Transfers objects that haven't been modified in 30 days to a Nearline bucket"

	// The time to start the transfer
	startTime := time.Now().UTC()

	req := &storagetransferpb.CreateTransferJobRequest{
		TransferJob: &storagetransferpb.TransferJob{
			ProjectId:   projectID,
			Description: jobDescription,
			TransferSpec: &storagetransferpb.TransferSpec{
				DataSink: &storagetransferpb.TransferSpec_GcsDataSink{
					GcsDataSink: &storagetransferpb.GcsData{BucketName: gcsNearlineSinkBucket}},
				DataSource: &storagetransferpb.TransferSpec_GcsDataSource{
					GcsDataSource: &storagetransferpb.GcsData{BucketName: gcsSourceBucket},
				},
				ObjectConditions: &storagetransferpb.ObjectConditions{
					MinTimeElapsedSinceLastModification: &durationpb.Duration{Seconds: 2592000 /*30 days */},
				},
				TransferOptions: &storagetransferpb.TransferOptions{DeleteObjectsFromSourceAfterTransfer: true},
			},
			Schedule: &storagetransferpb.Schedule{
				ScheduleStartDate: &date.Date{
					Year:  int32(startTime.Year()),
					Month: int32(startTime.Month()),
					Day:   int32(startTime.Day()),
				},
				ScheduleEndDate: &date.Date{
					Year:  int32(startTime.Year()),
					Month: int32(startTime.Month()),
					Day:   int32(startTime.Day()),
				},
				StartTimeOfDay: &timeofday.TimeOfDay{
					Hours:   int32(startTime.Hour()),
					Minutes: int32(startTime.Minute()),
					Seconds: int32(startTime.Second()),
				},
			},
			Status: storagetransferpb.TransferJob_ENABLED,
		},
	}
	resp, err := client.CreateTransferJob(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("failed to create transfer job: %w", err)
	}
	if _, err = client.RunTransferJob(ctx, &storagetransferpb.RunTransferJobRequest{
		ProjectId: projectID,
		JobName:   resp.Name,
	}); err != nil {
		return nil, fmt.Errorf("failed to run transfer job: %w", err)
	}
	fmt.Fprintf(w, "Created and ran transfer job from %v to %v with name %v", gcsSourceBucket, gcsNearlineSinkBucket, resp.Name)
	return resp, nil
}

Java

古いサンプルをお探しの場合Storage Transfer Service 移行ガイドをご覧ください。

import com.google.protobuf.Duration;
import com.google.storagetransfer.v1.proto.StorageTransferServiceClient;
import com.google.storagetransfer.v1.proto.TransferProto.CreateTransferJobRequest;
import com.google.storagetransfer.v1.proto.TransferTypes.GcsData;
import com.google.storagetransfer.v1.proto.TransferTypes.ObjectConditions;
import com.google.storagetransfer.v1.proto.TransferTypes.Schedule;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferJob;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferJob.Status;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferOptions;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferSpec;
import com.google.type.Date;
import com.google.type.TimeOfDay;
import java.io.IOException;
import java.util.Calendar;

public class TransferToNearline {
  /**
   * Creates a one-off transfer job that transfers objects in a standard GCS bucket that are more
   * than 30 days old to a Nearline GCS bucket.
   */
  public static void transferToNearline(
      String projectId,
      String jobDescription,
      String gcsSourceBucket,
      String gcsNearlineSinkBucket,
      long startDateTime)
      throws IOException {

    // Your Google Cloud Project ID
    // String projectId = "your-project-id";

    // A short description of this job
    // String jobDescription = "Sample transfer job of old objects to a Nearline GCS bucket.";

    // The name of the source GCS bucket to transfer data from
    // String gcsSourceBucket = "your-gcs-source-bucket";

    // The name of the Nearline GCS bucket to transfer old objects to
    // String gcsSinkBucket = "your-nearline-gcs-bucket";

    // What day and time in UTC to start the transfer, expressed as an epoch date timestamp.
    // If this is in the past relative to when the job is created, it will run the next day.
    // long startDateTime =
    //     new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2000-01-01 00:00:00").getTime();

    // Parse epoch timestamp into the model classes
    Calendar startCalendar = Calendar.getInstance();
    startCalendar.setTimeInMillis(startDateTime);
    // Note that this is a Date from the model class package, not a java.util.Date
    Date date =
        Date.newBuilder()
            .setYear(startCalendar.get(Calendar.YEAR))
            .setMonth(startCalendar.get(Calendar.MONTH) + 1)
            .setDay(startCalendar.get(Calendar.DAY_OF_MONTH))
            .build();
    TimeOfDay time =
        TimeOfDay.newBuilder()
            .setHours(startCalendar.get(Calendar.HOUR_OF_DAY))
            .setMinutes(startCalendar.get(Calendar.MINUTE))
            .setSeconds(startCalendar.get(Calendar.SECOND))
            .build();

    TransferJob transferJob =
        TransferJob.newBuilder()
            .setDescription(jobDescription)
            .setProjectId(projectId)
            .setTransferSpec(
                TransferSpec.newBuilder()
                    .setGcsDataSource(GcsData.newBuilder().setBucketName(gcsSourceBucket))
                    .setGcsDataSink(GcsData.newBuilder().setBucketName(gcsNearlineSinkBucket))
                    .setObjectConditions(
                        ObjectConditions.newBuilder()
                            .setMinTimeElapsedSinceLastModification(
                                Duration.newBuilder().setSeconds(2592000 /* 30 days */)))
                    .setTransferOptions(
                        TransferOptions.newBuilder().setDeleteObjectsFromSourceAfterTransfer(true)))
            .setSchedule(Schedule.newBuilder().setScheduleStartDate(date).setStartTimeOfDay(time))
            .setStatus(Status.ENABLED)
            .build();

    // Create a Transfer Service client
    StorageTransferServiceClient storageTransfer = StorageTransferServiceClient.create();

    // Create the transfer job
    TransferJob response =
        storageTransfer.createTransferJob(
            CreateTransferJobRequest.newBuilder().setTransferJob(transferJob).build());

    System.out.println("Created transfer job from standard bucket to Nearline bucket:");
    System.out.println(response.toString());
  }
}

Node.js


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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of the Google Cloud Platform Project that owns the job
// projectId = 'my-project-id'

// A useful description for your transfer job
// description = 'My transfer job'

// Google Cloud Storage source bucket name
// gcsSourceBucket = 'my-gcs-source-bucket'

// Google Cloud Storage destination bucket name
// gcsSinkBucket = 'my-gcs-destination-bucket'

// Date to start daily migration
// startDate = new Date()

// Creates a client
const client = new StorageTransferServiceClient();

/**
 * Create a daily migration from a GCS bucket to another GCS bucket for
 * objects untouched for 30+ days.
 */
async function createDailyNearline30DayMigration() {
  // Runs the request and creates the job
  const [transferJob] = await client.createTransferJob({
    transferJob: {
      projectId,
      description,
      status: 'ENABLED',
      schedule: {
        scheduleStartDate: {
          day: startDate.getDate(),
          month: startDate.getMonth() + 1,
          year: startDate.getFullYear(),
        },
      },
      transferSpec: {
        gcsDataSource: {
          bucketName: gcsSourceBucket,
        },
        gcsDataSink: {
          bucketName: gcsSinkBucket,
        },
        objectConditions: {
          minTimeElapsedSinceLastModification: {
            seconds: 2592000, // 30 days
          },
        },
        transferOptions: {
          deleteObjectsFromSourceAfterTransfer: true,
        },
      },
    },
  });

  console.log(`Created transferJob: ${transferJob.name}`);
}

createDailyNearline30DayMigration();

Python

古いサンプルをお探しの場合Storage Transfer Service 移行ガイドをご覧ください。

from datetime import datetime

from google.cloud import storage_transfer
from google.protobuf.duration_pb2 import Duration

def create_daily_nearline_30_day_migration(
    project_id: str,
    description: str,
    source_bucket: str,
    sink_bucket: str,
    start_date: datetime,
):
    """Create a daily migration from a GCS bucket to a Nearline GCS bucket
    for objects untouched for 30 days."""

    client = storage_transfer.StorageTransferServiceClient()

    # The ID of the Google Cloud Platform Project that owns the job
    # project_id = 'my-project-id'

    # A useful description for your transfer job
    # description = 'My transfer job'

    # Google Cloud Storage source bucket name
    # source_bucket = 'my-gcs-source-bucket'

    # Google Cloud Storage destination bucket name
    # sink_bucket = 'my-gcs-destination-bucket'

    transfer_job_request = storage_transfer.CreateTransferJobRequest(
        {
            "transfer_job": {
                "project_id": project_id,
                "description": description,
                "status": storage_transfer.TransferJob.Status.ENABLED,
                "schedule": {
                    "schedule_start_date": {
                        "day": start_date.day,
                        "month": start_date.month,
                        "year": start_date.year,
                    }
                },
                "transfer_spec": {
                    "gcs_data_source": {
                        "bucket_name": source_bucket,
                    },
                    "gcs_data_sink": {
                        "bucket_name": sink_bucket,
                    },
                    "object_conditions": {
                        "min_time_elapsed_since_last_modification": Duration(
                            seconds=2592000  # 30 days
                        )
                    },
                    "transfer_options": {
                        "delete_objects_from_source_after_transfer": True
                    },
                },
            }
        }
    )

    result = client.create_transfer_job(transfer_job_request)
    print(f"Created transferJob: {result.name}")

Amazon S3 から Cloud Storage への転送

この例では、Amazon S3 から Cloud Storage バケットにファイルを移動します。Amazon S3 から Cloud Storage にデータを移動した場合にどのような影響があるかを理解するために、Amazon S3 へのアクセスを構成する料金の記事を必ずご確認ください。

転送ジョブを作成する場合は、Amazon S3 バケットソース名に bucketNames3:// 接頭辞を含めないでください。

Go

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

	storagetransfer "cloud.google.com/go/storagetransfer/apiv1"
	"cloud.google.com/go/storagetransfer/apiv1/storagetransferpb"
	"google.golang.org/genproto/googleapis/type/date"
	"google.golang.org/genproto/googleapis/type/timeofday"
)

func transferFromAws(w io.Writer, projectID string, awsSourceBucket string, gcsSinkBucket string) (*storagetransferpb.TransferJob, error) {
	// Your Google Cloud Project ID
	// projectID := "my-project-id"

	// The name of the Aws bucket to transfer objects from
	// awsSourceBucket := "my-source-bucket"

	// The name of the GCS bucket to transfer objects to
	// gcsSinkBucket := "my-sink-bucket"

	ctx := context.Background()
	client, err := storagetransfer.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storagetransfer.NewClient: %w", err)
	}
	defer client.Close()

	// A description of this job
	jobDescription := "Transfers objects from an AWS bucket to a GCS bucket"

	// The time to start the transfer
	startTime := time.Now().UTC()

	// The AWS access key credential, should be accessed via environment variable for security
	awsAccessKeyID := os.Getenv("AWS_ACCESS_KEY_ID")

	// The AWS secret key credential, should be accessed via environment variable for security
	awsSecretKey := os.Getenv("AWS_SECRET_ACCESS_KEY")

	req := &storagetransferpb.CreateTransferJobRequest{
		TransferJob: &storagetransferpb.TransferJob{
			ProjectId:   projectID,
			Description: jobDescription,
			TransferSpec: &storagetransferpb.TransferSpec{
				DataSource: &storagetransferpb.TransferSpec_AwsS3DataSource{
					AwsS3DataSource: &storagetransferpb.AwsS3Data{
						BucketName: awsSourceBucket,
						AwsAccessKey: &storagetransferpb.AwsAccessKey{
							AccessKeyId:     awsAccessKeyID,
							SecretAccessKey: awsSecretKey,
						}},
				},
				DataSink: &storagetransferpb.TransferSpec_GcsDataSink{
					GcsDataSink: &storagetransferpb.GcsData{BucketName: gcsSinkBucket}},
			},
			Schedule: &storagetransferpb.Schedule{
				ScheduleStartDate: &date.Date{
					Year:  int32(startTime.Year()),
					Month: int32(startTime.Month()),
					Day:   int32(startTime.Day()),
				},
				ScheduleEndDate: &date.Date{
					Year:  int32(startTime.Year()),
					Month: int32(startTime.Month()),
					Day:   int32(startTime.Day()),
				},
				StartTimeOfDay: &timeofday.TimeOfDay{
					Hours:   int32(startTime.Hour()),
					Minutes: int32(startTime.Minute()),
					Seconds: int32(startTime.Second()),
				},
			},
			Status: storagetransferpb.TransferJob_ENABLED,
		},
	}
	resp, err := client.CreateTransferJob(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("failed to create transfer job: %w", err)
	}
	if _, err = client.RunTransferJob(ctx, &storagetransferpb.RunTransferJobRequest{
		ProjectId: projectID,
		JobName:   resp.Name,
	}); err != nil {
		return nil, fmt.Errorf("failed to run transfer job: %w", err)
	}
	fmt.Fprintf(w, "Created and ran transfer job from %v to %v with name %v", awsSourceBucket, gcsSinkBucket, resp.Name)
	return resp, nil
}

Java

古いサンプルをお探しの場合Storage Transfer Service 移行ガイドをご覧ください。


import com.google.storagetransfer.v1.proto.StorageTransferServiceClient;
import com.google.storagetransfer.v1.proto.TransferProto.CreateTransferJobRequest;
import com.google.storagetransfer.v1.proto.TransferTypes.AwsAccessKey;
import com.google.storagetransfer.v1.proto.TransferTypes.AwsS3Data;
import com.google.storagetransfer.v1.proto.TransferTypes.GcsData;
import com.google.storagetransfer.v1.proto.TransferTypes.Schedule;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferJob;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferJob.Status;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferSpec;
import com.google.type.Date;
import com.google.type.TimeOfDay;
import java.io.IOException;
import java.util.Calendar;

public class TransferFromAws {

  // Creates a one-off transfer job from Amazon S3 to Google Cloud Storage.
  public static void transferFromAws(
      String projectId,
      String jobDescription,
      String awsSourceBucket,
      String gcsSinkBucket,
      long startDateTime)
      throws IOException {

    // Your Google Cloud Project ID
    // String projectId = "your-project-id";

    // A short description of this job
    // String jobDescription = "Sample transfer job from S3 to GCS.";

    // The name of the source AWS bucket to transfer data from
    // String awsSourceBucket = "yourAwsSourceBucket";

    // The name of the GCS bucket to transfer data to
    // String gcsSinkBucket = "your-gcs-bucket";

    // What day and time in UTC to start the transfer, expressed as an epoch date timestamp.
    // If this is in the past relative to when the job is created, it will run the next day.
    // long startDateTime =
    //     new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2000-01-01 00:00:00").getTime();

    // The ID used to access your AWS account. Should be accessed via environment variable.
    String awsAccessKeyId = System.getenv("AWS_ACCESS_KEY_ID");

    // The Secret Key used to access your AWS account. Should be accessed via environment variable.
    String awsSecretAccessKey = System.getenv("AWS_SECRET_ACCESS_KEY");

    // Set up source and sink
    TransferSpec transferSpec =
        TransferSpec.newBuilder()
            .setAwsS3DataSource(
                AwsS3Data.newBuilder()
                    .setBucketName(awsSourceBucket)
                    .setAwsAccessKey(
                        AwsAccessKey.newBuilder()
                            .setAccessKeyId(awsAccessKeyId)
                            .setSecretAccessKey(awsSecretAccessKey)))
            .setGcsDataSink(GcsData.newBuilder().setBucketName(gcsSinkBucket))
            .build();

    // Parse epoch timestamp into the model classes
    Calendar startCalendar = Calendar.getInstance();
    startCalendar.setTimeInMillis(startDateTime);
    // Note that this is a Date from the model class package, not a java.util.Date
    Date startDate =
        Date.newBuilder()
            .setYear(startCalendar.get(Calendar.YEAR))
            .setMonth(startCalendar.get(Calendar.MONTH) + 1)
            .setDay(startCalendar.get(Calendar.DAY_OF_MONTH))
            .build();
    TimeOfDay startTime =
        TimeOfDay.newBuilder()
            .setHours(startCalendar.get(Calendar.HOUR_OF_DAY))
            .setMinutes(startCalendar.get(Calendar.MINUTE))
            .setSeconds(startCalendar.get(Calendar.SECOND))
            .build();
    Schedule schedule =
        Schedule.newBuilder()
            .setScheduleStartDate(startDate)
            .setScheduleEndDate(startDate)
            .setStartTimeOfDay(startTime)
            .build();

    // Set up the transfer job
    TransferJob transferJob =
        TransferJob.newBuilder()
            .setDescription(jobDescription)
            .setProjectId(projectId)
            .setTransferSpec(transferSpec)
            .setSchedule(schedule)
            .setStatus(Status.ENABLED)
            .build();

    // Create a Transfer Service client
    StorageTransferServiceClient storageTransfer = StorageTransferServiceClient.create();

    // Create the transfer job
    TransferJob response =
        storageTransfer.createTransferJob(
            CreateTransferJobRequest.newBuilder().setTransferJob(transferJob).build());

    System.out.println("Created transfer job from AWS to GCS:");
    System.out.println(response.toString());
  }
}

Node.js


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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of the Google Cloud Platform Project that owns the job
// projectId = 'my-project-id'

// A useful description for your transfer job
// description = 'My transfer job'

// AWS S3 source bucket name
// awsSourceBucket = 'my-s3-source-bucket'

// AWS Access Key ID
// awsAccessKeyId = 'AKIA...'

// AWS Secret Access Key
// awsSecretAccessKey = 'HEAoMK2.../...ku8'

// Google Cloud Storage destination bucket name
// gcsSinkBucket = 'my-gcs-destination-bucket'

// Creates a client
const client = new StorageTransferServiceClient();

/**
 * Creates a one-time transfer job from Amazon S3 to Google Cloud Storage.
 */
async function transferFromS3() {
  // Setting the start date and the end date as the same time creates a
  // one-time transfer
  const now = new Date();
  const oneTimeSchedule = {
    day: now.getDate(),
    month: now.getMonth() + 1,
    year: now.getFullYear(),
  };

  // Runs the request and creates the job
  const [transferJob] = await client.createTransferJob({
    transferJob: {
      projectId,
      description,
      status: 'ENABLED',
      schedule: {
        scheduleStartDate: oneTimeSchedule,
        scheduleEndDate: oneTimeSchedule,
      },
      transferSpec: {
        awsS3DataSource: {
          bucketName: awsSourceBucket,
          awsAccessKey: {
            accessKeyId: awsAccessKeyId,
            secretAccessKey: awsSecretAccessKey,
          },
        },
        gcsDataSink: {
          bucketName: gcsSinkBucket,
        },
      },
    },
  });

  console.log(
    `Created and ran a transfer job from '${awsSourceBucket}' to '${gcsSinkBucket}' with name ${transferJob.name}`
  );
}

transferFromS3();

Python

古いサンプルをお探しの場合Storage Transfer Service 移行ガイドをご覧ください。

from datetime import datetime

from google.cloud import storage_transfer

def create_one_time_aws_transfer(
    project_id: str,
    description: str,
    source_bucket: str,
    aws_access_key_id: str,
    aws_secret_access_key: str,
    sink_bucket: str,
):
    """Creates a one-time transfer job from Amazon S3 to Google Cloud
    Storage."""

    client = storage_transfer.StorageTransferServiceClient()

    # The ID of the Google Cloud Platform Project that owns the job
    # project_id = 'my-project-id'

    # A useful description for your transfer job
    # description = 'My transfer job'

    # AWS S3 source bucket name
    # source_bucket = 'my-s3-source-bucket'

    # AWS Access Key ID
    # aws_access_key_id = 'AKIA...'

    # AWS Secret Access Key
    # aws_secret_access_key = 'HEAoMK2.../...ku8'

    # Google Cloud Storage destination bucket name
    # sink_bucket = 'my-gcs-destination-bucket'

    now = datetime.utcnow()
    # Setting the start date and the end date as
    # the same time creates a one-time transfer
    one_time_schedule = {"day": now.day, "month": now.month, "year": now.year}

    transfer_job_request = storage_transfer.CreateTransferJobRequest(
        {
            "transfer_job": {
                "project_id": project_id,
                "description": description,
                "status": storage_transfer.TransferJob.Status.ENABLED,
                "schedule": {
                    "schedule_start_date": one_time_schedule,
                    "schedule_end_date": one_time_schedule,
                },
                "transfer_spec": {
                    "aws_s3_data_source": {
                        "bucket_name": source_bucket,
                        "aws_access_key": {
                            "access_key_id": aws_access_key_id,
                            "secret_access_key": aws_secret_access_key,
                        },
                    },
                    "gcs_data_sink": {
                        "bucket_name": sink_bucket,
                    },
                },
            }
        }
    )

    result = client.create_transfer_job(transfer_job_request)
    print(f"Created transferJob: {result.name}")

Microsoft Azure Blob Storage と Cloud Storage の間の転送

この例では、Microsoft Azure Storage の共有アクセス署名(SAS)トークンを使用して、Microsoft Azure Storage から Cloud Storage バケットにファイルを移動する方法について学習します。

Microsoft Azure Storage SAS の詳細については、Shared Access Signature(SAS)を使用した Azure Storage リソースへのアクセスの制限を付与するをご覧ください。

開始する前に、Microsoft Azure Storage へのアクセスを構成する料金を確認して、Microsoft Azure Storage から Cloud Storage にデータを移動した場合にどのような影響があるかを把握してください。

Go

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

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

import (
	"context"
	"fmt"
	"io"
	"os"

	storagetransfer "cloud.google.com/go/storagetransfer/apiv1"
	"cloud.google.com/go/storagetransfer/apiv1/storagetransferpb"
)

func transferFromAzure(w io.Writer, projectID string, azureStorageAccountName string, azureSourceContainer string, gcsSinkBucket string) (*storagetransferpb.TransferJob, error) {
	// Your Google Cloud Project ID.
	// projectID := "my-project-id"

	// The name of your Azure Storage account.
	// azureStorageAccountName := "my-azure-storage-acc"

	// The name of the Azure container to transfer objects from.
	// azureSourceContainer := "my-source-container"

	// The name of the GCS bucket to transfer objects to.
	// gcsSinkBucket := "my-sink-bucket"

	ctx := context.Background()
	client, err := storagetransfer.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storagetransfer.NewClient: %w", err)
	}
	defer client.Close()

	// The Azure SAS token, should be accessed via environment variable for security
	azureSasToken := os.Getenv("AZURE_SAS_TOKEN")

	req := &storagetransferpb.CreateTransferJobRequest{
		TransferJob: &storagetransferpb.TransferJob{
			ProjectId: projectID,
			TransferSpec: &storagetransferpb.TransferSpec{
				DataSource: &storagetransferpb.TransferSpec_AzureBlobStorageDataSource{
					AzureBlobStorageDataSource: &storagetransferpb.AzureBlobStorageData{
						StorageAccount: azureStorageAccountName,
						AzureCredentials: &storagetransferpb.AzureCredentials{
							SasToken: azureSasToken,
						},
						Container: azureSourceContainer,
					},
				},
				DataSink: &storagetransferpb.TransferSpec_GcsDataSink{
					GcsDataSink: &storagetransferpb.GcsData{BucketName: gcsSinkBucket}},
			},
			Status: storagetransferpb.TransferJob_ENABLED,
		},
	}
	resp, err := client.CreateTransferJob(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("failed to create transfer job: %w", err)
	}
	if _, err = client.RunTransferJob(ctx, &storagetransferpb.RunTransferJobRequest{
		ProjectId: projectID,
		JobName:   resp.Name,
	}); err != nil {
		return nil, fmt.Errorf("failed to run transfer job: %w", err)
	}
	fmt.Fprintf(w, "Created and ran transfer job from %v to %v with name %v", azureSourceContainer, gcsSinkBucket, resp.Name)
	return resp, nil
}

Java

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

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

import com.google.storagetransfer.v1.proto.StorageTransferServiceClient;
import com.google.storagetransfer.v1.proto.TransferProto;
import com.google.storagetransfer.v1.proto.TransferProto.RunTransferJobRequest;
import com.google.storagetransfer.v1.proto.TransferTypes.AzureBlobStorageData;
import com.google.storagetransfer.v1.proto.TransferTypes.AzureCredentials;
import com.google.storagetransfer.v1.proto.TransferTypes.GcsData;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferJob;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferJob.Status;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferSpec;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class TransferFromAzure {
  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    // Your Google Cloud Project ID
    String projectId = "my-project-id";

    // Your Azure Storage Account name
    String azureStorageAccount = "my-azure-account";

    // The Azure source container to transfer data from
    String azureSourceContainer = "my-source-container";

    // The GCS bucket to transfer data to
    String gcsSinkBucket = "my-sink-bucket";

    transferFromAzureBlobStorage(
        projectId, azureStorageAccount, azureSourceContainer, gcsSinkBucket);
  }

  /**
   * Creates and runs a transfer job to transfer all data from an Azure container to a GCS bucket.
   */
  public static void transferFromAzureBlobStorage(
      String projectId,
      String azureStorageAccount,
      String azureSourceContainer,
      String gcsSinkBucket)
      throws IOException, ExecutionException, InterruptedException {

    // Your Azure SAS token, should be accessed via environment variable
    String azureSasToken = System.getenv("AZURE_SAS_TOKEN");

    TransferSpec transferSpec =
        TransferSpec.newBuilder()
            .setAzureBlobStorageDataSource(
                AzureBlobStorageData.newBuilder()
                    .setAzureCredentials(
                        AzureCredentials.newBuilder().setSasToken(azureSasToken).build())
                    .setContainer(azureSourceContainer)
                    .setStorageAccount(azureStorageAccount))
            .setGcsDataSink(GcsData.newBuilder().setBucketName(gcsSinkBucket).build())
            .build();

    TransferJob transferJob =
        TransferJob.newBuilder()
            .setProjectId(projectId)
            .setStatus(Status.ENABLED)
            .setTransferSpec(transferSpec)
            .build();

    // 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,
    // or use "try-with-close" statement to do this automatically.
    try (StorageTransferServiceClient storageTransfer = StorageTransferServiceClient.create()) {
      // Create the transfer job
      TransferJob response =
          storageTransfer.createTransferJob(
              TransferProto.CreateTransferJobRequest.newBuilder()
                  .setTransferJob(transferJob)
                  .build());

      // Run the created job
      storageTransfer
          .runTransferJobAsync(
              RunTransferJobRequest.newBuilder()
                  .setProjectId(projectId)
                  .setJobName(response.getName())
                  .build())
          .get();

      System.out.println(
          "Created and ran a transfer job from "
              + azureSourceContainer
              + " to "
              + gcsSinkBucket
              + " with "
              + "name "
              + response.getName());
    }
  }
}

Node.js

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

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


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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of the Google Cloud Platform Project that owns the job
// projectId = 'my-project-id'

// A useful description for your transfer job
// description = 'My transfer job'

// Azure Storage Account name
// azureStorageAccount = 'accountname'

// Azure Storage Account name
// azureSourceContainer = 'my-azure-source-bucket'

// Azure Shared Access Signature token
// azureSASToken = '?sv=...'

// Google Cloud Storage destination bucket name
// gcsSinkBucket = 'my-gcs-destination-bucket'

// Creates a client
const client = new StorageTransferServiceClient();

/**
 * Creates a one-time transfer job from Azure Blob Storage to Google Cloud Storage.
 */
async function transferFromBlobStorage() {
  // Setting the start date and the end date as the same time creates a
  // one-time transfer
  const now = new Date();
  const oneTimeSchedule = {
    day: now.getDate(),
    month: now.getMonth() + 1,
    year: now.getFullYear(),
  };

  // Runs the request and creates the job
  const [transferJob] = await client.createTransferJob({
    transferJob: {
      projectId,
      description,
      status: 'ENABLED',
      schedule: {
        scheduleStartDate: oneTimeSchedule,
        scheduleEndDate: oneTimeSchedule,
      },
      transferSpec: {
        azureBlobStorageDataSource: {
          azureCredentials: {
            sasToken: azureSASToken,
          },
          container: azureSourceContainer,
          storageAccount: azureStorageAccount,
        },
        gcsDataSink: {
          bucketName: gcsSinkBucket,
        },
      },
    },
  });

  console.log(
    `Created and ran a transfer job from '${azureSourceContainer}' to '${gcsSinkBucket}' with name ${transferJob.name}`
  );
}

transferFromBlobStorage();

Python

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

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

from datetime import datetime

from google.cloud import storage_transfer

def create_one_time_azure_transfer(
    project_id: str,
    description: str,
    azure_storage_account: str,
    azure_sas_token: str,
    source_container: str,
    sink_bucket: str,
):
    """Creates a one-time transfer job from Azure Blob Storage to Google Cloud
    Storage."""

    # Initialize client that will be used to create storage transfer requests.
    # This client only needs to be created once, and can be reused for
    # multiple requests.
    client = storage_transfer.StorageTransferServiceClient()

    # The ID of the Google Cloud Platform Project that owns the job
    # project_id = 'my-project-id'

    # A useful description for your transfer job
    # description = 'My transfer job'

    # Azure Storage Account name
    # azure_storage_account = 'accountname'

    # Azure Shared Access Signature token
    # azure_sas_token = '?sv=...'

    # Azure Blob source container name
    # source_container = 'my-azure-source-bucket'

    # Google Cloud Storage destination bucket name
    # sink_bucket = 'my-gcs-destination-bucket'

    now = datetime.utcnow()
    # Setting the start date and the end date as
    # the same time creates a one-time transfer
    one_time_schedule = {"day": now.day, "month": now.month, "year": now.year}

    transfer_job_request = storage_transfer.CreateTransferJobRequest(
        {
            "transfer_job": {
                "project_id": project_id,
                "description": description,
                "status": storage_transfer.TransferJob.Status.ENABLED,
                "schedule": {
                    "schedule_start_date": one_time_schedule,
                    "schedule_end_date": one_time_schedule,
                },
                "transfer_spec": {
                    "azure_blob_storage_data_source": {
                        "storage_account": azure_storage_account,
                        "azure_credentials": {"sas_token": azure_sas_token},
                        "container": source_container,
                    },
                    "gcs_data_sink": {
                        "bucket_name": sink_bucket,
                    },
                },
            }
        }
    )

    result = client.create_transfer_job(transfer_job_request)
    print(f"Created transferJob: {result.name}")

ファイル システムから転送する

この例では、POSIX ファイル システムから Cloud Storage バケットにファイルを移動する方法について学習します。

Go


import (
	"context"
	"fmt"
	"io"

	storagetransfer "cloud.google.com/go/storagetransfer/apiv1"
	"cloud.google.com/go/storagetransfer/apiv1/storagetransferpb"
)

func transferFromPosix(w io.Writer, projectID string, sourceAgentPoolName string, rootDirectory string, gcsSinkBucket string) (*storagetransferpb.TransferJob, error) {
	// Your project id
	// projectId := "myproject-id"

	// The agent pool associated with the POSIX data source. If not provided, defaults to the default agent
	// sourceAgentPoolName := "projects/my-project/agentPools/transfer_service_default"

	// The root directory path on the source filesystem
	// rootDirectory := "/directory/to/transfer/source"

	// The ID of the GCS bucket to transfer data to
	// gcsSinkBucket := "my-sink-bucket"

	ctx := context.Background()
	client, err := storagetransfer.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storagetransfer.NewClient: %w", err)
	}
	defer client.Close()

	req := &storagetransferpb.CreateTransferJobRequest{
		TransferJob: &storagetransferpb.TransferJob{
			ProjectId: projectID,
			TransferSpec: &storagetransferpb.TransferSpec{
				SourceAgentPoolName: sourceAgentPoolName,
				DataSource: &storagetransferpb.TransferSpec_PosixDataSource{
					PosixDataSource: &storagetransferpb.PosixFilesystem{RootDirectory: rootDirectory},
				},
				DataSink: &storagetransferpb.TransferSpec_GcsDataSink{
					GcsDataSink: &storagetransferpb.GcsData{BucketName: gcsSinkBucket},
				},
			},
			Status: storagetransferpb.TransferJob_ENABLED,
		},
	}

	resp, err := client.CreateTransferJob(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("failed to create transfer job: %w", err)
	}
	if _, err = client.RunTransferJob(ctx, &storagetransferpb.RunTransferJobRequest{
		ProjectId: projectID,
		JobName:   resp.Name,
	}); err != nil {
		return nil, fmt.Errorf("failed to run transfer job: %w", err)
	}
	fmt.Fprintf(w, "Created and ran transfer job from %v to %v with name %v", rootDirectory, gcsSinkBucket, resp.Name)
	return resp, nil
}

Java

import com.google.storagetransfer.v1.proto.StorageTransferServiceClient;
import com.google.storagetransfer.v1.proto.TransferProto;
import com.google.storagetransfer.v1.proto.TransferTypes.GcsData;
import com.google.storagetransfer.v1.proto.TransferTypes.PosixFilesystem;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferJob;
import com.google.storagetransfer.v1.proto.TransferTypes.TransferSpec;
import java.io.IOException;

public class TransferFromPosix {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your project id
    String projectId = "my-project-id";

    // The agent pool associated with the POSIX data source. If not provided, defaults to the
    // default agent
    String sourceAgentPoolName = "projects/my-project-id/agentPools/transfer_service_default";

    // The root directory path on the source filesystem
    String rootDirectory = "/directory/to/transfer/source";

    // The ID of the GCS bucket to transfer data to
    String gcsSinkBucket = "my-sink-bucket";

    transferFromPosix(projectId, sourceAgentPoolName, rootDirectory, gcsSinkBucket);
  }

  public static void transferFromPosix(
      String projectId, String sourceAgentPoolName, String rootDirectory, String gcsSinkBucket)
      throws IOException {
    TransferJob transferJob =
        TransferJob.newBuilder()
            .setProjectId(projectId)
            .setTransferSpec(
                TransferSpec.newBuilder()
                    .setSourceAgentPoolName(sourceAgentPoolName)
                    .setPosixDataSource(
                        PosixFilesystem.newBuilder().setRootDirectory(rootDirectory).build())
                    .setGcsDataSink(GcsData.newBuilder().setBucketName(gcsSinkBucket).build()))
            .setStatus(TransferJob.Status.ENABLED)
            .build();

    // 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,
    // or use "try-with-close" statement to do this automatically.
    try (StorageTransferServiceClient storageTransfer = StorageTransferServiceClient.create()) {

      // Create the transfer job
      TransferJob response =
          storageTransfer.createTransferJob(
              TransferProto.CreateTransferJobRequest.newBuilder()
                  .setTransferJob(transferJob)
                  .build());

      System.out.println(
          "Created a transfer job from "
              + rootDirectory
              + " to "
              + gcsSinkBucket
              + " with "
              + "name "
              + response.getName());
    }
  }
}

Node.js


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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// Your project id
// const projectId = 'my-project'

// The agent pool associated with the POSIX data source. Defaults to the default agent
// const sourceAgentPoolName = 'projects/my-project/agentPools/transfer_service_default'

// The root directory path on the source filesystem
// const rootDirectory = '/directory/to/transfer/source'

// The ID of the GCS bucket to transfer data to
// const gcsSinkBucket = 'my-sink-bucket'

// Creates a client
const client = new StorageTransferServiceClient();

/**
 * Creates a request to transfer from the local file system to the sink bucket
 */
async function transferDirectory() {
  const createRequest = {
    transferJob: {
      projectId,
      transferSpec: {
        sourceAgentPoolName,
        posixDataSource: {
          rootDirectory,
        },
        gcsDataSink: {bucketName: gcsSinkBucket},
      },
      status: 'ENABLED',
    },
  };

  // Runs the request and creates the job
  const [transferJob] = await client.createTransferJob(createRequest);

  const runRequest = {
    jobName: transferJob.name,
    projectId: projectId,
  };

  await client.runTransferJob(runRequest);

  console.log(
    `Created and ran a transfer job from '${rootDirectory}' to '${gcsSinkBucket}' with name ${transferJob.name}`
  );
}

transferDirectory();

Python

from google.cloud import storage_transfer

def transfer_from_posix_to_gcs(
    project_id: str,
    description: str,
    source_agent_pool_name: str,
    root_directory: str,
    sink_bucket: str,
):
    """Create a transfer from a POSIX file system to a GCS bucket."""

    client = storage_transfer.StorageTransferServiceClient()

    # The ID of the Google Cloud Platform Project that owns the job
    # project_id = 'my-project-id'

    # A useful description for your transfer job
    # description = 'My transfer job'

    # The agent pool associated with the POSIX data source.
    # Defaults to 'projects/{project_id}/agentPools/transfer_service_default'
    # source_agent_pool_name = 'projects/my-project/agentPools/my-agent'

    # The root directory path on the source filesystem
    # root_directory = '/directory/to/transfer/source'

    # Google Cloud Storage sink bucket name
    # sink_bucket = 'my-gcs-sink-bucket'

    transfer_job_request = storage_transfer.CreateTransferJobRequest(
        {
            "transfer_job": {
                "project_id": project_id,
                "description": description,
                "status": storage_transfer.TransferJob.Status.ENABLED,
                "transfer_spec": {
                    "source_agent_pool_name": source_agent_pool_name,
                    "posix_data_source": {
                        "root_directory": root_directory,
                    },
                    "gcs_data_sink": {"bucket_name": sink_bucket},
                },
            }
        }
    )

    result = client.create_transfer_job(transfer_job_request)
    print(f"Created transferJob: {result.name}")