from google.cloud import storage
def create_bucket_if_not_exists(storage_client, bucket_name):
"""Create a GCP bucket if it doesn't already exist."""
bucket = storage_client.bucket(bucket_name)
if not bucket.exists():
bucket.create()
print(f"Bucket {bucket_name} created.")
else:
print(f"Bucket {bucket_name} already exists.")
def copy_bucket_contents(source_storage_client, target_storage_client, source_bucket_name, target_bucket_name):
"""Copy contents from the source bucket to the target bucket."""
source_bucket = source_storage_client.bucket(source_bucket_name)
target_bucket = target_storage_client.bucket(target_bucket_name)
blobs = source_bucket.list_blobs()
for blob in blobs:
source_blob = source_bucket.blob(blob.name)
target_bucket.copy_blob(source_blob, target_bucket, blob.name)
print("copy_bucket_contents done")
# Replace with your project names and bucket names
source_project = ''
target_project = ''
source_bucket_name = ''
target_bucket_name = ''
# Initialize clients for each project
source_storage_client = storage.Client(project=source_project)
target_storage_client = storage.Client(project=target_project)
create_bucket_if_not_exists(target_storage_client, target_bucket_name)
copy_bucket_contents(source_storage_client, target_storage_client, source_bucket_name, target_bucket_name)