Vagrant Sync Directories

Vagrant Sync Directories | Vagrant makes it easy to sync directories between your host machine and the guest virtual machine (VM). This ensures that you can work on files on your host system while having them available inside the VM.

Starting Vagrant and Checking Synced Directories

When you start your Vagrant environment, you can see the sync directories mapping in the logs:

$ vagrant up
default: C:/install/vagrant-vms/ubuntu => /vagrant

Example of Syncing Directories

  1. Creating a File on the Host:
$ ls
Vagrantfile

$ touch test1.txt

$ ls -a
./  ../  .vagrant/  Vagrantfile  test1.txt
  1. Accessing Synced Directory in the VM:
$ vagrant ssh

vagrant@ubuntu-jammy:~$ cd /vagrant/

vagrant@ubuntu-jammy:/vagrant$ ls
Vagrantfile  test1.txt

The /vagrant/ directory in the VM is synced with the host directory where the Vagrantfile is located. Any files created in the VM inside /vagrant/ will also appear in the host directory, and vice versa.

  1. Creating Multiple Files in VM:
vagrant@ubuntu-jammy:/vagrant$ touch file{1..20}.txt
  1. Deleting Files in VM:
vagrant@ubuntu-jammy:/vagrant$ rm -rf file*

Configuring Additional Synced Folders

To sync another host directory with the VM, follow these steps:

  1. Create the Host Directory: For example, C:\workspace\scripts\shellscripts.
  2. Edit the Vagrantfile to Add Synced Folder:
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.

# Windows Path
config.vm.synced_folder "C:\\workspace\\scripts\\shellscripts", "/opt/scripts"

# MacOS
# config.vm.synced_folder "/Users/yourusername/workspace/scripts/shellscripts", "/opt/scripts"
  1. Reload Vagrant to Apply Changes:
$ exit
$ vagrant reload

During reload, you will see the new sync directory configuration in the logs:

...
default: C:/install/vagrant-vms/ubuntu => /vagrant
default: C:/workspace/scripts/shellscripts => /opt/scripts

Purpose of Using Synced Directories

Ease of Editing: You can use your favorite text editor on the host machine to write scripts or code, save them in the synced directory, and immediately access and run them in the VM.

Preserve VM Files: Syncing directories ensures that your files are stored on the host machine. If the VM is aborted or corrupted, your files remain safe on the host.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *