Last Updated: May 12, 2022
·
12.94K
· gmr

A quick hack to set the timezone for a Vagrant VM in Ubuntu

I wanted to make sure that the Vagrant VM I was building was always in sync with the host timezone. After poking about and not finding any real elegant way to do it, I came up with the following hack for an Ubuntu VM.

NOTE: This only works if the VM is set to UTC in /etc/timezone

The snippet:

Vagrant.configure(2) do |config|

  # Set the timezone to the host timezone
  require 'time'
  timezone = 'Etc/GMT' + ((Time.zone_offset(Time.now.zone)/60)/60).to_s
  config.vm.provision :shell, :inline => "if [ $(grep -c UTC /etc/timezone) -gt 0 ]; then echo \"#{timezone}\" | sudo tee /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata; fi"

end

Using Ruby's time class, the timezone variable is assigned the string of Etc/GMT-# where # is the calculated timezone offset cast to a string.

Upon boot of the vm, grep will check to see if /etc/timezone is set to UTC and if so, put the value of the timezone variable in /etc/timezone, then call dpkg-reconfigure to update the OS to use the value set in /etc/timezone.

1 Response
Add your response

Also some multi-string syntax makes things easier to read/modify later:

config.vm.provision :shell, :inline => %Q(
  if [ $(grep -c UTC /etc/timezone) -gt 0 ]
    then echo "#{timezone}" | sudo tee /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata
  fi
)
over 1 year ago ·