Setting the Timezone

It seems trivial… Set the timezone to the one you use on a day to day basis, or just leave it as whatever the default is. It’s not like it really matters… Except timezone selection is a very critical part of programming global systems. As the Yeller team writes in The Worst Server Setup Mistake You Can Make, timezone is an important thing to get right at the beginning, and unless you have very good reasons, you should be using UTC in most cases.

Editing the Timezone File

We’ve seen the copy module in action, during the last lesson to copy a full file, but this time we add a twist. Instead of actually needing to have a file on your local file system, we can actually just provide the contents of the file as a string using the “contents” option, and the copy module will take care of making sure it’s in a file on the remote system with the proper file permissions. Of course, this is only good to use when file contents are short, and stick to a separate file for lengthy configurations.

- name: Update Timezone to Etc/UTC
  copy: content="Etc/UTC\n" dest=/etc/timezone owner=root group=root mode=0644
  sudo: true
  register: timezone

As you can see, we’re just adding one line: “Etc/UTC” plus a return (newline character) which gets placed in /etc/timezone. Additionally, we register the output in a new variable called “timezone” so we can detect when changes are made to the /etc/timezone file.

Updating the System Timezone

We changed the timezone file, but to ensure the system picks up on our changes, we need to tell it to reconfigure itself using the new information. We could do this through a reboot, but we don’t want to invoke an unnecessary reboot when it can be prevented.

- name: Reconfigure Timezone Data
  shell: dpkg-reconfigure -f noninteractive tzdata
  sudo: true
  when: timezone.changed

We check the “timezone” variable and only run this reconfiguration task when the contents of /etc/timezone was actually changed. No changes, no need to reconfigure.

With minimal effort, we’ve saved many hours of headaches that would have resulted from using a local timezone and dealing with Daylight Savings Time changes (DST).

Full Playbook

---
- name: Configure the Timezone
  hosts: all
  tasks:

    - name: Update Timezone to Etc/UTC
      copy: content="Etc/UTC\n" dest=/etc/timezone owner=root group=root mode=0644
      sudo: true
      register: timezone

    - name: Reconfigure Timezone Data
      shell: dpkg-reconfigure -f noninteractive tzdata
      sudo: true
      when: timezone.changed