Skip to main content

NTP Configuration on Linux

In this article, we will learn how to configure NTP on Linux using Ansible.

You can directly visit the full code here.

Define the Ansible Inventory

The playbook is set to run on all hosts defined in the ansible_hosts group. It will gather facts about these hosts, which can be used in later tasks. The become and become_method directives are used to gain administrative privileges.

- hosts: ansible_hosts
gather_facts: true
become: yes
become_method: sudo

Define the Ansible Variables

The ntp_servers variable is defined, which is a list of NTP servers that the target hosts will be configured to use.

vars:
ntp_servers:
- "0.uk.pool.ntp.org"
- "1.uk.pool.ntp.org"
- "2.uk.pool.ntp.org"
- "3.uk.pool.ntp.org"

Define the Ansible Handlers

A handler is defined to restart the NTP service. This handler can be triggered by tasks later in the playbook.

handlers:
- name: "restart ntp"
ansible.builtin.service:
name: "ntp"
state: "restarted"

Define tasks

The tasks section is where the main actions of the playbook are defined. In this case, the tasks are:

  • Print a debug message with information about the target host.
  • Update all packages on the target host.
  • Install the ntp, sntp, and ntp-doc packages.
  • Use a template to create the /etc/ntp.conf file on the target host, and notify the "restart ntp" handler if the file changes.
tasks:
- ansible.builtin.debug:
msg: "I am connecting to {{ ansible_nodename }} which is running {{ ansible_distribution }} {{ ansible_distribution_version }}"
- ansible.builtin.apt:
name: "*"
state: "latest"
update_cache: "yes"
- ansible.builtin.apt:
state: "latest"
pkg:
- "ntp"
- "sntp"
- "ntp-doc"
- ansible.builtin.template:
src: "./ntp.conf.j2"
dest: "/etc/ntp.conf"
notify: "restart ntp"

Full Code

---

- hosts: ansible_hosts
gather_facts: true
become: yes
become_method: sudo

vars:
ntp_servers:
- "0.uk.pool.ntp.org"
- "1.uk.pool.ntp.org"
- "2.uk.pool.ntp.org"
- "3.uk.pool.ntp.org"

handlers:
- name: "restart ntp"
ansible.builtin.service:
name: "ntp"
state: "restarted"

tasks:
- ansible.builtin.debug:
msg: "I am connecting to {{ ansible_nodename }} which is running {{ ansible_distribution }} {{ ansible_distribution_version }}"
- ansible.builtin.apt:
name: "*"
state: "latest"
update_cache: "yes"
- ansible.builtin.apt:
state: "latest"
pkg:
- "ntp"
- "sntp"
- "ntp-doc"
- ansible.builtin.template:
src: "./ntp.conf.j2"
dest: "/etc/ntp.conf"
notify: "restart ntp"