Curious about the different ways to spin up a virtual machine locally? In my latest blog post, I explore three practical methods to build a VM using VirtualBox:
🔹 Manual setup via GUI
🔹 Python scripting using VBoxManage
🔹 Vagrant automation by HashiCorp
I’ve included hands-on demos for scripting and Vagrant, complete with code snippets and command-line examples—perfect for beginners and DevOps enthusiasts alike.
Introduction
Virtualization is a cornerstone of modern IT infrastructure, enabling developers, sysadmins, and DevOps engineers to simulate complete environments without the need for physical hardware. If you’ve been following along, you might remember our VirtualBox is one of the most popular tools for running virtual machines (VMs) locally, especially among developers and system admins. It’s a Type 2 hypervisor, which means it runs on top of an existing operating system—unlike Type 1 hypervisors that run directly on hardware.
In my earlier post on hypervisors, I explained the difference between Type 1 and Type 2 hypervisors. VirtualBox, being Type 2, is ideal for desktop-level VM testing, training environments, and reproducible setups without needing dedicated hardware.
Learning Objectives
In this post, I’ll show you three different ways to build a VM using VirtualBox, from manual GUI-based setup to scripting and automation using tools like Python and Vagrant.
By the end, you’ll be able to choose the method that best fits your workflow—whether you prefer point-and-click or full automation.
⚠️ Important Note: Please use your personal computer when building these homelabs. Avoid using company-issued laptops or work devices to prevent potential conflicts with corporate security policies or system restrictions.
Three Methods to Build a VM in VirtualBox
1. Manual or Traditional Setup
- Launch VirtualBox GUI
- Step-by-step: Create VM → Set RAM & disk → Mount ISO → Install OS
- Good for beginners or one-off setups
2. Python Script (Using VBoxManage
or pyvbox
)
- Programmatically define and build VMs
- Offers precise control and automation
- Example: Python script that creates a Debian 12 VM using
VBoxManage
- Best for DevOps or scripting workflows
3. Vagrant by HashiCorp
- Vagrant + VirtualBox = easy and repeatable VM provisioning
- Vagrantfile defines VM properties
- Supports provisioning scripts (e.g., shell, Ansible)
- Ideal for testing environments and team collaboration
Comparison Table
Feature / Method | Manual Setup | Python Script | Vagrant |
---|
Ease of Use | ⭐⭐⭐⭐☆ | ⭐⭐☆☆☆ | ⭐⭐⭐⭐☆ |
Automation | ❌ | ✅ | ✅ |
Scripting Flexibility | ❌ | ✅✅ | ✅ |
Learning Curve | Low | Medium | Medium |
Best Use Case | One-off VMs | Custom automation | Reproducible dev env |
Hands-on Demo: Debian 12 Sample VM
In this hands-on demo, we’ll walk through creating a Debian 12 virtual machine on VirtualBox using different methods. But before diving into the steps, let’s first look at some practical hardware considerations for your personal computer.
Suggested Host System Requirements
Since VirtualBox is a Type 2 hypervisor, it runs on top of an existing host OS (e.g., Windows, macOS, or Linux). This means your computer needs to have enough resources to run both the host and the guest OS smoothly.
Here are the recommended hardware specs for a comfortable experience when running Debian 12 as a guest VM on VirtualBox:
Component | Recommended Minimum | Notes |
---|---|---|
CPU | Quad-core (Intel i5/Ryzen 5 or better) | Virtualization support (VT-x or AMD-V) must be enabled in BIOS/UEFI. |
RAM | 8 GB minimum (16 GB preferred) | Allocate 2–4 GB to the VM for Debian 12. |
Storage (SSD) | 30 GB free (at least) | VM disk size: 15–20 GB suggested. SSDs greatly improve performance. |
GPU | Optional (for GUI guests) | Not required for CLI-only installations. |
Host OS | Windows 10+, macOS 12+, or Linux | Ensure VirtualBox latest version is compatible with your OS. |
💡 Tip: If your machine has limited RAM or an older CPU, consider using Debian’s netinst (minimal) ISO and installing only what you need during setup.
What We’ll Do in This Demo
We’ll cover:
- Creating a Debian 12 VM in VirtualBox (via GUI)
- Setting appropriate VM parameters
- Booting and installing the OS
- (Later sections) Repeating the build using Python and VBoxManage
This hands-on setup is ideal for:
- Homelab beginners
- DevOps learners who want a local playground
- Linux users exploring new workflows or environments
Before you begin:
- Download the Debian 12 netinst ISO and note the path to the ISO file.
- Set up a working directory, e.g.
~/vbox-vm-demo
.
Method 1: Manual (Traditional) GUI Setup
- Open VirtualBox Manager.
- Click New > Name your VM (
debian12-vm
), choose:- Type:
Linux
- Version:
Debian (64-bit)
- Type:
- Set Memory Size: 2048 MB (2 GB).
- Create a Virtual Hard Disk: VDI, dynamically allocated, 10 GB.
- After creation:
- Go to Settings > Storage
- Mount the Debian ISO under the Empty optical drive (click the disc icon).
- Click Start and follow the Debian install wizard.
- Minimal install is fine. Optionally enable SSH during install.
📌 Optional: Once installed, remove the ISO from the virtual CD drive so it boots into the OS. If you don’t have any idea about this manual installation please search in youtube virtualbox installation and any sample virtual machine demo.
Method 2: Python Script using VBoxManage
You’ll need:
- Python 3 (for people with little knowledge of Python)
- VirtualBox installed (ensure
VBoxManage
is in your PATH) - This is only just a simple script you can tweak and modify if you want some enhancement
build-vm.py
#!/usr/bin/env python3
import subprocess
import os
# Config
vm_name = "debian12-python"
iso_path = "/path/to/debian-12.5.0-amd64-netinst.iso"
vbox_disk_path = f"{vm_name}.vdi"
def run(cmd):
print(f"> {cmd}")
subprocess.run(cmd, shell=True, check=True)
# Create VM
run(f"VBoxManage createvm --name {vm_name} --register")
run(f"VBoxManage modifyvm {vm_name} --memory 2048 --cpus 2 --ostype Debian_64")
run(f"VBoxManage createhd --filename {vbox_disk_path} --size 10240") # 10 GB
# Set up storage
run(f"VBoxManage storagectl {vm_name} --name 'SATA Controller' --add sata --controller IntelAhci")
run(f"VBoxManage storageattach {vm_name} --storagectl 'SATA Controller' --port 0 --device 0 --type hdd --medium {vbox_disk_path}")
run(f"VBoxManage storagectl {vm_name} --name 'IDE Controller' --add ide")
run(f"VBoxManage storageattach {vm_name} --storagectl 'IDE Controller' --port 0 --device 0 --type dvddrive --medium {iso_path}")
# Boot from ISO
run(f"VBoxManage modifyvm {vm_name} --boot1 dvd --boot2 disk")
# Start the VM
run(f"VBoxManage startvm {vm_name}")
vm.py
– VM Control Script (CLI)
#!/usr/bin/env python3
import subprocess
import argparse
import sys
# Configuration
VM_NAME = "debian12-python"
def run(cmd):
print(f"> {cmd}")
try:
subprocess.run(cmd, shell=True, check=True)
except subprocess.CalledProcessError:
print(f"❌ Command failed: {cmd}")
sys.exit(1)
def start_vm(headless=False):
mode = "--type headless" if headless else ""
run(f"VBoxManage startvm {VM_NAME} {mode}")
def stop_vm(graceful=True):
if graceful:
run(f"VBoxManage controlvm {VM_NAME} acpipowerbutton")
else:
run(f"VBoxManage controlvm {VM_NAME} poweroff")
def delete_vm():
run(f"VBoxManage unregistervm {VM_NAME} --delete")
def main():
parser = argparse.ArgumentParser(description="Control VirtualBox VM")
subparsers = parser.add_subparsers(dest="command", required=True)
# Start command
start_parser = subparsers.add_parser("start", help="Start the VM")
start_parser.add_argument("--headless", action="store_true", help="Start the VM without GUI")
# Stop command
stop_parser = subparsers.add_parser("stop", help="Gracefully shut down the VM")
stop_parser.add_argument("--force", action="store_true", help="Force power off the VM")
# Delete command
subparsers.add_parser("delete", help="Unregister and delete the VM")
args = parser.parse_args()
if args.command == "start":
start_vm(headless=args.headless)
elif args.command == "stop":
stop_vm(graceful=not args.force)
elif args.command == "delete":
delete_vm()
if __name__ == "__main__":
main()
Usage Examples
# Build a VM
python build-vm.py
# Start with GUI
python vm.py start
# Start headless
python vm.py start --headless
# Graceful shutdown
python vm.py stop
# Force power off
python vm.py stop --force
# Delete the VM
python vm.py delete
Method 3: Vagrant Demo with VirtualBox
# General Notes: This just a simple work instructions
# Please explore and do some research if you want
# to modify some parameters of Virtual Machine you build
# OS Requirements
# Debian/Ubuntu
# Installation Requirements
sudo apt install virtualbox
sudo apt install vagrant
# Initialize a Vagrant VM
mkdir vagrant-debian12 && cd vagrant-debian12
vagrant init debian/bookworm64
# Create a file named vagrantfile
touch vagrantfile
nano vagrantfile
# Insert this code below
Vagrant.configure("2") do |config|
config.vm.box = "debian/bookworm64"
config.vm.hostname = "debian12"
config.vm.provider "virtualbox" do |vb|
vb.name = "vagrant-debian12"
vb.memory = "2048"
vb.cpus = 2
end
end
# Run vagrant command
vagrant up # Start the VM
vagrant halt # Gracefully stop the VM
vagrant destroy # Delete the VM
# Once running, you can SSH into the VM:
vagrant ssh
Final Thoughts
Building virtual machines doesn’t have to be a one-size-fits-all process. Whether you’re:
- 👨💻 just starting out and prefer the GUI,
- ⚙️ building custom scripts for automation, or
- 🚀 using Vagrant to spin up disposable dev environments,
…VirtualBox offers a method that suits your needs.
For personal experimentation or quick tests, the manual method works fine. But if you value repeatability and automation, Python or Vagrant will save you a lot of time in the long run.
0 Comments