VM Lifecycle Management with KubeVirt
local graph
Chapter 5: VM Lifecycle Management With KubeVirt
Section titled “Chapter 5: VM Lifecycle Management With KubeVirt”Virtual machines on Harvester are not a separate thing bolted on the side of Kubernetes. They are modeled as Kubernetes resources that KubeVirt understands, scheduled as pods, backed by Longhorn volumes, and controlled through the same API surface you use for containers. The Harvester UI makes this look very similar to a traditional hypervisor experience, but underneath you are dealing with objects such as VirtualMachine, VirtualMachineInstance, VirtualMachineImage, PersistentVolumeClaim, and NetworkAttachmentDefinition.
If you are coming from VMware or another classical hypervisor, this has two practical consequences. First, you gain a lot of flexibility. You can define VMs declaratively, apply GitOps patterns, and use standard Kubernetes tooling to observe and automate your infrastructure. Second, you need to understand how KubeVirt models VM lifecycle so that you do not treat Harvester as a black box. That is what this section is about.
You will see how the VirtualMachine and VirtualMachineInstance objects behave in Harvester, how images and templates work together with cloud init to create reproducible VM builds, how to handle common operations such as starting, stopping, resizing, and migrating VMs, and how to design standards that keep your estate consistent and manageable as more teams adopt the platform.
5.1: KubeVirt Concepts VirtualMachine And VirtualMachineInstance In Harvester
Section titled “5.1: KubeVirt Concepts VirtualMachine And VirtualMachineInstance In Harvester”KubeVirt introduces a clear separation between the definition of a VM and its current runtime state. The VirtualMachine resource describes the desired configuration of a virtual machine, including CPU, memory, disks, and networks, and it also carries a spec.running flag that indicates whether the VM should be powered on. The VirtualMachineInstance resource represents a specific running instance of that VM. When spec.running on the VirtualMachine is set to true, KubeVirt ensures that a corresponding VirtualMachineInstance exists. When it is set to false, KubeVirt shuts down the instance and removes the VirtualMachineInstance object.
Harvester uses these KubeVirt primitives directly. When you create a VM in the Harvester UI, the platform generates a VirtualMachine manifest in the appropriate namespace. The UI stores additional metadata in labels and annotations so it can display information such as operating system, creation source, and template version. Once you click create, Harvester sets spec.running to true, KubeVirt creates a VirtualMachineInstance, and the Kubernetes scheduler places a pod on a suitable node. This pod runs the virt-launcher container that starts the QEMU process for the guest.
It is useful to see how this looks in raw YAML. The UI usually hides the details, but inspecting them is essential when you debug issues or integrate Harvester with automation tools.
apiVersion: kubevirt.io/v1kind: VirtualMachinemetadata: name: app-server-01 namespace: default labels: harvesterhci.io/os: "linux" harvesterhci.io/creator: "admin" harvesterhci.io/managed: "true"spec: running: true template: metadata: labels: kubevirt.io/domain: app-server-01 spec: domain: cpu: cores: 4 resources: requests: memory: 8Gi devices: disks: - name: rootdisk disk: bus: virtio interfaces: - name: default masquerade: {} networks: - name: default pod: {} volumes: - name: rootdisk persistentVolumeClaim: claimName: pvc-app-server-01-rootIn this definition, the VirtualMachine says that a VM called app-server-01 should be running, with 4 vCPUs and 8 GiB of RAM, a single disk bound to a PVC, and a single network interface that uses the cluster default network via pod networking. The Longhorn volume that backs the root disk exists separately as a PVC.
Once this VM is running, KubeVirt maintains a VirtualMachineInstance object with more detailed status fields.
apiVersion: kubevirt.io/v1kind: VirtualMachineInstancemetadata: name: app-server-01 namespace: default labels: kubevirt.io/domain: app-server-01status: phase: Running nodeName: harv-compute-01 interfaces: - name: default ipAddress: 10.52.0.23 conditions: - type: Ready status: "True" - type: LiveMigratable status: "True" guestOSInfo: name: "Ubuntu" version: "22.04"The VirtualMachineInstance object tells you which node the VM is running on, what IP address it is using on each interface, what phase it is in (Scheduling, Running, Succeeded, Failed, Migrating), and whether it meets conditions such as readiness and migratability.
From a lifecycle perspective, you can think of VirtualMachine as the desired state and VirtualMachineInstance as the current one. You usually interact with the VirtualMachine when you want to start, stop, or change a VM. KubeVirt translates those changes into VirtualMachineInstance operations.
Harvester gives you a visual view of this, but you can always drop into the CLI to confirm what is going on.
# List virtual machines in a namespacekubectl get vm -n default
# Inspect a specific VM definitionkubectl get vm app-server-01 -n default -o yaml
# See the current instance and where it runskubectl get vmi app-server-01 -n default -o wide
# Show events related to the VMI, useful for debugging failureskubectl describe vmi app-server-01 -n defaultThese commands are particularly useful when a VM fails to start. For example, if there is insufficient memory on all nodes that match scheduling rules, the VirtualMachineInstance will sit in the Scheduling phase and events will explain that there are no suitable nodes. The Harvester UI will show a failure, but the CLI output gives the precise reason.
Harvester also adds its own custom resources for convenience. For example, VM backups are represented as VirtualMachineBackup objects, and images are represented as VirtualMachineImage resources. These live in the harvesterhci.io API group, not in kubevirt.io, but they are part of the same overall lifecycle. Creating a backup affects how you later restore or clone a VM, and creating an image affects how new VMs are initialized.
Once you internalize that KubeVirt controls runtime through VirtualMachineInstance and that Harvester hangs UI and extra behavior on top of these primary objects, a lot of Harvester behavior becomes predictable. A VM power operation is a patch to the VirtualMachine resource, not some opaque RPC routed through a custom daemon. A migration is a KubeVirt migration object that causes a new VirtualMachineInstance to appear on another node. This consistency is one of the benefits of building virtualization on Kubernetes.
5.2: Creating Images, VM Templates And Cloud Init Based Configuration
Section titled “5.2: Creating Images, VM Templates And Cloud Init Based Configuration”Image and template management in Harvester is where you set the tone for how clean or messy your VM estate will become. If every VM is created by hand from random ISO files, you end up with snowflakes that are hard to maintain. If you invest up front in curated images, templates, and cloud init driven configuration, you can provision VMs consistently through the UI, Terraform, or other automation.
Harvester uses the VirtualMachineImage resource to represent VM images. You can upload images directly through the UI, point Harvester at an HTTP or HTTPS URL that hosts a qcow2 or raw disk image, or import images from S3 compatible storage. Under the hood, Harvester creates a VirtualMachineImage object in the harvester-system namespace, and controllers pull the image into Longhorn.
A typical VirtualMachineImage manifest looks similar to the following trimmed example.
apiVersion: harvesterhci.io/v1beta1kind: VirtualMachineImagemetadata: name: ubuntu-22-04-base namespace: harvester-system labels: harvesterhci.io/os: "ubuntu" harvesterhci.io/version: "22.04"spec: displayName: "Ubuntu 22.04 Base" sourceType: "download" url: "https://images.example.com/ubuntu/22.04/server-cloudimg-amd64.img"status: progress: 100 status: "Ready"Here, sourceType is set to download, which tells Harvester to fetch the image from the provided URL. Other values such as upload are used when you upload directly. Once the image status reaches Ready, it appears as an option when you create volumes or VM templates in the UI.
Templates are another layer. A VM template captures a reusable configuration for VMs based on a given image. Harvester stores templates as VirtualMachineTemplate and VirtualMachineTemplateVersion resources. You can define CPU, memory, disk, network interfaces, and cloud init behavior in a template, then let users create VMs by selecting that template and overriding a minimal set of fields such as name and SSH keys.
In this model, cloud init is critical. Most modern Linux images support cloud init for first boot configuration. That includes injecting SSH keys, setting hostnames, configuring users, and running custom scripts. Harvester integrates with cloud init by letting you attach user data and network data when you create a VM. That data is stored either inline in the VM spec or more commonly in a Kubernetes secret that KubeVirt passes through to the guest as a config drive.
The pattern usually looks like this. You create an image that is cloud init capable, for example Ubuntu cloud images or custom builds with cloud init installed. You define a VM template that references this image and enables cloud init. When users create VMs from that template, they provide their SSH keys and any instance specific parameters. The VM boots from the image and cloud init applies the configuration.
Here is a concrete example of a simple cloud init user data definition that creates a user, sets an SSH key, and installs a few packages.
#cloud-configusers: - name: devops sudo: ALL=(ALL) NOPASSWD:ALL shell: /bin/bash ssh_authorized_keys:packages: - qemu-guest-agent - htop - curlpackage_update: trueruncmd: - systemctl enable qemu-guest-agent - systemctl start qemu-guest-agentTo feed this into Harvester in a reusable way, you usually store it in a secret and reference that secret from the VM spec.
apiVersion: v1kind: Secretmetadata: name: app-server-01-cloudinit namespace: defaulttype: Opaquedata: userData: | I2Nsb3VkLWNvbmZpZwp1c2VyczoKICAtIG5hbWU6IGRldm9wcwogICAgc3VkbzogQUxMPShBTExKIE5PUEFTU1dERDpBTEwpCiAgICBzaGVsbDogL2Jpbi9iYXNoCiAgICBzc2hfYXV0aG9yaXplZF9rZXlzOgogICAgICAtIHNzaC1lZDI1NTE5IEFBQUFDM056YUMxbFpESTFOVEU1QUFBQUlCQVNFNjRLRVkgZGV2b3BzQGV4YW1wbGUuY29tCnBhY2thZ2VzOgogIC0gcWVtdS1ndWVzdC1hZ2VudAogIC0gaHRvcAogIC0gY3VybApwYWNrYWdlX3VwZGF0ZTogdHJ1ZQpydW5jbWQ6CiAgLSBzeXN0ZW1jdGwgZW5hYmxlIHFlbXUtZ3Vlc3QtYWdlbnQKICAtIHN5c3RlbWN0bCBzdGFydCBxZW11LWd1ZXN0LWFnZW50Cg==The userData field here is base64 encoded cloud init content. Harvester can generate this secret for you from the UI, but it is useful to see the underlying structure.
Now, you can create a VM that references both the image and the cloud init secret.
apiVersion: kubevirt.io/v1kind: VirtualMachinemetadata: name: app-server-01 namespace: defaultspec: running: true template: metadata: labels: kubevirt.io/domain: app-server-01 harvesterhci.io/os: "ubuntu" spec: domain: cpu: cores: 4 resources: requests: memory: 8Gi devices: disks: - name: rootdisk disk: bus: virtio - name: cloudinitdisk disk: bus: virtio networks: - name: default pod: {} volumes: - name: rootdisk dataVolume: name: dv-app-server-01-root - name: cloudinitdisk cloudInitNoCloud: userDataSecretRef: name: app-server-01-cloudinitIn many Harvester setups, the dataVolume section refers to a DataVolume object managed by the Containerized Data Importer (CDI) component, which handles creating the initial Longhorn volume from the VirtualMachineImage. The Harvester UI hides CDI details, but this pattern explains why you sometimes see extra resources with names derived from your VM names.
When you start to codify this into templates, you can create a VirtualMachineTemplate that contains the structure above with placeholders for CPU, memory, and cloud init secret names. Harvester then lets users select that template and supply values at creation time, so you keep governance over the base image and configuration while still supporting team level customization.
For Windows VMs, the basic pattern is similar, but you often rely on sysprep or other guest specific mechanisms in addition to or instead of cloud init. Harvester supports Windows VMs and exposes virtio drivers and guest agents in ways similar to other KubeVirt environments. Where possible, you can still use cloud init style configuration through tools like Cloudbase Init, but on most platforms you will have separate base images and customization scripts.
The key outcome of doing image and template work properly is that you stop thinking of VM creation as a manual art and start treating it as a repeatable process. That is what allows teams to build automation on top of Harvester rather than redoing the same point and click steps for each application.
5.3: Routine VM Operations Start, Stop, Console, Resize, Live Migration
Section titled “5.3: Routine VM Operations Start, Stop, Console, Resize, Live Migration”Once VMs exist on Harvester, daily operations start to resemble what you are used to from VMware or similar platforms, but with Kubernetes constructs in the background. You still need to start and stop VMs, connect to consoles, modify CPU and memory assignments, add disks, and migrate VMs between nodes for maintenance or load balancing. What changes is how those actions are wired.
Power operations are simple conceptually. When you click start, stop, or restart in the Harvester UI, you are indirectly toggling the spec.running flag on the VirtualMachine object or applying an action that KubeVirt understands. If you prefer CLI, you can do the same with kubectl or virtctl.
# Stop a VM by patching spec.running to falsekubectl patch vm app-server-01 -n default --type merge -p '{"spec":{"running":false}}'
# Start it againkubectl patch vm app-server-01 -n default --type merge -p '{"spec":{"running":true}}'
# Alternatively, use virtctl convenience commandsvirtctl stop app-server-01 -n defaultvirtctl start app-server-01 -n defaultHarvester updates the UI to reflect the new state as KubeVirt processes these changes. If the VM does not stop promptly, you can inspect the VirtualMachineInstance events to see whether there is a guest agent delay or a more fundamental issue.
Console access in Harvester is provided through a browser interface that connects to KubeVirt’s console access service. Underneath, KubeVirt exposes serial and VNC consoles. You can initiate console sessions through the UI or through virtctl.
# Open a serial console in a local terminalvirtctl console app-server-01 -n default
# Open a VNC console using a local VNC clientvirtctl vnc app-server-01 -n defaultThe UI wraps the VNC console in a browser frame using noVNC. From an operational perspective, this is equivalent to opening the vSphere console in a browser, but the actual protocol flow is KubeVirt specific.
Resizing a VM has two dimensions. One is CPU and memory. The other is storage. KubeVirt supports both offline and online resource changes depending on the guest and how features are configured. Harvester surfaces safe options in the UI, generally encouraging you to shut down VMs before large changes.
For CPU and memory, you adjust fields in the VirtualMachine spec.
apiVersion: kubevirt.io/v1kind: VirtualMachinemetadata: name: app-server-01 namespace: defaultspec: running: true template: spec: domain: cpu: cores: 6 # increased from 4 resources: requests: memory: 12Gi # increased from 8GiIf you apply this patch while the VM is stopped, KubeVirt will create the next VirtualMachineInstance with the updated resources. For certain guest OS and configuration combinations, you can change CPU and memory while the VM is running, but you need to be careful and understand both KubeVirt and guest capabilities. In many production environments it is still safer to plan maintenance windows for substantial resource changes.
Disk resizing for Longhorn backed volumes follows the standard Kubernetes PVC pattern. You edit the PVC that backs the VM disk and increase the requested storage size, making sure that the storage class allows expansion. Longhorn will resize the volume, and KubeVirt will see the new capacity. Inside the guest, you still need to extend partitions and filesystems. Harvester makes PVC expansion available through the UI, but the underlying mechanism looks like this.
apiVersion: v1kind: PersistentVolumeClaimmetadata: name: pvc-app-server-01-root namespace: defaultspec: resources: requests: storage: 200Gi # previously 100GiAfter this change, Longhorn grows the underlying volume, then you run your standard disk extension steps inside the VM.
Live migration is often the feature that convinces administrators that KubeVirt based virtualization is viable. Harvester supports live migration between nodes when the configuration is suitable. The conditions are similar to those in classical hypervisors. Storage must be shared in a way that both source and target nodes can access the VM disk, which Longhorn provides. Networks must be consistent on both nodes so that the VM can keep its IP and external connectivity. The VM must not be using certain device passthrough features that prevent migration, such as local host devices or some GPU configurations, unless special support is configured.
KubeVirt tracks whether a VirtualMachineInstance is migratable through status conditions. From a CLI perspective, you can trigger a migration with virtctl.
# Check if the VMI is live migratablekubectl get vmi app-server-01 -n default -o jsonpath='{.status.conditions[?(@.type=="LiveMigratable")].status}'
# Trigger a live migrationvirtctl migrate app-server-01 -n default
# Watch the migration progresskubectl get vmi app-server-01 -n default -o widekubectl get vmi -n defaultWhen a migration starts, KubeVirt creates a new migration object and orchestrates the state transfer. For a period, you may see both the source and target nodes involved in the process. Once it completes, the VirtualMachineInstance shows the new nodeName.
When you initiate a migration from the Harvester UI, it uses the same underlying KubeVirt mechanisms. Knowing this helps when migrations fail. For example, if KubeVirt reports that the VM is not migratable because of a specific device type, the Harvester UI will show a generic error. Looking at the VirtualMachineInstance conditions and the migration object in Kubernetes gives you the full story.
Routine operations also include backups and restores. Harvester integrates VM level backups with Longhorn and additional CRDs. When you trigger a backup from the UI, Harvester creates a VirtualMachineBackup object that references the VM, captures metadata, and triggers Longhorn snapshot and backup operations. A successful backup has a status that points to the backup location (NFS or S3). Restoring from a backup involves creating a new VM along with restored volumes. All of this is driven by Kubernetes resources which means you can inspect and, if needed, script around them.
Throughout these operations, it is worth reinforcing a key point. You can carry out everyday tasks entirely through the Harvester UI if you prefer, but at any time you can switch to kubectl and virtctl for clarity or automation. VM lifecycle is governed by KubeVirt and Longhorn, not by opaque proprietary services, and that transparency is a major advantage when you need to troubleshoot or integrate with external tools.
5.4: Designing VM Standards For Teams And Projects
Section titled “5.4: Designing VM Standards For Teams And Projects”As soon as multiple teams start creating and managing VMs on Harvester, you move from isolated testing into something that behaves more like an internal platform. At that point, standards are not a luxury. They are what prevent your cluster from turning into an unstructured collection of ad hoc VMs that nobody fully understands.
Good VM standards start with naming. You should define a simple, consistent scheme that encodes at least the environment, application, and sequence number in the VM name. For example, you might decide that names follow a pattern such as env-app-role-##, giving you identifiers like prod-web-01 or dev-db-02. Harvester does not enforce this, but you can encourage it through templates, team guidelines, and review practices. When dozens or hundreds of VMs exist across namespaces, having clear names makes dashboards, logs, and incident communication much simpler.
Labels and annotations are your next layer of structure. Kubernetes and Harvester allow you to attach arbitrary key value pairs to VM resources. You can use labels for things you want to select on, such as team, project, environment, tier, or backup-policy. For example, you might label VMs that need daily backups with backup-policy=daily and configure your backup automation to discover and process all VMs with that label. Annotations can hold more descriptive metadata such as ticket numbers, change identifiers, or links to service catalogs. Over time, these labels and annotations become the backbone of your reporting and governance.
Standardization around images and templates is equally important. You should limit the set of base images that teams are allowed to use for production workloads and treat those images as carefully maintained artifacts. For Linux, that often means one or two distributions at specific LTS versions. For Windows, it might mean a standard server image and a domain joined variant. Each base image should be updated regularly with security patches and tested before being promoted. Templates should be built on top of these images and made available in Harvester with clear names and versions. When you need to improve security configuration or add base packages, you update the templates and plan for how existing VMs will be refreshed or replaced.
Sizing standards reduce guesswork. You can define a small set of VM flavors, such as small, medium, and large, each mapping to specific CPU and memory configurations. Teams would pick a flavor rather than arbitrary numbers, at least at first. This makes capacity planning and cost analysis more predictable, because you can count how many of each flavor are in use and know what that means in terms of resource consumption. Over time you can introduce specialized flavors for databases, caches, or other workload types that have distinctive requirements.
Network and security standards belong in the same conversation. Teams should not choose random VLANs or network policies for each VM. Instead, you define standard networks for environments and roles. For example, all production web VMs might attach to one VLAN for front end traffic and one for management, while database VMs attach to a restricted VLAN that only application tiers can reach. In Harvester this translates into a set of predefined VLAN networks and possibly network policies applied at the Kubernetes level for workloads running in guest clusters. The goal is not to eliminate flexibility, but to keep most workloads within well understood patterns.
Backup and recovery policies must be clearly defined and tied to VM labels and environments. Some VMs genuinely do not need backups because their data is ephemeral or fully reconstructed from source control and pipelines. Others, especially stateful applications and infrastructure components such as authentication servers, require aggressive backup policies and regular restore testing. Standards should specify which VMs fall into which category, how often backups run, where they are stored, and how long they are retained. Harvester and Longhorn give you the tools to take snapshots and push backups to NFS or S3 compatible storage. Your standards decide how those tools are used.
You also need a position on configuration management inside VMs. Harvester does not care whether you use Ansible, Salt, Puppet, Chef, cloud init alone, or simple shell scripts. The platform will happily run VMs configured in any of these ways. For operational sanity, however, it is sensible to converge on one or two methods that most teams share. Cloud init is excellent for one time bootstrapping, but long lived configuration should sit in a version controlled system, not solely in VM disk images. A common pattern is to use cloud init to register new VMs with a configuration management system and then let that system keep the instance aligned with declared state.
Finally, think about lifecycle and decommissioning. Standards should describe how you decide when a VM is no longer needed, how you track that decision, and how you remove the VM cleanly. That might involve labeling VMs with an owner and an expiry date, running periodic reports on VMs that have not shown activity, and requiring teams to review and either justify or retire those resources. Proper deletion should clean up associated PVCs, snapshots, and backups where appropriate, to avoid wasting storage on volumes that nobody uses.
Harvester and KubeVirt give you a lot of power to define VMs declaratively and to automate their lifecycle. Without standards, that power tends to fragment along team lines, and you end up with inconsistent practices that are hard to support. With thoughtful standards for naming, labeling, images, templates, sizing, networks, security, backup, and configuration management, you can treat VM lifecycle on Harvester as a first class part of your platform, not as an exception carved out for legacy workloads.