Day 20 - Exploring the Vagrantfile

“If it works on my machine, it should work on yours too.” — Every developer, before they met Vagrant

Today I took a deep dive into the Vagrantfile, the core configuration file that powers Vagrant. It’s essentially a blueprint for spinning up reproducible, disposable development environments — and it’s surprisingly elegant once you understand its moving parts.


🔑 Key Elements I Explored

1. config.vm.box – The Base Image

This defines which operating system your VM will use. I used the popular Ubuntu image:

config.vm.box = "ubuntu/bionic64"

2. config.vm.hostname – Name Your VM

Sets a custom hostname for your virtual machine:

config.vm.hostname = "devops-vm"

3. config.vm.network – Private & Public IPs

Configure networking options like private IPs and port forwarding:

config.vm.network "private_network", ip: "192.168.33.10"
config.vm.network "forwarded_port", guest: 80, host: 8080

4. config.vm.provider – Customize Resources

You can allocate memory, CPU, and even name the VM instance:

config.vm.provider "virtualbox" do |vb|
  vb.name = "DevOpsVM"
  vb.memory = 2048
  vb.cpus = 2
end

5. config.vm.synced_folder – Sync Your Code

Keep a folder on your host synced with your guest machine (ideal for live development):

config.vm.synced_folder "./app", "/home/vagrant/app", type: "virtualbox"

🛠 Bonus: Shell Provisioning

Automate software installation when the VM boots up:

config.vm.provision "shell", inline: <<-SHELL
  sudo apt-get update
  sudo apt-get install -y nginx
  echo "Hello from Vagrant!" > /var/www/html/index.html
SHELL

This makes it incredibly easy to provision a complete dev environment in seconds.


⚙️ Full Example: My Vagrantfile

 Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/bionic64"
  config.vm.hostname = "devops-vm"
  config.vm.network "private_network", ip: "192.168.33.10"

  config.vm.provider "virtualbox" do |vb|
    vb.name = "DevOpsVM"
    vb.memory = 2048
    vb.cpus = 2
  end

  config.vm.network "forwarded_port", guest: 80, host: 8080
  config.vm.synced_folder "./app", "/home/vagrant/app", type: "virtualbox"

  config.vm.provision "shell", inline: <<-SHELL
    sudo apt-get update
    sudo apt-get install -y nginx
    echo "Hello from Vagrant!" > /var/www/html/index.html
  SHELL
end

📦 Takeaway

The Vagrantfile is more than just configuration — it's infrastructure as code. Once set up, you can share it with your team, run vagrant up, and know everyone is working in the same exact environment.


🚀 Next Steps

  • Try multi-machine setups (web + DB)

  • Use external provisioning tools like Ansible or Puppet

  • Explore alternative providers like Docker or Hyper-V


💬 Have you used Vagrant in your projects? What’s your favorite use case?


Tools

0
Subscribe to my newsletter

Read articles from Shaharyar Shakir directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shaharyar Shakir
Shaharyar Shakir