Terraform set timezone upon virtual machine creation


Sometimes it’s important to set proper timezone on the server and recently I’ve got this task: set proper timezone automatically based on the server’s location in Azure Cloud. Moreover, I needed timezone to be set automatically by Terraform upon virtual machine creation.  In my case I had Ubuntu VMs in Azure and here is the simple and elegant solution I came with:

Detect server’s timezone based on the location with World Time API

Amazing resource that shows all time-related information in either JSON or text format.

For example:

To get the same information in simple text format prepend the request with “.txt” as follows:

And timezone can be easily get with standard bash commands “grep” and “cut” as follows:

In Ubuntu timezone can be set as:

So what we need now is to use results from World Time API as an argument to timedatectl command. As simple as:

Notice backticks around curl… command! It means “fill this place with execution result”.

And the last piece of the puzzle:

Set timezone automatically in Terraform

The command above can be used in remote-exec provisioner right after VM is created:

The last three commands: set virtual machine’s timezone based on it’s location, enable NTP syncronization and display current date/time and other timezone information so you can ensure it was set correctly.

That’s it! Have fun!

Want me to do this for you? Drop me a line: itgalaxyzzz {at} gmail [dot] com