Search code examples
google-cloud-platformgoogle-compute-enginehigh-availability

Is it possible to instantiate a new VM on GCP using Google Cloud Function and Regional Managed Instance?


basically what I trying to do is creating a message on Pub/Sub that triggers a GCF which creates a instance from a Regional Managed Instance Group in whatever available zone it has at the time.

The issue I'm trying to solve here is a rather recurrent ZONE_RESOURCE_POOL_EXHAUSTED which the regional MIG deals with.

Is this solution possible? I've tried using createInstances method but Logging just states PRECONDITION_FAILED.

The code snippet I'm using is as follows:

from googleapiclient import discovery
def launch_vm(project, region, igm, body)
    service = discovery.build('compute', 'v1')
    response = service.regionInstanceGroupManagers()\
               .createInstances(
                   project=project,
                   region=region,
                   instanceGroupManager=igm,
                   body=body)
    return response.execute()

request_body = {"instances":[{"name": "testinstance"}]}

launch_vm('project-name', 'us-central1', 'instace-group-name', request_body)

####### EDIT : I just found out what happened, when I tried on another project with a recently created instance group, I found out that instance redistribution was enabled, which can NOT be the case as with the response from the CLI:

ERROR: (gcloud.compute.instance-groups.managed.create-instance) CreateInstances can be used only when instance redistribution is disabled (set to NONE).

I checked out the instance redistribution check and now it works wonders :) Thanks everyone for the help!


Solution

  • I'm able to createInstance:

    import os
    
    from googleapiclient import discovery
    
    
    PROJECT = os.environ["PROJECT"]
    REGION = os.environ["REGION"]
    NAME = os.environ["NAME"]
    
    service = discovery.build('compute', 'v1')
    
    def launch_vm(project,region, name, body):
        rqst = service.regionInstanceGroupManagers().createInstances(
                       project=project,
                       region=region,
                       instanceGroupManager=name,
                       body=body)
        return rqst.execute()
    
    
    body = {
        "instances": [
            {
                "name": "testinstance"
            }
        ]
    }
    
    launch_vm(PROJECT, REGION, NAME, body)