Crea trasferimenti

Questa pagina mostra come creare e avviare job di trasferimento.

Per verificare se l'origine e la destinazione (nota anche come sink) sono supportate da Storage Transfer Service, consulta l'articolo Origini e sink supportati.

Agenti e pool di agenti

A seconda dell'origine e della destinazione, potrebbe essere necessario creare e configurare un pool di agenti e installare agenti su una macchina con accesso all'origine o alla destinazione.

  • I trasferimenti da Amazon S3, Microsoft Azure, elenchi di URL o Cloud Storage a Cloud Storage non richiedono agenti e pool di agenti.

  • I trasferimenti la cui origine e/o destinazione è un file system o dallo spazio di archiviazione compatibile con S3 richiedono agenti e pool di agenti. Per le istruzioni, consulta Gestire i pool di agenti.

Prima di iniziare

Prima di configurare i trasferimenti, assicurati di aver configurato l'accesso:

Se utilizzi i comandi gcloud, installa gcloud CLI.

Crea un trasferimento

Non includere informazioni sensibili come informazioni che consentono l'identificazione personale o dati di sicurezza nel nome del job di trasferimento. I nomi delle risorse possono essere propagati ai nomi di altre risorse Google Cloud ed essere esposti ai sistemi interni di Google al di fuori del tuo progetto.

Console Google Cloud

  1. Vai alla pagina Storage Transfer Service nella console Google Cloud.

    Vai a Storage Transfer Service

  2. Fai clic su Crea job di trasferimento. Viene visualizzata la pagina Crea un job di trasferimento.

  3. Scegli un'origine:

    Cloud Storage

    Il tuo account utente deve disporre dell'autorizzazione storage.buckets.get per selezionare i bucket di origine e di destinazione. In alternativa, puoi digitare direttamente il nome del bucket. Per maggiori informazioni, consulta Risoluzione dei problemi di accesso.

    1. In Tipo di origine, seleziona Cloud Storage.

    2. Seleziona il Tipo di destinazione.

    3. Se la tua destinazione è Cloud Storage, seleziona la modalità di pianificazione. I trasferimenti batch vengono eseguiti una tantum o pianificati. I trasferimenti basati su eventi monitorano continuamente l'origine e trasferiscono i dati quando vengono aggiunti o modificati.

      Per configurare un trasferimento basato su eventi, segui le istruzioni in Trasferimenti basati su eventi.

    4. Fai clic su Passaggio successivo.

    5. Seleziona un bucket e, facoltativamente, una cartella nel bucket in uno dei seguenti modi:

      • Inserisci il nome e il percorso di un bucket Cloud Storage esistente nel campo Bucket o cartella senza il prefisso gs://. Ad esempio: my-test-bucket/path/to/files. Per specificare un bucket Cloud Storage da un altro progetto, digita il nome esattamente nel campo Nome bucket.

      • Seleziona un elenco dei bucket esistenti nei tuoi progetti facendo clic su Sfoglia e selezionando un bucket.

        Quando fai clic su Sfoglia, puoi selezionare bucket in altri progetti facendo clic sull'ID progetto e poi selezionando il nuovo ID progetto e il nuovo bucket.

      • Per creare un nuovo bucket, fai clic su Crea nuovo bucket.

    6. Se si tratta di un trasferimento basato su eventi, inserisci il nome della sottoscrizione Pub/Sub, che avrà il seguente formato:

      projects/PROJECT_NAME/subscriptions/SUBSCRIPTION_ID
      
    7. Facoltativamente, scegli di filtrare gli oggetti per prefisso o per data dell'ultima modifica. Se hai specificato una cartella come posizione di origine, i filtri per il prefisso sono relativi a quella cartella. Ad esempio, se l'origine è my-test-bucket/path/, un filtro di inclusione di file include tutti i file che iniziano con my-test-bucket/path/file.
    8. Fai clic su Passaggio successivo.

    Amazon S3

    1. In Tipo di origine, seleziona Amazon S3.

    2. Come Tipo di destinazione, seleziona Google Cloud Storage.

    3. Seleziona la modalità di pianificazione. I trasferimenti batch vengono eseguiti una tantum o pianificati. I trasferimenti basati su eventi monitorano continuamente l'origine e trasferiscono i dati quando vengono aggiunti o modificati.

      Per configurare un trasferimento basato su eventi, segui le istruzioni in Trasferimenti basati su eventi.

    4. Fai clic su Passaggio successivo.

    5. Nel campo Nome bucket o cartella, inserisci il nome del bucket di origine.

      Il nome del bucket è il nome visualizzato nella Console di gestione AWS.

    6. Se utilizzi una distribuzione CloudFront per il trasferimento da S3, inserisci il nome del dominio di distribuzione nel campo Dominio CloudFront. Ad esempio, https://dy1h2n3l4ob56.cloudfront.net. Consulta Trasferimento da S3 tramite CloudFront per configurare una distribuzione CloudFront.

    7. Seleziona il metodo di autenticazione di Amazon Web Services (AWS). Puoi fornire una chiave di accesso AWS o un Amazon Resource Name (ARN) per la federazione delle identità:

      • Chiave di accesso: inserisci la chiave di accesso nel campo ID chiave di accesso e il secret associato alla chiave di accesso nel campo Chiave di accesso segreta.

      • ARN: inserisci il tuo ARN nel campo ARN del ruolo AWS IAM con la seguente sintassi:

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

        Dove:

        • ACCOUNT: l'ID account AWS senza trattini.
        • ROLE-NAME-WITH-PATH: il nome del ruolo AWS, incluso il percorso.

        Per ulteriori informazioni sugli ARN, consulta la pagina IAM ARN.

    8. Se si tratta di un trasferimento basato su eventi, inserisci l'ARN della coda di Amazon SQS, che avrà il formato seguente:

      arn:aws:sqs:us-east-1:1234567890:event-queue
      
    9. Facoltativamente, scegli di filtrare gli oggetti per prefisso o per data dell'ultima modifica. Se hai specificato una cartella come posizione di origine, i filtri per il prefisso sono relativi a quella cartella. Ad esempio, se l'origine è my-test-bucket/path/, un filtro di inclusione di file include tutti i file che iniziano con my-test-bucket/path/file.
    10. Fai clic su Passaggio successivo.

    Spazio di archiviazione compatibile con S3

    1. In Tipo di origine, seleziona Archiviazione di oggetti compatibile con S3.

    2. Fai clic su Passaggio successivo.

    3. Specifica le informazioni richieste per questo trasferimento:

      1. Seleziona il pool di agenti che hai configurato per questo trasferimento.

      2. Inserisci il Nome bucket relativo all'endpoint. Ad esempio, se i tuoi dati si trovano in:

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

        Inserisci: folder1/bucket_a

      3. Inserisci l'Endpoint. Non includere il protocollo (http:// o https://). Nell'esempio del passaggio precedente, dovrai inserire:

        us-east-1.example.com

    4. Specifica eventuali attributi facoltativi per questo trasferimento:

      1. Inserisci la Regione firma da utilizzare per la firma delle richieste. Lascia vuoto questo campo se l'origine non richiede una regione di firma.

      2. Scegli la procedura di firma per questa richiesta.

      3. Seleziona lo Stile di indirizzamento. Questo determina se il nome del bucket è fornito in stile percorso (ad es. https://s3.region.example.com/bucket-name/key-name) o in stile ospitato virtuale (ad es. https://bucket-name.s3.region.example.com/key-name). Per ulteriori informazioni, leggi la pagina [Hosting virtuale dei bucket] nella documentazione di Amazon.

      4. Seleziona il Protocollo di rete.

      5. Seleziona la versione dell'API dell'elenco da utilizzare. Per ulteriori informazioni, consulta la documentazione ListObjectsV2 e ListObjects.

    5. Fai clic su Passaggio successivo.

    Archiviazione BLOB di Microsoft Azure

    1. In Tipo di origine, seleziona Archiviazione BLOB di Azure o Data Lake Storage Gen2.

    2. Fai clic su Passaggio successivo.

    3. Specifica quanto segue:

      1. Nome account di archiviazione: il nome dell'account Archiviazione Microsoft Azure di origine.

        Il nome dell'account di archiviazione viene visualizzato nel portale Archiviazione di Azure di Microsoft in Tutti i servizi > Archiviazione > Account di archiviazione.

      2. Nome contenitore: il nome del contenitore Archiviazione di Microsoft Azure.

        Il nome del container viene visualizzato nel portale Archiviazione di Microsoft Azure in Explorer Storage > Container BLOB.

      3. Firma di accesso condiviso (SAS): il token SAS di Microsoft Azure Storage creato da un criterio di accesso archiviato. Per maggiori informazioni, consulta Concedere l'accesso limitato alle risorse di archiviazione di Azure utilizzando le firme di accesso condiviso (SAS).

        La scadenza predefinita per i token SAS è 8 ore. Quando crei il token SAS, assicurati di impostare una scadenza ragionevole che consenta di completare il trasferimento.
    4. Facoltativamente, scegli di filtrare gli oggetti per prefisso o per data dell'ultima modifica. Se hai specificato una cartella come posizione di origine, i filtri per il prefisso sono relativi a quella cartella. Ad esempio, se l'origine è my-test-bucket/path/, un filtro di inclusione di file include tutti i file che iniziano con my-test-bucket/path/file.
    5. Fai clic su Passaggio successivo.

    File system

    1. In Tipo di origine, seleziona File system POSIX.

    2. Seleziona il Tipo di destinazione e fai clic su Passaggio successivo.

    3. Seleziona un pool di agenti esistente o seleziona Crea pool di agenti e segui le istruzioni per creare un nuovo pool.

    4. Specifica il percorso completo della directory del file system.

    5. Fai clic su Passaggio successivo.

    HDFS

    Vedi Trasferimento da HDFS a Cloud Storage.

    Elenco URL

    1. In Tipo di origine, seleziona Elenco URL e fai clic su Passaggio successivo.

    2. In URL del file TSV, fornisci l'URL di un file con valori separati da tabulazioni (TSV). Consulta la pagina Creazione di un elenco di URL per informazioni dettagliate su come creare il file TSV.

    3. Facoltativamente, scegli di filtrare gli oggetti per prefisso o per data dell'ultima modifica. Se hai specificato una cartella come posizione di origine, i filtri per il prefisso sono relativi a quella cartella. Ad esempio, se l'origine è my-test-bucket/path/, un filtro di inclusione di file include tutti i file che iniziano con my-test-bucket/path/file.
    4. Fai clic su Passaggio successivo.

  4. Scegli una destinazione:

    Cloud Storage

    1. Nel campo Bucket o cartella, inserisci il bucket di destinazione e, facoltativamente, il nome della cartella oppure fai clic su Sfoglia per selezionare un bucket da un elenco di bucket esistenti nel progetto attuale. Per creare un nuovo bucket, fai clic su Crea nuovo bucket.

    2. Fai clic su Passaggio successivo.

    3. Scegli le impostazioni per il job di trasferimento. Alcune opzioni sono disponibili solo per determinate combinazioni di origine/sink.

      1. Nel campo Description (Descrizione), inserisci una descrizione del trasferimento. Come best practice, inserisci una descrizione significativa e univoca in modo da poter distinguere i job.

      2. In Opzioni dei metadati, scegli di utilizzare le opzioni predefinite oppure fai clic su Visualizza e seleziona opzioni per specificare i valori di tutti i metadati supportati. Per i dettagli, consulta Conservazione dei metadati.

      3. In Quando sovrascrivere, seleziona una delle seguenti opzioni:

        • Se diverso: sovrascrive i file di destinazione se il file di origine con lo stesso nome ha valori Etag o checksum diversi.

        • Sempre: sovrascrive sempre i file di destinazione quando il file di origine ha lo stesso nome, anche se sono identici.

      4. In Quando eliminare, seleziona una delle seguenti opzioni:

        • Mai: non eliminare mai i file dall'origine o dalla destinazione.

        • Elimina file dall'origine dopo il trasferimento: elimina i file dall'origine dopo che sono stati trasferiti alla destinazione.

        • Elimina i file dalla destinazione se non sono anche nell'origine: se i file nel bucket Cloud Storage di destinazione non sono anche nell'origine, eliminali dal bucket Cloud Storage.

          Questa opzione garantisce che il bucket Cloud Storage di destinazione corrisponda esattamente all'origine.

      5. In Opzioni di notifica, seleziona l'argomento Pub/Sub e gli eventi per i quali inviare notifiche. Per ulteriori dettagli, consulta la pagina relativa alle notifiche Pub/Sub.

    4. Fai clic su Passaggio successivo.

    File system

    1. Seleziona un pool di agenti esistente o seleziona Crea pool di agenti e segui le istruzioni per creare un nuovo pool.

    2. Specifica il percorso completo della directory di destinazione.

    3. Fai clic su Passaggio successivo.

  5. Scegli le opzioni di pianificazione:

    1. Nell'elenco a discesa Esegui una volta, seleziona una delle seguenti opzioni:

      • Esegui una volta: esegue un singolo trasferimento, a partire dal momento selezionato da te.

      • Esegui ogni giorno: esegue un trasferimento ogni giorno, a partire dall'ora selezionata.

        Puoi inserire una Data di fine facoltativa o lasciare vuoto il campo Data di fine per eseguire il trasferimento continuamente.

      • Esegui ogni settimana: esegue un trasferimento ogni settimana, a partire dall'ora selezionata.

      • Esegui con una frequenza personalizzata: esegue un trasferimento con una frequenza selezionata da te. Puoi scegliere di ripetere il trasferimento a intervalli regolari di Ore, Giorni o Settimane.

        Puoi inserire una Data di fine facoltativa o lasciare vuoto il campo Data di fine per eseguire il trasferimento continuamente.

    2. Dall'elenco a discesa Inizia ora, seleziona una delle seguenti opzioni:

      • Inizia ora: avvia il trasferimento dopo aver fatto clic su Crea.

      • A partire dal giorno: avvia il trasferimento nella data e nell'ora selezionate. Fai clic su Calendario per visualizzare un calendario in cui selezionare la data di inizio.

    3. Per creare il job di trasferimento, fai clic su Crea.

Interfaccia a riga di comando gcloud

Per creare un nuovo job di trasferimento, utilizza il comando gcloud transfer jobs create. La creazione di un nuovo job avvia il trasferimento specificato, a meno che non venga specificata una pianificazione o un --do-not-run.

gcloud transfer jobs create \
  SOURCE DESTINATION

Dove:

  • SOURCE è l'origine dati per questo trasferimento. Il formato di ogni origine è:

    • Cloud Storage: gs://BUCKET_NAME Per eseguire il trasferimento da una cartella specifica, specifica gs://BUCKET_NAME/FOLDER_PATH/, inclusa la barra finale.
    • Amazon S3: s3://BUCKET_NAME/FOLDER_PATH
    • Spazio di archiviazione compatibile con S3: s3://BUCKET_NAME. Il nome del bucket è relativo all'endpoint. Ad esempio, se i tuoi dati si trovano in https://us-east-1.example.com/folder1/bucket_a, inserisci s3://folder1/bucket_a.
    • Archiviazione di Microsoft Azure: https://myaccount.blob.core.windows.net/CONTAINER_NAME
    • Elenco di URL: https://PATH_TO_URL_LIST o http://PATH_TO_URL_LIST
    • File system POSIX: posix:///PATH. Deve essere un percorso assoluto dalla directory principale della macchina host dell'agente.
    • HDFS: hdfs:///PATH
  • DESTINATION è uno dei seguenti:

    • Cloud Storage: gs://BUCKET_NAME Per effettuare il trasferimento in una directory specifica, specifica gs://BUCKET_NAME/FOLDER_PATH/, inclusa la barra finale.
    • File system POSIX: posix:///PATH. Deve essere un percorso assoluto dalla directory principale della macchina host dell'agente.

Se il trasferimento richiede agenti trasferiti, sono disponibili le seguenti opzioni:

  • --source-agent-pool specifica il pool di agenti di origine da utilizzare per questo trasferimento. Obbligatorio per i trasferimenti provenienti da un file system.

  • --destination-agent-pool specifica il pool di agenti di destinazione da utilizzare per questo trasferimento. Obbligatorio per i trasferimenti a un file system.

  • --intermediate-storage-path è il percorso di un bucket Cloud Storage, nel formato gs://my-intermediary-bucket. Obbligatorio per i trasferimenti tra due file system. Per maggiori dettagli sulla creazione del bucket intermedio, consulta Creare un bucket Cloud Storage come intermediario.

Ecco alcune opzioni aggiuntive:

  • --source-creds-file specifica il percorso relativo a un file locale sulla tua macchina che include le credenziali AWS o Azure per l'origine del trasferimento. Per informazioni sulla formattazione dei file delle credenziali, consulta la documentazione di riferimento TransferSpec.

  • --do-not-run impedisce a Storage Transfer Service di eseguire il job all'invio del comando. Per eseguire il job, aggiornalo per aggiungere una pianificazione oppure utilizza jobs run per avviarlo manualmente.

  • --manifest-file specifica il percorso di un file CSV in Cloud Storage contenente un elenco di file da trasferire dalla tua origine. Per la formattazione dei file manifest, consulta Trasferire file o oggetti specifici utilizzando un manifest.

  • Informazioni job: puoi specificare --name, --description e --source-creds-file.

  • Pianificazione: specifica --schedule-starts, --schedule-repeats-every e --schedule-repeats-until o --do-not-run.

  • Condizioni degli oggetti: utilizza le condizioni per determinare quali oggetti vengono trasferiti. Questi includono --include-prefixes e --exclude-prefixes e le condizioni basate sul tempo in --include-modified-[before | after]-[absolute | relative]. Se hai specificato una cartella con la tua origine, i filtri per il prefisso sono relativi alla cartella. Per ulteriori informazioni, consulta Filtrare gli oggetti di origine in base al prefisso.

    Le condizioni degli oggetti non sono supportate per i trasferimenti che coinvolgono i file system.

  • Opzioni di trasferimento: specifica se sovrascrivere i file di destinazione (--overwrite-when=different o always) e se eliminare determinati file durante o dopo il trasferimento (--delete-from=destination-if-unique o source-after-transfer), specifica i valori dei metadati da conservare (--preserve-metadata) e, facoltativamente, imposta una classe di archiviazione per gli oggetti trasferiti (--custom-storage-class).

  • Notifiche: configura le notifiche Pub/Sub per i trasferimenti con --notification-pubsub-topic, --notification-event-types e --notification-payload-format.

  • Cloud Logging: abilita Cloud Logging per i trasferimenti senza agente o i trasferimenti da origini compatibili con S3, con --log-actions e --log-action-states. Per i dettagli, consulta Cloud Logging per Storage Transfer Service.

Anche i trasferimenti da origini compatibili con S3 utilizzano le seguenti opzioni:

  • --source-endpoint (obbligatorio) specifica l'endpoint del sistema di archiviazione. Ad esempio, s3.example.com. Rivolgiti al tuo fornitore per la formattazione corretta. Non specificare il protocollo (http:// o https://).
  • --source-signing-region specifica una regione per la firma delle richieste. Ometti questo flag se il tuo provider di archiviazione non richiede una regione di firma.
  • --source-auth-method specifica il metodo di autenticazione da utilizzare. I valori validi sono AWS_SIGNATURE_V2 o AWS_SIGNATURE_V4. Per ulteriori informazioni, consulta la documentazione di Amazon SigV4 e SigV2.
  • --source-request-model specifica lo stile di indirizzamento da utilizzare. I valori validi sono PATH_STYLE o VIRTUAL_HOSTED_STYLE. Lo stile del percorso utilizza il formato https://s3.example.com/BUCKET_NAME/KEY_NAME. Lo stile con hosting virtuale utilizza il formato "https://BUCKET_NAME.s3.example.com/KEY_NAME.
  • --source-network-protocol specifica il protocollo di rete che gli agenti devono utilizzare per questo job. I valori validi sono HTTP o HTTPS.
  • --source-list-api specifica la versione dell'API S3 che restituisce gli oggetti dal bucket. I valori validi sono LIST_OBJECTS o LIST_OBJECTS_V2. Per ulteriori informazioni, consulta la documentazione di Amazon ListObjectsV2 e ListObjects.

Per visualizzare tutte le opzioni, esegui gcloud transfer jobs create --help o fai riferimento alla documentazione di riferimento di gcloud.

Esempi

Da Amazon S3 a Cloud Storage

Esegui questo comando per creare un job di trasferimento giornaliero per spostare i dati modificati nell'ultimo giorno da s3://my-s3-bucket a un bucket Cloud Storage denominato my-storage-bucket:

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

Spazio di archiviazione compatibile con S3 in Cloud Storage

Per eseguire il trasferimento da un'origine compatibile con S3 a un bucket 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

Da file system in Cloud Storage

Per eseguire il trasferimento da un file system a un bucket Cloud Storage, specifica quanto segue.

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

Da Cloud Storage a file system

Per eseguire il trasferimento da un bucket Cloud Storage a un file system, specifica quanto segue.

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

Da file system a file system

Per eseguire il trasferimento tra due file system, devi specificare un pool di agenti di origine, un pool di agenti di destinazione e un bucket Cloud Storage intermedio attraverso il quale passano i dati.

Per maggiori dettagli sul bucket intermedio, consulta Creare un bucket Cloud Storage come intermediario.

Quindi specifica queste tre risorse durante la chiamata a transfer jobs create:

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

I seguenti esempi mostrano come utilizzare Storage Transfer Service tramite l'API REST.

Quando configuri o modifichi i job di trasferimento utilizzando l'API Storage Transfer Service, l'ora deve essere nel fuso orario UTC. Per ulteriori informazioni su come specificare la pianificazione di un job di trasferimento, consulta Pianificazione.

Trasferimento tra bucket Cloud Storage

In questo esempio, imparerai a spostare file da un bucket Cloud Storage a un altro. Ad esempio, puoi spostare i dati in un bucket in un'altra località.

Richiedi utilizzando 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
      }
  }
}
Risposta:
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
              }
          }
      }
  ]
}

Trasferimento da Amazon S3 a Cloud Storage

In questo esempio, imparerai come spostare file da Amazon S3 a un bucket Cloud Storage. Consulta gli articoli Configurare l'accesso ad Amazon S3 e Prezzi per comprendere le implicazioni dello spostamento dei dati da Amazon S3 a Cloud Storage.

Quando crei job di trasferimento, non includere il prefisso s3:// per bucketName nei nomi delle origini dei bucket Amazon S3.

Richiedi utilizzando 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"
      }
  }
}
Risposta:
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": {}
          }
      }
  ]
}

Se esegui il trasferimento da S3 tramite una distribuzione CloudFront, specifica il nome di dominio di distribuzione come valore del campo 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"
    }
  },
  ...
}

Trasferimento tra Microsoft Azure Blob Storage e Cloud Storage

In questo esempio, scoprirai come spostare file da Archiviazione di Microsoft Azure a un bucket Cloud Storage, utilizzando un token per la firma di accesso condivisa (SAS) di Microsoft Azure Storage.

Per maggiori informazioni sulla SAS per Archiviazione di Azure per Microsoft, consulta Concedere l'accesso limitato alle risorse di Archiviazione di Azure utilizzando le firme di accesso condiviso (SAS).

Prima di iniziare, consulta Configurare l'accesso ad Archiviazione di Microsoft Azure e Prezzi per comprendere le implicazioni dello spostamento dei dati da Microsoft Azure Storage a Cloud Storage.

Richiedi utilizzando 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"
      }
  }
}
Risposta:
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": {}
          }
      }
  ]
}

Trasferire da un file system

In questo esempio, scoprirai come spostare file da un file system POSIX a un bucket Cloud Storage.

Utilizza transferJobs.create con un posixDataSource:

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/"
     },
  }
}

Il campo schedule è facoltativo; se non è incluso, il job di trasferimento deve essere avviato con una richiesta transferJobs.run.

Per verificare lo stato del trasferimento dopo aver creato un job, utilizza transferJobs.get:

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

Specifica dei percorsi di origine e di destinazione

I percorsi di origine e di destinazione consentono di specificare le directory di origine e di destinazione durante il trasferimento dei dati nel bucket Cloud Storage. Ad esempio, supponiamo di avere i file file1.txt e file2.txt e un bucket Cloud Storage denominato B. Se imposti un percorso di destinazione denominato my-stuff, al termine del trasferimento i tuoi file si trovano in gs://B/my-stuff/file1.txt e gs://B/my-stuff/file2.txt.

Specificare un percorso di origine

Per specificare un percorso di origine durante la creazione di un job di trasferimento, aggiungi un campo path al campo gcsDataSource nella tua specifica TransferSpec:

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

In questo esempio:

  • SOURCE_BUCKET: il bucket Cloud Storage di origine.
  • SOURCE_PATH: il percorso Cloud Storage di origine.

Specificare un percorso di destinazione

Per specificare una cartella di destinazione quando crei un job di trasferimento, aggiungi un campo path al campo gcsDataSink nella tua specifica TransferSpec:

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

In questo esempio:

  • DESTINATION_BUCKET: il bucket Cloud Storage di destinazione.
  • DESTINATION_PATH: il percorso Cloud Storage di destinazione.

Esempio di richiesta completo

Di seguito è riportato un esempio di richiesta completa:

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
      }
  }

}

Librerie client

Gli esempi riportati di seguito mostrano come utilizzare Storage Transfer Service in modo programmatico con Go, Java, Node.js e Python.

Quando configuri o modifichi i job di trasferimento in modo programmatico, l'ora deve essere espressa nel fuso orario UTC. Per ulteriori informazioni su come specificare la pianificazione di un job di trasferimento, consulta Pianificazione.

Per ulteriori informazioni sulle librerie client di Storage Transfer Service, consulta la guida introduttiva alle librerie client di Storage Transfer Service.

Trasferimento tra bucket Cloud Storage

In questo esempio, imparerai a spostare file da un bucket Cloud Storage a un altro. Ad esempio, puoi spostare i dati in un bucket in un'altra località.

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

Stai cercando anteprime meno recenti? Consulta la guida alla migrazione di 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

Stai cercando anteprime meno recenti? Consulta la guida alla migrazione di 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}")

Trasferimento da Amazon S3 a Cloud Storage

In questo esempio, imparerai come spostare file da Amazon S3 a un bucket Cloud Storage. Consulta gli articoli Configurare l'accesso ad Amazon S3 e Prezzi per comprendere le implicazioni dello spostamento dei dati da Amazon S3 a Cloud Storage.

Quando crei job di trasferimento, non includere il prefisso s3:// per bucketName nei nomi delle origini dei bucket Amazon S3.

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

Stai cercando anteprime meno recenti? Consulta la guida alla migrazione di 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

Stai cercando anteprime meno recenti? Consulta la guida alla migrazione di 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}")

Trasferimento tra Microsoft Azure Blob Storage e Cloud Storage

In questo esempio, scoprirai come spostare file da Archiviazione di Microsoft Azure a un bucket Cloud Storage, utilizzando un token per la firma di accesso condivisa (SAS) di Microsoft Azure Storage.

Per maggiori informazioni sulla SAS per Archiviazione di Azure per Microsoft, consulta Concedere l'accesso limitato alle risorse di Archiviazione di Azure utilizzando le firme di accesso condiviso (SAS).

Prima di iniziare, consulta Configurare l'accesso ad Archiviazione di Microsoft Azure e Prezzi per comprendere le implicazioni dello spostamento dei dati da Microsoft Azure Storage a Cloud Storage.

Go

Per scoprire come installare e utilizzare la libreria client per Storage Transfer Service, consulta librerie client di Storage Transfer Service. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Storage Transfer Service.

Per eseguire l'autenticazione in Storage Transfer Service, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per scoprire come installare e utilizzare la libreria client per Storage Transfer Service, consulta librerie client di Storage Transfer Service. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Storage Transfer Service.

Per eseguire l'autenticazione in Storage Transfer Service, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per scoprire come installare e utilizzare la libreria client per Storage Transfer Service, consulta librerie client di Storage Transfer Service. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Storage Transfer Service.

Per eseguire l'autenticazione in Storage Transfer Service, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


// 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

Per scoprire come installare e utilizzare la libreria client per Storage Transfer Service, consulta librerie client di Storage Transfer Service. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Storage Transfer Service.

Per eseguire l'autenticazione in Storage Transfer Service, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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}")

Trasferire da un file system

In questo esempio, scoprirai come spostare file da un file system POSIX a un bucket 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}")