Configuring NTP

Next up, we are copying the ntp.conf file from the templates folder, adding the list of NTP servers as we do, and then telling Ansible to restart NTP whenever the configuration file changes:

- name: copy the ntp.conf to /etc/ntp.conf
template:
src: "ntp.conf.j2"
dest: "/etc/ntp.conf"
notify: "restart ntp"

The template file can be found at roles/common/templates/ntp.conf.j2:

# {{ ansible_managed }}
driftfile /var/lib/ntp/drift
restrict default nomodify notrap nopeer noquery
restrict 127.0.0.1
restrict ::1
{% for item in ntp_servers %}
server {{ item }} iburst
{% endfor %}
includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys
disable monitor

As you can see, we are using the ntp_servers variable; this is stored in the roles/common/defaults/main.yml file:

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

Finally, the following task has been added to roles/common/handlers/main.yml:

- name: "restart ntp"
service:
name: "ntpd"
state: "restarted"

While we have notified the handler here, NTP will not be restarted to the end of the playbook run along with any other tasks we have notified.