How to change Google Cloud instance type using Python update method

555 Views Asked by At

Using Python example from docs on insert method

from pprint import pprint

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()

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


project = 'my-project' 
zone = 'us-west1-a' 
instance_body = {
    # TODO: Add desired entries to the request body.
}

request = service.instances().update(project=project, zone=zone, body=instance_body)
response = request.execute()

# TODO: Change code below to process the `response` dict:
pprint(response)

I customize the instance_body variable to be

instance_body = {
    'name': 'my-vm-0001',
    'machineType':  'https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/e2-highcpu-32' % (project, zone)
}

But running the update() method

request = service.instances().update(project=project, zone=zone, body=instance_body)
response = request.execute()

raises TypeError: Missing required parameter "instance".

Is there a way to update the instance type using the update method? It appears changing the instancy type can be done using gcloud command:

gcloud compute instances set-machine-type my-vm-0001 --project my-project --zone=us-west1-a--machine-type=e2-highcpu-32
1

There are 1 best solutions below

1
alphanumeric On

The update method takes the same parameters defined in the instance_body variable as the insert method with an additional fingerprint one which should match the fingerprint of the instance that you can query by instance name.