Automation, APIs and Infrastructure as Code
local graph
Chapter 9: Automation, APIs And Infrastructure As Code
Section titled “Chapter 9: Automation, APIs And Infrastructure As Code”Harvester is already an opinionated platform that hides a lot of Kubernetes details, but at any realistic scale you cannot treat it as a purely click driven system. You want repeatable VM builds, consistent networks, predictable storage, and a clear way to track changes over time. Infrastructure as Code practices turn Harvester from a one off HCI cluster into part of your automated platform.
You have several layers to work with. At the lowest level, Harvester exposes Kubernetes APIs and custom resources, so anything you can do in the UI you can also do with kubectl and YAML. On top of that there is a dedicated Terraform provider that talks to Harvester and lets you describe VMs, networks, images, and volumes as HCL. Further up, GitOps tools such as Fleet apply those definitions from Git repositories into Harvester and related clusters. Finally, CI pipelines glue everything together, running validation and tests before changes touch production.
Taken together, these pieces let you standardize VM and network provisioning, make Harvester settings traceable, and detect configuration drift early rather than during an outage. The goal is not to chase fashionable buzzwords. The goal is to reach a point where you can look at a Git history and know why a VM looks the way it does and where you can rebuild core parts of the environment without guesswork.
9.1: Using The Harvester Terraform Provider For VM And Network Provisioning
Section titled “9.1: Using The Harvester Terraform Provider For VM And Network Provisioning”Terraform is a natural fit for Harvester because it already excels at describing compute, network, and storage resources as code. Harvester has its own official provider that integrates directly with the Harvester API using your kubeconfig to authenticate. The provider can manage virtual machines, images, volumes, networks, load balancers, and related objects.
The provider is installed in a standard way. You declare it as a required provider with source harvester/harvester and choose a version constraint that matches your Harvester cluster capabilities. The provider block itself usually points Terraform at a kubeconfig file or accepts an inline base64 encoded kubeconfig string. The Terraform registry lists supported configuration options, including environment variable based configuration through KUBECONFIG if you prefer not to hardcode paths.
A minimal entry point looks like this.
terraform { required_providers { harvester = { source = "harvester/harvester" version = "~> 0.6.0" } }}
provider "harvester" { kubeconfig = pathexpand("~/.kube/harvester-config")}Once the provider is in place, you define resources. The two most common categories are networks and virtual machines. Networks are managed with harvester_network, which maps to Harvester VM networks such as VLAN networks exposed in the UI.
A typical VLAN aware network definition might look like this.
resource "harvester_network" "vlan_200" { name = "vlan-200" namespace = "harvester-public"
vlan_id = 200
# optional DHCP or routing fields depend on your Harvester version route_dhcp_server_ip = ""}This resource corresponds to a VM network that attaches to a Linux bridge on the Harvester hosts and tags outbound traffic with VLAN 200, provided the host NICs are connected to trunks that allow that VLAN. The exact attributes vary slightly between provider releases, but the pattern stays stable: you declare a name, a namespace, and network parameters, then Terraform posts the matching object into Harvester through the Kubernetes API.
Virtual machines are described via the harvester_virtualmachine resource. This abstraction hides a fair amount of KubeVirt and Harvester complexity, providing a consistent way to set CPU, memory, disks, boot images, and networks. The SUSE documentation and Terraform provider docs show several examples, especially using cloud images and cloud init for Linux VMs.
Here is a simplified resource that provisions a single Ubuntu VM on a VLAN network.
resource "harvester_image" "ubuntu_2204" { name = "ubuntu-22-04-cloud" namespace = "harvester-public"
display_name = "Ubuntu 22.04 Cloud" source_type = "download" url = "https://cloud-images.ubuntu.com/releases/22.04/release/ubuntu-22.04-server-cloudimg-amd64.img"}
resource "harvester_ssh_key" "platform_key" { name = "platform-admin-key" namespace = "default"
}
resource "harvester_virtualmachine" "app_vm" { name = "app-01" namespace = "default"
cpu = 4 memory = "8Gi"
network_interface { name = "eth0" model = "virtio" network_id = harvester_network.vlan_200.id }
disk { name = "rootdisk" type = "disk" size = "100Gi" bus = "virtio" image_name = harvester_image.ubuntu_2204.name image_namespace = harvester_image.ubuntu_2204.namespace }
ssh_keys = [ harvester_ssh_key.platform_key.id, ]
cloudinit { user_data = <<EOF#cloud-confighostname: app-01users: - name: ubuntu sudo: ALL=(ALL) NOPASSWD:ALL groups: users, admin ssh_authorized_keys: - ${harvester_ssh_key.platform_key.public_key}package_update: trueruncmd: - [ sh, -c, "apt-get update && apt-get install -y nginx" ]EOF }}This definition covers a complete VM lifecycle from Terraform. It declares the image download, SSH key, network, VM shape, and initial configuration. The cloudinit block injects standard cloud config so that the VM boots with a known user and installs packages automatically. The provider translates all of this into a VirtualMachine custom resource plus underlying Longhorn volumes, networks, and secrets.
Several patterns are worth adopting early. Use Terraform data sources such as harvester_network and harvester_image data objects when you want to refer to existing networks or images instead of having Terraform manage them. This keeps the separation between shared infrastructure and per application VMs clear. The provider offers data sources for VLAN configs, networks, images, and VMs.
You should also treat VM and network definitions as modules rather than scattering them across loose files. For instance, define a module that creates a standardized application VM with tagging and a base cloud init template, then call that module with different hostnames and small overrides. This translates operational standards into reusable code instead of documentation that people forget to follow. SUSE’s example repository and various community labs show this approach in practice.
Terraform state management needs a bit of thought when Harvester is involved. If you use the provider both interactively and from CI, make sure you use a remote backend such as S3 or another shared storage for the state file. That way, team members do not race each other or overwrite state accidentally. The general Terraform guidance on drift detection and state refresh applies here exactly as it does on public clouds.
You should also be aware of API compatibility. Provider versions track Harvester and Kubernetes API versions. A discussion thread on Terraform and Harvester highlights problems when the provider targets a different API group version than the cluster actually serves, causing resource POST failures for objects like virtualmachineimages.harvesterhci.io. Keeping the provider version aligned with your Harvester release and testing against a lab cluster before upgrading in production avoids these surprises.
When Terraform is fully wired into your process, Harvester becomes just another target. Creating a dev environment can be as simple as terraform apply in a directory that defines a handful of VMs, networks, and images. Destroying it when done is just as easy. That kind of ephemeral behavior is hard to achieve if you define everything by hand in a web UI.
9.2: Managing Harvester Resources With kubectl And Custom Resource YAML
Section titled “9.2: Managing Harvester Resources With kubectl And Custom Resource YAML”Terraform is optional. The Kubernetes API is not. Harvester itself runs on RKE2 and exposes its functionality through custom resources such as VirtualMachine, VirtualMachineImage, Network, IPPool, LoadBalancer, and a variety of Setting objects. Anything you do through the Harvester web UI is ultimately a Kubernetes operation against these CRDs or against underlying core resources.
This is why the UI lets you edit a VM or network as YAML. When you choose that option, you are literally editing the underlying resource. This also means that you can script or automate harvester operations with kubectl as long as you understand the relevant schemas. SUSE documentation organizes the API reference around those resources and their fields.
A VirtualMachine object in Harvester is based on KubeVirt’s CRD with Harvester specific additions. It lives in a namespace and references images, disks, networks, and cloud init secrets. A short but realistic example looks like this.
apiVersion: kubevirt.io/v1kind: VirtualMachinemetadata: name: db-01 namespace: production labels: app: orders-db tier: databasespec: running: true template: metadata: labels: kubevirt.io/domain: db-01 app: orders-db spec: domain: cpu: cores: 4 resources: requests: memory: 16Gi devices: disks: - name: rootdisk disk: bus: virtio - name: datadisk disk: bus: virtio interfaces: - name: mgmt masquerade: {} networks: - name: mgmt pod: {} volumes: - name: rootdisk persistentVolumeClaim: claimName: pvc-db-01-root - name: datadisk persistentVolumeClaim: claimName: pvc-db-01-dataHere, PVCs have already been created, either by Harvester or by you. The VM definition specifies CPU and memory, attaches two disks, and binds a single interface to the default pod network. In Harvester, you usually let the platform manage the PVCs for VM disks, but it is valuable to see that these are regular Kubernetes volumes.
A VirtualMachineImage is a Harvester specific CRD. It captures where an image comes from, how it should be imported, and what metadata it should carry. For example, a cloud image can be defined like this.
apiVersion: harvesterhci.io/v1beta1kind: VirtualMachineImagemetadata: name: ubuntu-22-04-cloud namespace: harvester-public annotations: harvesterhci.io/os-type: linuxspec: displayName: "Ubuntu 22.04 Cloud" sourceType: download url: "https://cloud-images.ubuntu.com/releases/22.04/release/ubuntu-22.04-server-cloudimg-amd64.img"The harvester-public namespace is commonly used for images that should be visible across projects. Documentation lists supported source types such as download, export-from-volume, and export-from-vm.
Networks and IP pools are also modeled as CRDs. A Harvester Network object describes how VM interfaces should be wired, using either the management network, VLAN networks, or untagged networks. A VLAN backed network might look similar to this in YAML.
apiVersion: network.harvesterhci.io/v1beta1kind: Networkmetadata: name: vlan-200 namespace: harvester-publicspec: description: "Application front end VLAN 200" config: mode: "bridge" vlan: vlanId: 200 uplink: bondName: "bond0"The exact schema varies by Harvester version, but the intent is stable: map a VLAN ID and uplink to a bridge that guest VMs can attach to. The networking documentation describes the three network types management, VLAN, and untagged and shows how they are represented internally.
Settings are particularly important when you want to manage Harvester behavior as code. Many system wide options such as backup targets, image storage classes, and feature toggles are exposed through Setting resources in the harvester-system namespace. For example, the backup target for VM backups is stored in a setting named backup-target.
apiVersion: harvesterhci.io/v1beta1kind: Settingmetadata: name: backup-target namespace: harvester-systemvalue: | { "type": "s3", "endpoint": "https://s3.example.com", "bucketName": "harvester-backups", "bucketRegion": "us-east-1", "accessKeyId": "ACCESS_KEY_ID", "secretAccessKey": "SECRET_ACCESS_KEY", "virtualHostedStyle": false, "cert": "" }In the UI, you fill in a form to set this information. With kubectl and YAML, you can define it once, commit it to Git, and apply it to clusters in a controlled way. Harvester and Longhorn then use this configuration as the backup target for VM backups.
To work with these resources you use standard Kubernetes tooling. Export a VM or network definition from the UI with Edit as YAML, clean it up, and store it in a repository. Apply it with kubectl apply -f in lower environments first. Use kubectl diff to see what changes a new configuration would cause. Use labels consistently so you can select resources by purpose or owner. You can then layer tools like Kustomize on top if you want structured overlays for different environments.
One operational concern specific to Harvester is that editing VM user data through the YAML view can unintentionally modify the underlying template if you are not careful. The Harvester troubleshooting documentation warns that changes to cloud config in a VM created from a template may propagate back to that template in some cases. That is another reason to express templates and VMs explicitly as separate YAML manifests under source control rather than relying solely on in place edits through the UI.
The advantage of managing Harvester via kubectl and CRDs is not just flexibility. It gives you a clear mental model. Harvester is not a black box hypervisor. It is a Kubernetes application that happens to provide virtualization and storage. Once you use YAML and the API directly, this becomes obvious, and everything from automation to observability benefits.
9.3: GitOps Workflows For VM Definitions And Harvester Settings
Section titled “9.3: GitOps Workflows For VM Definitions And Harvester Settings”Describing Harvester resources as YAML is useful, but on its own it is still a manual process. GitOps practices complete the picture. The core idea is straightforward. You store the desired state of your clusters in Git and let a controller such as Fleet continuously reconcile actual state against that repository. Harvester and Rancher are explicitly designed to support this model.
Fleet acts as the GitOps engine in Rancher. It is implemented as a set of CRDs and controllers that monitor GitRepo resources. Each GitRepo points at a repository and path. Fleet clones the repo, renders manifests, and applies them to target clusters or cluster groups. This is used extensively for Kubernetes workloads, but it also works for Harvester resources, since those are just Kubernetes objects.
The Harvester project publishes example repositories that show how to use Fleet to define baseline configuration for imported Harvester clusters. Those examples include VM networks, settings, and other configuration that you would otherwise have to create manually. They demonstrate that you can reliably treat Harvester as another consumer of GitOps.
A typical GitOps layout might have one repository per environment or a single mono repo with directories such as harvester/cluster-1, harvester/cluster-2, and so on. Inside each directory you keep YAML for VirtualMachineImage, Network, Setting, and perhaps a few standard VMs such as jump hosts or seeders.
To connect such a repo to a Harvester cluster through Rancher and Fleet, you define a GitRepo object.
apiVersion: fleet.cattle.io/v1alpha1kind: GitRepometadata: name: harvester-baseline namespace: fleet-defaultspec: repo: "https://git.example.com/platform/harvester-iac.git" branch: "main" paths: - "clusters/prod-harvester" targets: - clusterSelector: matchLabels: harvester-role: "prod"This GitRepo tells Fleet to apply everything under clusters/prod-harvester to any cluster labeled with harvester-role=prod. In a typical setup, that label is added to the Harvester cluster in Rancher so that Fleet knows which cluster is which.
Inside the referenced path, you might have a file vm-images.yaml that defines standard images and a file settings.yaml that describes global settings such as backup targets or load balancer behavior.
apiVersion: harvesterhci.io/v1beta1kind: VirtualMachineImagemetadata: name: rocky-9-cloud namespace: harvester-publicspec: displayName: "Rocky Linux 9 Cloud" sourceType: download url: "https://dl.rockylinux.org/pub/rocky/9/images/x86_64/Rocky-9-GenericCloud.latest.x86_64.qcow2"---apiVersion: harvesterhci.io/v1beta1kind: Settingmetadata: name: backup-target namespace: harvester-systemvalue: | { "type": "nfs", "endpoint": "nfs01.backup.example.com:/exports/harvester", "accessKeyId": "", "secretAccessKey": "", "bucketName": "", "bucketRegion": "", "cert": "", "virtualHostedStyle": false }When this repository is applied by Fleet, every matching Harvester cluster gets the same standard cloud image and backup target configuration. Changes are made by editing the Git repository and letting Fleet roll them out, not by logging into each cluster and editing settings by hand.
VM definitions also fit naturally into a GitOps flow. A jump host VM that should exist in each cluster can be expressed as a VirtualMachine YAML file. If the VM is stateless or bootstraps itself from configuration management, you can even allow GitOps to recreate it when deleted, treating it as cattle rather than a unique pet. SUSE’s Harvester blog explicitly calls out the fact that VM definitions can be managed as code in this way and integrated into Fleet.
You should design the Git repository structure with maintenance in mind. For example, you might separate cluster wide infrastructure such as networks, settings, and images from application specific VMs. Infrastructure definitions can live in one path that targets all Harvester clusters of a certain type. Application VMs can live in per project directories and target only specific clusters using Fleet’s targets rules. This lets you keep clear boundaries between platform concerns and application concerns.
In multi team environments, GitOps security matters. Recent Fleet improvements allow you to restrict which namespaces can target which clusters or resource types using objects such as GitRepoRestriction. That makes it possible to give application teams the ability to add and change VM manifests within certain boundaries without letting them touch core Harvester settings. Combined with Rancher’s RBAC, you can align Git permissions and runtime permissions closely.
GitOps workflows also tend to expose bad patterns quickly. If someone edits Harvester settings directly in the UI, Fleet will detect drift when it next compares the live objects with the Git repository and will either revert the change or flag the drift depending on configuration. This gives you a feedback loop on manual interventions and encourages people to make changes in code.
The end result is that Harvester configuration, from basic networking to VM images and seed VMs, lives in source control and can be rolled out consistently across clusters. You know what is where and why, because it is written down as code with history, not scattered across dashboards and personal notes.
9.4: CI Pipelines For Harvester Changes And Validation Jobs
Section titled “9.4: CI Pipelines For Harvester Changes And Validation Jobs”Once Harvester resources are managed through Terraform and GitOps, the natural next step is to introduce CI pipelines that validate and apply changes. Pipelines are how you enforce quality checks such as formatting, schema validation, and basic functional tests before Terraform plans or YAML manifests reach production clusters.
There are two broad categories of pipelines you will care about. One category focuses on Terraform, checking HCL syntax, running terraform validate, and producing plans for review. The other category focuses on Kubernetes and Harvester YAML, running schema validation, policy checks, and in some cases integration tests that talk directly to Harvester clusters via kubeconfig. Tools like GitHub Actions, GitLab CI, Jenkins, or Harness can all run these workflows. The specifics differ, but the pattern is stable.
A simple example using GitHub Actions can illustrate how these pieces fit together. Consider a repository that contains Terraform code for Harvester under terraform/ and YAML manifests for Harvester GitOps under manifests/. You can define a workflow that runs on pull requests and on merges to main.
name: harvester-iac-ci
on: pull_request: branches: [ "main" ] push: branches: [ "main" ]
jobs: terraform: runs-on: ubuntu-latest defaults: run: working-directory: terraform steps: - name: Checkout uses: actions/checkout@v4
- name: Setup Terraform uses: hashicorp/setup-terraform@v3
- name: Terraform fmt run: terraform fmt -check
- name: Terraform validate run: terraform validate
- name: Terraform plan env: KUBECONFIG: ${{ secrets.HARVESTER_KUBECONFIG }} run: terraform plan -out=tfplan
yaml-validate: runs-on: ubuntu-latest defaults: run: working-directory: manifests steps: - name: Checkout uses: actions/checkout@v4
- name: Install kubeconform run: | curl -L https://github.com/yannh/kubeconform/releases/latest/download/kubeconform-linux-amd64.tar.gz \ | tar -xz sudo mv kubeconform /usr/local/bin/
- name: Validate Kubernetes manifests run: | find . -name '*.yaml' -print0 | xargs -0 kubeconform -ignore-missing-schemasIn this workflow, the Terraform job ensures that HCL is formatted and syntactically valid and that a plan can be produced against a Harvester cluster using a kubeconfig stored as a secret. The YAML job uses a tool such as kubeconform to validate all Kubernetes and Harvester manifests. You can tighten validation further by supplying schema locations for Harvester CRDs or by using custom policy engines like OPA Gatekeeper, but even these basic checks catch many errors that would otherwise surface only at apply time.
You can also introduce automated tests that apply changes to a non production Harvester cluster. One approach is to stand up a small test cluster that CI can access and to run short lived namespaces or projects dedicated to validation. Pipeline jobs apply a subset of manifests, run smoke tests against them, and then clean up. For Terraform driven VMs, a test job can create one or two instances, verify that they reach the expected state through SSH or HTTP checks, and then destroy them. The Harvester Terraform blog shows that creating and tearing down VMs for Kubernetes control planes or application nodes can be automated this way.
If you use Fleet for GitOps, CI does not apply YAML directly to Harvester clusters. Instead, CI validates YAML and perhaps updates version tags or values files, then merges changes into branches that Fleet watches. Deployment is then handled by Fleet in a pull based manner. That separation is useful because CI does not need direct network access to production clusters; it only needs access to Git. Fleet takes responsibility for reconciling live state. Rancher documentation on Fleet based continuous delivery describes this pattern as the default.
For Terraform, you have more flexibility. Some teams let CI run terraform apply directly against Harvester when changes merge into main branches. Others treat Terraform plans as artifacts that operators apply manually after review, especially in environments with strict change control. Both options benefit from CI, because validation and plan creation still happen in a consistent, reproducible context.
CI pipelines are also good places to enforce security and compliance checks. You can run static analysis on cloud init templates to catch hardcoded credentials. You can ensure that all harvester_virtualmachine resources use approved VM images or that all VirtualMachineImage resources pull from trusted registries or URLs. Policy engines that inspect HCL or YAML can flag violations automatically before they land in Git or before they are applied.
For more advanced setups, you may want to run integration tests that involve Rancher and guest clusters as well. For example, a pipeline can use Terraform to provision an RKE2 cluster on Harvester, then run Kubernetes conformance tests or application level tests against that guest cluster, and finally tear everything down. SUSE and community articles on using Terraform to deploy secure Kubernetes clusters show patterns that translate directly to Harvester backed infrastructure.
Finally, CI pipelines should report clearly. If a change to a Harvester Setting resource or Terraform VM definition fails validation, the pipeline should show exactly which file and which resource caused the problem. That kind of feedback encourages making many small changes instead of risky large ones. Over time, the pipeline configuration itself becomes part of your Harvester discipline, encoding best practices that every engineer benefits from without having to learn them all at once.
With Terraform, kubectl, GitOps, and CI working together, Harvester is no longer just a cluster of hosts running VMs. It becomes an automated, testable, and repeatable part of your infrastructure platform, subject to the same rigor as application code and Kubernetes manifests. That is the level of control you need if you want to use Harvester as a serious alternative to traditional hypervisors in environments where correctness and speed both matter.