cypherlock1010
cypherlock1010

Reputation: 53

Need help creating a GCP Machine Image using GCP Python Libraries

I'm trying to create a new machine image from a .tar.gz file in one of my storage buckets. Doing this through the console is easy enough, but I need to do this programmatically with Python for a project I'm working on.

I've found what I think is the correct sections on how to create the machine image, but without examples I'm a little lost. I am fairly new to Python to still learning. I looks like I can use the Class "MachineImagesClient" and the "insert" method to make this happen.

If anyone can give me a bit of an example of where to start it would be much appreciated.

https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.services.machine_images.MachineImagesClient#google_cloud_compute_v1_services_machine_images_MachineImagesClient_insert 2

Upvotes: 0

Views: 391

Answers (2)

cypherlock1010
cypherlock1010

Reputation: 53

Hurray! I was able to successfully create my image from the tar.gz file within my storage bucket. Thanks for the help everyone.

from pprint import pprint
import os
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

#Path to service account credentials JSON file for authentication
srvc_cred_path = "C:/pathtoserviceaccountcreds.json"
credentials = os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = srvc_cred_path

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

# Project ID
project = 'my_project_id'  

#Parameters for the new image- name, container type, and source path
image_body = {
  "name": "test-image",
  "rawDisk": {
  "containerType": "TAR",
  "source": "URL to my bucket containing the tar.gz file"
  }
}

#Send the request
request = service.images().insert(project=project, body=image_body)
response = request.execute()

pprint(response)

Upvotes: 1

cypherlock1010
cypherlock1010

Reputation: 53

Not necessarily an answer, but an important step. I was able to follow guidance from @Ferregina and create a custom image with the API Explorer. I was able to use a tar.gz file from my storage bucket and define it in the request parameters. The API Explorer gives an example in JavaScript after it successfully complete so my next step is to try and adopt that to Python. I will update the post once I have something. screenshot

Upvotes: 0

Related Questions