How to Use Custom Image for VM in Azure: Step-by-Step Guide
To use a
custom image for a VM in Azure, first create the image from a generalized VM or managed disk, then specify this image when creating a new VM using the --image parameter in Azure CLI. This lets you deploy VMs with your own pre-configured OS and software.Syntax
Use the Azure CLI command to create a VM from a custom image. The key parts are:
az vm create: Command to create a VM.--resource-group: Your Azure resource group name.--name: Name for the new VM.--image: The custom image resource ID or name.--admin-usernameand--admin-password: Credentials for the VM.
bash
az vm create --resource-group MyResourceGroup --name MyVM --image MyCustomImage --admin-username azureuser --admin-password MyP@ssw0rd!
Example
This example shows how to create a custom image from an existing VM and then deploy a new VM using that image.
bash
# Step 1: Deallocate and generalize the source VM az vm deallocate --resource-group MyResourceGroup --name SourceVM az vm generalize --resource-group MyResourceGroup --name SourceVM # Step 2: Create a custom image from the generalized VM az image create --resource-group MyResourceGroup --name MyCustomImage --source SourceVM # Step 3: Create a new VM using the custom image az vm create --resource-group MyResourceGroup --name NewVM --image MyCustomImage --admin-username azureuser --admin-password MyP@ssw0rd!
Output
Virtual machine 'NewVM' created successfully.
Common Pitfalls
- Not generalizing the source VM: You must run
az vm generalizeafter deallocating the VM to prepare it for imaging. - Using incorrect image name or ID: Ensure the
--imageparameter matches the exact name or resource ID of your custom image. - Missing permissions: Your Azure account must have rights to create images and VMs in the resource group.
- Incorrect admin credentials: Passwords must meet Azure's complexity requirements.
bash
Wrong: az vm create --resource-group MyResourceGroup --name NewVM --image SourceVM --admin-username azureuser --admin-password MyP@ssw0rd! Right: az vm create --resource-group MyResourceGroup --name NewVM --image MyCustomImage --admin-username azureuser --admin-password MyP@ssw0rd!
Quick Reference
| Command | Purpose |
|---|---|
| az vm deallocate | Stop and deallocate the VM before generalizing |
| az vm generalize | Prepare the VM for image creation |
| az image create | Create a custom image from a VM or disk |
| az vm create --image | Create a new VM from a custom image |
Key Takeaways
Always deallocate and generalize the source VM before creating a custom image.
Use the custom image name or resource ID with the --image parameter when creating a VM.
Ensure your admin credentials meet Azure's security requirements.
Verify you have proper permissions to create images and VMs in your resource group.
Use Azure CLI commands in the correct order to avoid deployment errors.