Currently I am working on a light-weight PHP class which should help me to create, list and delete VM instances on Googles Compute Engine. While writing the class, I came across few issue I would like to share with you. In the following example I tried to create a micro instance, because didn’t need much computing power. As you probably know, here is how you can select the machine type via dashboard.
When I tried to create a micro instance via PHP API with the correct Machine Type I received the following error message.
1 |
Fatal error: Uncaught Google_Service_Exception: { "error": { "errors": [ { "domain": "global", "reason": "invalid", "message": "Invalid value for field 'resource.machineType': 'f1-micro'. The URL is malformed." } ], "code": 400, "message": "Invalid value for field 'resource.machineType': 'f1-micro'. The URL is malformed." } } |
Here is a part of a PHP file I am using for API connection tests.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php // Load https://github.com/googleapis/google-api-php-client require 'vendor/autoload.php'; ... // Authenticate $client = new Google_Client(); ... // Connect to Compute Engine Service $computeService = new Google_Service_Compute($client); ... // Update placeholder values $project = 'project-abc'; $zone = 'us-east1-b'; $instance = 'demo-project'; $machineType = 'f1-micro'; // Create instance inside project-abc $instanceName = 'my-first-instance'; $newInstance = new Google_Service_Compute_Instance(); $newInstance->setName($instanceName); $newInstance->setMachineType($machineType); $response = $computeService->instances->insert($project, $zone, $instanceName); |
As you can see, I set a string f1-micro which is obviously not valid. I double-checked the API guides and found this URL.
1 |
https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/machineTypes/{machineType} |
So I defined the value for the machine type as follows which has fixed the invalid value for field resource.machineType.
1 2 |
$machineType = sprintf('https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/%s', $project, $zone, $type); $newInstance->setMachineType($machineType); |