v8fr2g
Last Updated: September 19, 2017
·
8.959K
· gmr
Gavinr

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.

Say Thanks
Respond

2 Responses
Add your response

10237
855ad36e5a7f08ccf256948898b2d8e5

Cool! I've reworked your solution to execute always (not only for UTC) and handle GMT negative cases GMT-2 etc (coderwall new line formatting sucks big time)

/# Set the Timezone to host timezone
require 'time'
offset = ((Time.zoneoffset(Time.now.zone)/60)/60)
zone
sufix = offset >= 0 ? "+#{offset.tos}" : "#{offset.tos}"
timezone = 'Etc/GMT' + zone_sufix
config.vm.provision :shell, :inline => "echo \"#{timezone}\" | sudo tee /etc/timezone && dpkg-reconfigure --frontend noninteractive tzdata"

over 1 year ago ·
26409
None

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 ·
Filed Under