Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Vagrantfile and Boxes

Building Custom Boxes

Create your own Vagrant box from a running machine with vagrant package, learn what a base box needs, and see how Packer automates box builds.

Public boxes are fine for learning, but many teams end up wanting their own. Perhaps provisioning takes 15 minutes every time because the same packages are installed again and again; perhaps security rules demand a hardened image; perhaps your product needs a specific kernel. A custom box moves expensive setup from "every vagrant up" to "once, at build time".

There are two ways to make one: package a machine you already configured (quick and manual), or build it from an installer with an automated tool such as Packer (repeatable). This lesson covers both.

Option 1: package a running machine

Start with an ordinary machine, install what you want inside, then export it as a box.

Ruby
Vagrant.configure("2") do |config|
  config.vm.box = "bento/ubuntu-24.04"
  config.vm.provision "shell", inline: <<~SHELL
    apt-get update
    DEBIAN_FRONTEND=noninteractive apt-get install -y nginx postgresql git build-essential
  SHELL
end
CONSOLE
$ vagrant up
$ vagrant ssh -c "sudo apt-get clean && sudo rm -rf /var/lib/apt/lists/*"
$ vagrant package --output shop-base.box
==> default: Attempting graceful shutdown of VM...
==> default: Clearing any previously set forwarded ports...
==> default: Exporting VM...
==> default: Compressing package to: /home/you/shop/shop-base.box

vagrant package shuts the VM down, exports its disk and settings, and compresses them into a single .box file. A box is simply an archive (a tar, usually gzip-compressed) that contains:

File Purpose
metadata.json Says which provider the box is for, for example {"provider": "virtualbox"}
Vagrantfile Default settings baked into the box; merged below the project's own Vagrantfile
Provider disk and config For VirtualBox: an .ovf and .vmdk files

Now add it locally and use it:

CONSOLE
$ vagrant box add shop/base ./shop-base.box
$ vagrant box list
Ruby
Vagrant.configure("2") do |config|
  config.vm.box = "shop/base"
end

A fresh machine from this box already has nginx, PostgreSQL and a compiler, so provisioning only installs your application. Shrinking the image first (clean package caches, zero free space with dd or fstrim) makes the box smaller and quicker to share.

What a good base box needs

If you want to build your own base box from a plain operating system instead of a ready box, Vagrant expects a few conventions so that it can log in and configure the machine.

  1. A vagrant user with password vagrant and passwordless sudo.
  2. The Vagrant insecure public key in ~vagrant/.ssh/authorized_keys. On first boot, Vagrant replaces it with a random secure key unique to this machine.
  3. An SSH server running at boot.
  4. Guest tools: for VirtualBox, the Guest Additions (shared folders, time sync, clipboard). Without them, the default synced folder type will not work and you would need rsync or NFS.
  5. Network configured with DHCP on the first adapter (NAT).
  6. A clean disk: remove logs, caches, shell history, SSH host keys that are not regenerated, and unused packages.
  7. The right metadata.json for the provider.

The sudo rule is the one people forget:

TEXT
# /etc/sudoers.d/vagrant
vagrant ALL=(ALL) NOPASSWD:ALL

Never publish a box that contains secrets, private keys, shell history, database dumps or credentials. A box is a full disk copy; everything that was ever on the disk may be recoverable from it. Build public boxes from scratch with an automated tool, not from your personal machine.

Option 2: build boxes with Packer

Manual packaging gives a box nobody can reproduce. Packer (another HashiCorp tool) builds machine images from a template: it boots an operating system installer, types the answers, runs provisioning scripts, shuts down, and writes the box. The Bento boxes are made like this, and their templates are public. A minimal template in HCL looks like this (read-only; it needs Packer and a VirtualBox plugin):

HCL
source "virtualbox-iso" "ubuntu" {
  iso_url          = "https://releases.ubuntu.com/24.04/ubuntu-24.04-live-server-amd64.iso"
  iso_checksum     = "file:https://releases.ubuntu.com/24.04/SHA256SUMS"
  guest_os_type    = "Ubuntu_64"
  ssh_username     = "vagrant"
  ssh_password     = "vagrant"
  shutdown_command = "echo vagrant | sudo -S shutdown -P now"
}

build {
  sources = ["source.virtualbox-iso.ubuntu"]
  provisioner "shell" { script = "scripts/base.sh" }
  post-processor "vagrant" { output = "ubuntu-24.04-{{.Provider}}.box" }
}

The advantage is reproducibility: the template is code, changes are reviewed, and a CI system can rebuild the box monthly with the latest security updates. If you want a deeper Infrastructure as Code view, see the Terraform tutorial; Packer follows the same configuration style.

Box metadata and versions

To publish several versions on your own server, host a JSON file next to the boxes. Vagrant fetches it to learn which versions exist:

JSON
{
  "name": "shop/base",
  "description": "Ubuntu 24.04 with nginx and PostgreSQL",
  "versions": [
    {
      "version": "1.2.0",
      "providers": [
        {
          "name": "virtualbox",
          "url": "https://artifacts.example.com/shop-base-1.2.0.box",
          "checksum_type": "sha256",
          "checksum": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
        }
      ]
    }
  ]
}

Point the Vagrantfile at it with config.vm.box_url = "https://artifacts.example.com/shop-base.json". With this, vagrant box outdated works for your own boxes too, and box_version constraints apply. The runnable stand-in below checks such a metadata document the way a CI job could before publishing: valid JSON, semantic versions, one provider per version, checksums of the right length. It is a Ruby stand-in, not Vagrant.

Ruby Validating box metadata before publishing (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Keep it maintainable

  • Prefer building boxes from templates over snapshotting a hand-made machine.
  • Version every box and keep a changelog (what packages, what kernel).
  • Rebuild regularly: an old box is a security liability.
  • Keep boxes small; put project-specific installs in a provisioner so one base box serves many projects.
  • Test each new box with a throwaway project: vagrant up, vagrant ssh, a synced folder write, then vagrant destroy.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command turns an existing machine into a .box file?

    vagrant package shuts the VM down and compresses its disk and metadata into a box.
  2. 2. What does vagrant need in a base box in order to log in and run sudo?

    Vagrant connects over SSH as the vagrant user and relies on passwordless sudo for configuration.
  3. 3. What is Packer used for in this context?

    Packer builds images from code, which is repeatable, unlike packaging a hand-configured VM.
  4. 4. Why should a box never be made from a machine containing personal data?

    Everything on the disk goes into the box, including deleted-but-not-zeroed data and shell history.

Summary

  • A custom box moves slow, repeated setup to build time; use vagrant package for quick results.
  • A box is an archive with metadata, a default Vagrantfile and the provider's disk.
  • Base boxes need the vagrant user, key-based SSH, passwordless sudo, guest tools and a clean disk.
  • Packer templates make box builds repeatable and reviewable.
  • Host a metadata JSON to publish versions on your own server, and never ship secrets.

Next: Vagrantfile Load Order and Merging