Getting the Correct Time in a Vagrant Box

For Redbox's Magento 2 virtual machine, I made the prompt fancy. It works really well, and having a bit of extra information inside the virtual machine is dead handy.

The prompt has the time, hostname, working directory and Git branch

The prompt has the time, hostname, working directory and Git branch

When I first did this, I had a major problem, in that the time was not even remotely close to being correct. After much hemming, hawing, and generally being unsuccessful, I found the thing that seems to work.

Add the following to your Vagrantfile:


config.vm.provider "virtualbox" do |vb|
  # Compare the time every 10 seconds   
  vb.customize [
    "guestproperty",
    "set",
    :id,
    "/VirtualBox/GuestAdd/VBoxService/--timesync-interval",
    "10000"
  ]

  # Only change when it is ±0.1s out.
  vb.customize [
    "guestproperty",
    "set",
    :id,
    "/VirtualBox/GuestAdd/VBoxService/--timesync-min-adjust",
    "100"
  ]

  # Resync time when we restart.
  vb.customize [
    "guestproperty",
    "set",
    :id,
    "/VirtualBox/GuestAdd/VBoxService/--timesync-set-on-restore",
    "1"
  ]

  # Only change by 1 second at a time.
  #
  # Changing the time a lot can confuse processes that interrogate
  # the time to do their work.
  vb.customize [
    "guestproperty",
    "set",
    :id,
    "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold",     
    "1000"
  ]
end

My understanding is that by default, VirtualBox will sync time between host and guest, but that the rate it does it at is not useful for something like this. These settings fiddle to give a meaningful time to a regular Joe like you or me.

Vagrant actually allows you a great deal of customisation of VirtualBox's behaviour through this customize method. The array is simply a list of parameters passed to the VBoxManage command, where the :id variable is the ID of the virtual machine Vagrant creates. I just ripped these settings from this Stack Exchange answer.

As a fun aside, if time is set incorrectly, Magento will set cookies that have already expired, making it impossible to log into various things.