I am newbie to GCP, have experience with Python. I tried to write a Cloud Function for a scenario to untar files in GCS and copy them to another bucket.
from google.cloud import storage
import tarfile
client = storage.Client()
def untar_lookupfiles(data, context):
# Get the file that has been uploaded to GCS
bucket = client.get_bucket(data['Source_bucketName'])
#copy the tarfiles to another bucket
bucket = client.get_bucket('Target_bucketName')
blob = bucket.blob('gs://path/to/file.name')
blob.upload_from_filename('/path/to/source.file')
# Untar the files
print('Untaring Files: {}'.format(data['name']))
untar = tarfile.open("marfiles.tar.gz", "r:gz") # filename is hard coded should be replaced with data['name']
untar.extractall(path=dir)
But it looks like something is missing in this code, can someone help me with the code. I don't have experience with nodejs to write the code. Appreciate your help.
Here's a function that will untar a file placed in one bucket and put the contents in another bucket:
In requirements.txt:
google-cloud-storage
In main.py:
import io
import os
import tarfile
from google.cloud import storage
client = storage.Client()
input_bucket = client.get_bucket('INPUT-BUCKET-NAME')
output_bucket = client.get_bucket('OUTPUT-BUCKET-NAME')
def untar(data, context):
# Get the contents of the uploaded file
input_blob = input_bucket.get_blob(data['name']).download_as_string()
# Turn the upload file into a tar file
tar = tarfile.open(fileobj=io.BytesIO(input_blob))
# Iterate over all files in the tar file
for member in tar.getnames():
# Extract the individual file
file_object = tar.extractfile(member)
# Check if it's a file or directory (which should be skipped)
if file_object:
# Create a new blob instance in the output bucket
output_blob = output_bucket.blob(os.path.join(data['name'], member))
# Write the contents of the file to the output blob
output_blob.upload_from_string(file_object.read())
To deploy:
$ gcloud beta functions deploy test \
--runtime python37 \
--project PROJECT_NAME \
--trigger-resource INPUT_BUCKET_NAME \
--trigger-event google.storage.object.finalize
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With