Skip to main content

Overview

The VirtualMachine class provides comprehensive support for managing virtual machines in OpenShift Virtualization (based on KubeVirt). You can create, start, stop, restart VMs, and interact with their instances.

Prerequisites

Before working with virtual machines, ensure:
  • OpenShift Virtualization (KubeVirt) is installed on your cluster
  • You have proper permissions to create VirtualMachine resources
  • Required container disk images are available

Creating a Virtual Machine

Basic VM Creation

Create a simple virtual machine with minimal configuration:

VM with Custom Resources

Create a VM with specific CPU and memory:
The body parameter contains the VM specification. It must include the spec.template structure that defines the VM’s hardware and configuration.

Run Strategies

Virtual machines support different run strategies:

VM Lifecycle Operations

Start a Virtual Machine

Start a VM and wait for it to be running:

Stop a Virtual Machine

Gracefully stop a running VM:

Restart a Virtual Machine

Restart a running VM:
When using wait=True, ensure you set appropriate timeout values. VM operations can take several minutes depending on the image size and cluster performance.

Working with VirtualMachineInstance

Access the VMI

When a VM is running, it creates a VirtualMachineInstance (VMI):

Get VMI Details

Waiting for VM Status

Wait for Ready Status

Wait for a VM to reach a specific ready state:

Custom Wait Logic

VM Network Configuration

Get Network Interfaces

Retrieve configured network interfaces:

VM with Multiple Networks

VM Status and States

The VirtualMachine.Status class provides common VM states:
Available status constants:
  • VirtualMachine.Status.MIGRATING
  • VirtualMachine.Status.PAUSED
  • VirtualMachine.Status.PROVISIONING
  • VirtualMachine.Status.STARTING
  • VirtualMachine.Status.STOPPED
  • VirtualMachine.Status.STOPPING
  • VirtualMachine.Status.WAITING_FOR_VOLUME_BINDING
  • VirtualMachine.Status.ERROR_UNSCHEDULABLE
  • VirtualMachine.Status.DATAVOLUME_ERROR

Complete Example

Here’s a complete workflow for creating and managing a VM:

Troubleshooting

VM Not Starting

Image Pull Issues

If you see ImagePullBackOff or ErrImagePull status, verify that the container disk image is accessible and correctly specified.

VM Stuck in Starting State

Best Practices

  1. Use Appropriate Run Strategies: Choose the right run strategy for your use case
  2. Set Proper Timeouts: VM operations can be slow; set generous timeouts
  3. Wait for VMI: Always wait for VMI to be running before accessing it
  4. Resource Limits: Define appropriate CPU and memory limits
  5. Handle Errors: Wrap VM operations in try-except blocks
  6. Check Status: Monitor VM status during operations
  7. Clean Up: Always clean up test VMs to free resources