1
votes

I'm trying to create a cloud function using api, the source code will be provided in a zip archive which includes an index.js & package.json files. I have uploaded this archive to storage bucket and create a cloud function via API request but now I need to extract this zip archive to point out the source for cloud function, how can I achieve that?

Here's what I have done: From views.py

            sclient = storage.Client()
            bucket = sclient.get_bucket(func_obj.bucket)
            blob = bucket.blob(func_obj.sourceFile.name)
            print('Uploading archive...')
            print(blob.upload_from_filename(file_name))
name = "projects/{}/locations/us-central1/functions/{}".format(func_obj.project, func_obj.fname,)
            print(name)
            req_body = {
              "name": name,
              "entryPoint": func_obj.entryPoint,
              "timeout": "3.5s",
              "availableMemoryMb": func_obj.fmemory,
              # "sourceUploadUrl": upload_url,
              "sourceArchiveUrl": "gs://newer_bucket/func.zip",
              "httpsTrigger": {},
            }
            service = discovery.build('cloudfunctions', 'v1')
            func_api = service.projects().locations().functions()

            response = func_api.create(location='projects/' + func_obj.project + '/locations/us-central1',
                                                body=req_body).execute()

            pprint.pprint(response)
1

1 Answers

2
votes

According to the Cloud Function Docs, the request body for the functions.create REST endpoint must contain an instance of CloudFunction. One of the fields of a cloud function JSON resource, as you can see in the second link, is "sourceArchiveUrl" and it points to the zip archive which contains the function. From my understanding, you don't need to extract the zip archive for Google Cloud Functions to access the code. Check the non-REST API deployment of Cloud Functions; it requires the archive, not an extracted archive.

But anyway, there is no direct way to extract the archive inside the bucket. You will need to download/transfer the archive somewhere (i.e. local machine, Google Compute Engine VM instance, etc.), perform the extraction operation on it and upload the results back in the bucket. Why should you upload an archive to a Google Cloud Storage bucket if you are then required to extract it? Why not uploading the files?

You might wanna check this answer as well. Same question, different context.