--- # Sets the timezone on every Ubuntu/Rocky guest. LXC containers share the # host's clock, so NTP is disabled inside them; VMs sync against ntp_server. # # Extra vars (optional): # timezone_region - default America/New_York # ntp_server - default time.google.com - name: Configure timezone hosts: ubuntu:rocky become: true vars: timezone_region: America/New_York tasks: - name: Link /etc/localtime to the zoneinfo file ansible.builtin.file: src: "/usr/share/zoneinfo/{{ timezone_region }}" dest: /etc/localtime state: link force: true - name: Write /etc/timezone ansible.builtin.copy: dest: /etc/timezone content: "{{ timezone_region }}\n" owner: root group: root mode: '0644' # The plays below reuse the facts gathered above instead of collecting them again. - name: NTP on Ubuntu hosts: ubuntu become: true gather_facts: false vars: ntp_server: time.google.com tasks: - name: Stop and mask timesyncd in LXC containers ansible.builtin.systemd: name: systemd-timesyncd state: stopped enabled: false masked: true when: ansible_virtualization_type == "lxc" - name: Point timesyncd at ntp_server on VMs ansible.builtin.lineinfile: path: /etc/systemd/timesyncd.conf regexp: '^#?NTP=' line: "NTP={{ ntp_server }}" when: ansible_virtualization_type != "lxc" notify: Restart timesyncd handlers: - name: Restart timesyncd ansible.builtin.systemd: name: systemd-timesyncd state: restarted enabled: true - name: NTP on Rocky Linux hosts: rocky become: true gather_facts: false vars: ntp_server: time.google.com tasks: - name: Stop and mask chronyd in LXC containers ansible.builtin.systemd: name: chronyd state: stopped enabled: false masked: true when: ansible_virtualization_type == "lxc" # The lookahead keeps the server line added below from being commented # out again on the next run. - name: Disable the default chrony pools on VMs ansible.builtin.replace: path: /etc/chrony.conf regexp: '^(pool|server)\s+(?!{{ ntp_server | regex_escape }}(\s|$)).*' replace: '# \g<0> (disabled by Ansible)' when: ansible_virtualization_type != "lxc" notify: Restart chronyd - name: Point chrony at ntp_server on VMs ansible.builtin.lineinfile: path: /etc/chrony.conf regexp: '^server\s+{{ ntp_server | regex_escape }}(\s|$)' line: "server {{ ntp_server }} iburst" when: ansible_virtualization_type != "lxc" notify: Restart chronyd handlers: - name: Restart chronyd ansible.builtin.systemd: name: chronyd state: restarted enabled: true - name: Verify time configuration hosts: ubuntu:rocky become: true gather_facts: false tasks: - name: Check current system time ansible.builtin.command: date register: check_time changed_when: false - name: Summary ansible.builtin.debug: msg: "{{ inventory_hostname }} ({{ ansible_virtualization_type | default('unknown') }}) - {{ check_time.stdout }}"