0

I wanted to execute a cloud function whenever a file is dropped in the bucket (see the below code). Further this cloud function should start a VM instance.

def startVMInstance(event, context):
  file = event
  if (file['name'] == 'test1.csv'):
      print('Starting VM Instnace')
      request = context.instances().start(project ='proj-name', zone ='zone-info', instance ='VMlabel')
         response = request.execute(event)
         print(response)

When I run this code, I do get successful execution of the trigger event, when the file is added. but its giving me below error message

AttributeError: 'Context' object has no attribute 'instances'

I am only familiar with python, and could not find any resource which can help me write this functionality in my code.

It would be great if I some one can point out where I am going wrong and what libraries I am missing from my code to make it work.

ps: I haven't included any libraries in my code as of yet, as I don't know which once I will need.

user570778
  • 21
  • 2

1 Answers1

2

It turned out I need to include 'googleapiclient' for importing library 'discovery' below is the code will allowed me to start my VM instance

To dry run through the code. This is the code for a Google Cloud function which is executed when ever a file is added to the bucket. It checks if its the right file. If it is then starts the VM instance which will further process the uploaded file.

from googleapiclient import discovery

service = discovery.build('compute', 'v1')

def hello_gcs(event, context):
    """Triggered by a change to a Cloud Storage bucket.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    file = event
    print(f"Processing file: {file['name']}.")

    # Trigger VM start only if the correct file is uploaded
    if (file['name'] == 'test1.csv') :         

         print('VM Instance starting')

         # Project ID for this request.
         project = 'project_name' 

         # The name of the zone for this request.
         zone = 'zone_value'  

         # Name of the instance resource to start.
         instance = 'instance_name'

         request = service.instances().start(project=project, zone=zone, instance=instance)
         response = request.execute()

         print('VM Instance started')
user570778
  • 21
  • 2