Files
ansible/playbooks/time-region-ntp.yml
T

106 lines
3.2 KiB
YAML

---
- name: Configure timezone and NTP
hosts: all
become: yes
vars:
timezone_region: "Asia/Kolkata"
ntp_server: "0.in.pool.ntp.org"
tasks:
# ----------------------------------------------------------
# TIMEZONE (Works on Ubuntu LXC + Rocky)
# ----------------------------------------------------------
- name: Set timezone (manual method for compatibility)
block:
- name: Copy timezone file
ansible.builtin.copy:
src: "/usr/share/zoneinfo/{{ timezone_region }}"
dest: /etc/localtime
remote_src: yes
- name: Write /etc/timezone
ansible.builtin.copy:
dest: /etc/timezone
content: "{{ timezone_region }}\n"
register: tz_change
- name: Debug timezone set
ansible.builtin.debug:
msg: "Timezone set to {{ timezone_region }} successfully."
when: tz_change.changed
# ----------------------------------------------------------
# UBUNTU NTP (systemd-timesyncd)
# ----------------------------------------------------------
- name: Configure NTP for Ubuntu (systemd-timesyncd)
block:
- name: Create timesyncd.conf
ansible.builtin.copy:
dest: /etc/systemd/timesyncd.conf
content: |
[Time]
NTP={{ ntp_server }}
FallbackNTP=1.in.pool.ntp.org 2.in.pool.ntp.org
register: ubuntu_ntp
- name: Restart timesyncd
ansible.builtin.systemd:
name: systemd-timesyncd
state: restarted
enabled: yes
- name: Debug Ubuntu NTP
ansible.builtin.debug:
msg: "Ubuntu NTP configured with {{ ntp_server }}"
when: ubuntu_ntp.changed
when: ansible_facts['os_family'] == "Debian"
# ----------------------------------------------------------
# ROCKY LINUX NTP (chrony)
# ----------------------------------------------------------
- name: Configure NTP for Rocky Linux (chrony)
block:
- name: Install chrony
ansible.builtin.package:
name: chrony
state: present
- name: Backup chrony.conf
ansible.builtin.copy:
src: /etc/chrony.conf
dest: /etc/chrony.conf.bak
remote_src: yes
- name: Remove existing server lines
ansible.builtin.replace:
path: /etc/chrony.conf
regexp: '^server .*'
replace: ''
register: removed_servers
- name: Add new time server entry
ansible.builtin.lineinfile:
path: /etc/chrony.conf
line: "server {{ ntp_server }} iburst"
- name: Restart chronyd
ansible.builtin.systemd:
name: chronyd
state: restarted
enabled: yes
- name: Debug Rocky NTP
ansible.builtin.debug:
msg: "Rocky Linux NTP configured with {{ ntp_server }}"
when: ansible_facts['os_family'] == "RedHat"
# ----------------------------------------------------------
# Final output
# ----------------------------------------------------------
- name: Final summary
ansible.builtin.debug:
msg: "Timezone + NTP successfully applied on {{ inventory_hostname }}"