Last Updated: September 19, 2017
· 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(
  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"


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.

2 Responses
Add your response

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(
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 ·

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
over 1 year ago ·