首页 > 解决方案 > 如何在具有两个不同项目 gcp 的 2 个存储桶之间自动复制文件?

问题描述

实际上我使用该命令,并且效果很好:

gsutil cp gs:/bucket1/file.xml gs://bucket2/destination_folder

(bucket1 在 GCP 的 project1 中,bucket2 在 GCP 的另一个项目中)

但是我想每天早上 9 点执行该命令,我怎样才能在我的 GCP 项目中以简单的方式执行该命令?

编辑:它将每天一遍又一遍地从源存储桶复制文件到目标存储桶(这两个存储桶分别位于不同的项目中)。(实际上,当文件到达目标存储桶时,它会自动在 bigquery 中消耗和摄取,我只想触发我的命令 gsutil 并停止每天早上手动执行)

(数据传输的方法除外,因为我没有源项目的权限,所以我无法激活数据传输的服务帐户,我只有目标项目的权限。)

祝贺你,

实际上我可以将一个文件从一个存储桶复制到另一个存储桶到一个特定的文件夹(RQ:2个存储桶在同一个gcp项目上)我没有到达使用gs://的第二种方法

编辑2:

import base64
import  sys
import urllib.parse
# Imports the Google Cloud client library , dont forget the requirement or else it's ko
from google.cloud import storage


def copy_blob(
    bucket_name ="prod-data", blob_name="test.csv", destination_bucket_name = "prod-data-f", destination_blob_name ="channel_p"
):
    """Copies a blob from one bucket to another with a new name."""
    bucket_name = "prod-data"
    blob_name = "test.csv"
    destination_bucket_name = "prod-data-f"
    destination_blob_name = "channel_p/test.csv"

    storage_client = storage.Client()

    source_bucket = storage_client.bucket(bucket_name)
    source_blob = source_bucket.blob("huhu/"+blob_name)
    destination_bucket = storage_client.bucket(destination_bucket_name)

    blob_copy = source_bucket.copy_blob(
        source_blob, destination_bucket, destination_blob_name
    )

# Second Method (KO)
#
#   client = storage.Client()
#   with open('gs://prod-data-f/channelp.xml','wb') as file_obj:
#       client.download_blob_to_file(
#           'gs://pathsource/somefolder/channelp.xml', file_obj)
#
# End of second Method

    print(
        "Blob {} in bucket {} copied to blob {} in bucket {}.".format(
            source_blob.name,
            source_bucket.name,
            blob_copy.name,
            destination_bucket.name,
        )
    )

标签: google-cloud-platformcloudstoragebucket

解决方案


数据传输显然是执行此操作的正确工具,但由于您无法使用它,因此还有其他解决方案。

其中之一是使用 Cloud Function 复制文件(您可以使用此代码段),并在每天上午 9 点使用Cloud Scheduler触发该 Cloud Function 。Cloud Function 也可以由 Pub/Sub 消息触发。


推荐阅读