Automating a Kubernetes Cluster on VMware vSphere with Scripts and Terraform (v1.31)
Automating a Kubernetes Cluster on VMware vSphere with Scripts and Terraform (v1.31)
Introduction
In this post, we’ll walk through how to automate the deployment of a Kubernetes v1.31 cluster in a VMware vSphere environment using scripts, PowerCLI, and Terraform.
This approach follows both VMware and Kubernetes best practices—focusing on automation, consistent configuration, and scalability for lab and production environments.
Prerequisites
Before starting, ensure you have the following:
-
A functioning vSphere environment (vCenter + ESXi)
-
A Linux VM template with VMware Tools installed (Ubuntu 22.04 LTS is recommended)
-
Terraform and the vSphere provider configured
-
Access to either PowerCLI or
govcfor API automation -
Internet access for your Kubernetes nodes
1. Preparing the VM Template
For best results, create a lightweight Ubuntu 22.04 template with cloud-init installed and SSH enabled.
Shut down the VM and convert it to a vSphere template. This image will be cloned for all control-plane and worker nodes.
2. Automating Deployment with govc and PowerCLI
We’ll use two automation paths—govc for Linux/macOS and PowerCLI for Windows.
govc Script Example (Multi-user Input)
This simple script can be expanded to inject metadata and attach ISO images generated by Terraform later.
PowerCLI Version
Both scripts follow vSphere best practices by separating control-plane and worker creation logic for flexibility and scalability.
3. Cloud-Init User Data File
Below is a full, copy-pasteable user-data file for cloud-init automation of Kubernetes 1.31.
It handles initialization on the control-plane and join logic for workers automatically.
This approach initializes the control plane, configures kubeconfig for the ubuntu user, and dynamically joins workers.
4. Terraform Module for vSphere + Cloud-Init
Here’s an example Terraform module to deploy the nodes, attach cloud-init ISOs, and start the cluster.
main.tf
You can duplicate the above block for workers, changing the VM name and compute parameters.
Terraform handles provisioning and attaches the generated cloud-init ISO, which boots the VMs directly into cluster initialization.
5. Post-Deployment Configuration
After the nodes finish booting:
-
Validate the cluster:
-
Install a CNI plugin (Flannel example):
-
Install the vSphere CSI driver for dynamic storage provisioning:
6. Best Practices Recap
-
Use separate networks for management, storage, and workload traffic.
-
Keep your control-plane nodes highly available.
-
Backup your etcd regularly.
-
Use the vSphere CSI and CPI integrations for full VMware compatibility.
-
Automate cluster updates and rotate tokens periodically.
7. Further Reading
Author’s Note:
This article is part of my ongoing Virtology series on virtualization and automation.
Comments
Post a Comment
Got something to say? Drop a comment below — let’s chat!