In this article, we look to use Go to create a Google Compute Engine (GCE) instance of our choice. I’ll step through all code elements to ensure your code works too. For simplicity all the dependencies are held within a single function. I discovered that the existing Golang API did not offer much help with this, so we shall use REST API calls to do this. Here is a gist that I have, broken into 8 steps.

Step 1: Initialization: Place all your initialization parameters within these variables, such as the projectId and the zone . You can pass the accessToken as a parameter or if you are in a testing scenario and need an accessToken immediately, follow the OAuth Playground hosted by Google, and select the compute engine scope. Follow the instructions and you should receive the accessToken

Step 2 & 3: The request body: Use the struct template provided in the gist as the request body. This is just a basic version, and you can follow this link for a list of more parameters. Do not forget to add the JSON struct tags that will convert the struct into appropriate JSON format.

Step 4: Marshal the Request Body: Use the JSON library to marshal the struct into binary representation of JSON.

Step 5: Build a HTTP request: Use the HTTP library to create a new request and pass in the binary request body as the last parameter. It should be wrapped in a string as shown in the gist.

Step 6: HTTP Headers: You must set the authorization header otherwise Google will throw a 401-Not Authorized error at you. Make sure you obtained the accessToken in Step 1

Step 7: Run the Request: To run the request use an existing HTTP client, or the default one as showed in the gist.

Step 8: Read the Response: Read the response that came from the HTTP request. Use ioutil.ReadAll() to read the response body. The output is shown in the commented section at the bottom of the gist.

Step 9: Check your GCP console

All the best with your work!