Turge
Turge

Reputation: 1

Saving virtual machine into an image using azure python sdk

I have been working with Microsoft Azure to build virtual machines using the Azure SDK for Python, and now I want to create a managed image from an existing virtual machine.

I saw that there is a way to do it in power shell here

But after a long research i didn't find how to do it in python sdk. My goal is to be able to save a virtual machine into an image and load it afterwards (I'm using the ARM and not the ASM).

Upvotes: 0

Views: 1118

Answers (2)

ShaiB
ShaiB

Reputation: 111

After a long time trying to figure this out I was finally able to capture an image from a vm. firstly, the vm needs to be dealocated and generalized:

# Deallocate
async_vm_deallocate = self.compute_client.virtual_machines.deallocate(resource_group.name, names.vm)
async_vm_deallocate.wait()

# Generalize (possible because deallocated)
self.compute_client.virtual_machines.generalize(resource_group.name, names.vm)

I found that there are 2 options to creating the image:

  1. compute_client.virtual_machines.capture(resource_group_name=resource_group.name, vm_name=vm.name, parameters=parameters)

this way requires creating a ComputeManagmentClient and the following import:

from azure.mgmt.compute.v2015_06_15.models import VirtualMachineCaptureParameters

the parameters have to be object type: ~azure.mgmt.compute.v2015_06_15.models.VirtualMachineCaptureParameters.

The object VirtualMachineCaptureParameters has 3 required params: vhd_name_prefix (str), destination container name (str), overwrite vhds (bool)

what these are, I have no idea and there is no explanation as to what they are. so I didnt use this way

  1. (the way I choose to use) compute_client.images.create_or_update(resource_group_name=resource_group, image_name=unique_name, parameters=params)

this way requires creating a ComputeManagmentClient and the following import:

from azure.mgmt.compute.v2020_06_01.models import Image, SubResource

and it is pretty straight forward

sub_resource = SubResource(id=vm.id)
params = Image(location=LOCATION, source_virtual_machine=sub_resource)
i = compute_client.images.create_or_update(resource_group_name=resource_group, image_name=image_name, parameters=params)
i.wait()

creating the SubResource() and the Image() objects is mandatory as that is the object type expected

Upvotes: 1

Laurent Mazuel
Laurent Mazuel

Reputation: 3546

Create a compute client:

Deallocate and generalize:

    # Deallocate
    async_vm_deallocate = self.compute_client.virtual_machines.deallocate(resource_group.name, names.vm)
    async_vm_deallocate.wait()

    # Generalize (possible because deallocated)
    self.compute_client.virtual_machines.generalize(resource_group.name, names.vm)

Create an image, there an operation group compute_client.images. I have no exact example like yours, but see this one to create an image from a blob (can be adapted to your scenario):

Upvotes: 0

Related Questions