Python – Use python to create VMs using custom images on Azure

Use python to create VMs using custom images on Azure… here is a solution to the problem.

Use python to create VMs using custom images on Azure

Starting a

VM using a Marketplace image in Azure is straightforward.

This is the relevant code.

def create_vm(network_client, compute_client):

vm_parameters = {
    'storage_profile': {
        'image_reference': {
            'publisher': 'MicrosoftWindowsServer',
            'offer': 'WindowsServer',
            'sku': '2012-R2-Datacenter',
            'version': 'latest'
        }
    },

vm = compute_client.virtual_machines.create_or_update(
    GROUP_NAME, 
    VM_NAME, 
    vm_parameters
)

(Obviously there’s more in the actual code, which I think is the most relevant part).

So in this case, the image reference points to the market.

I created a custom image using the following document.

https://learn.microsoft.com/en-us/azure/virtual-machines/windows/create-vm-generalized-managed?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json

I

want to create a VM based on the new custom image I created. I think image_reference should point to something else, but it’s not clear to me what it should be. Can someone help?

Thanks!

Solution

In fact, the Azure Python SDK uses the Azure Rest API. You can check this example .

Therefore, you can modify your script like this:

vm_parameters = {
    'storage_profile': {
        'image_reference': {
            'id' : '/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}'
        }
    },

Related Problems and Solutions