Automation guides, explanations and reader checklists on whilenetworking.com

Ansible Workshop: Automating the Cleanup of Stale NTP Configurations Across Hybrid Cloud Infrastructure Using Jinja2 Templates

In modern hybrid cloud environments, time synchronization is not just a best practice; it is a critical operational requirement. Many legacy systems, virtual…

In modern hybrid cloud environments, time synchronization is not just a best practice; it is a critical operational requirement. Many legacy systems, virtual machines (VMs), and containers default to using ntpd or chrony pointing to public resolvers like pool.ntp.org. Over time, these configurations become “stale” due to organizational changes, security policies requiring internal NTP servers, or the decommissioning of specific data centers. Manually auditing hundreds of nodes across on-premise Linux servers, AWS EC2 instances, and Azure VMs is error-prone and inefficient. This workshop guide demonstrates how to use Ansible with Jinja2 templates to automate the detection and remediation of these stale configurations safely and efficiently.

Understanding the Risk of Stale NTP Configurations

A “stale” NTP configuration occurs when a server continues to query external time sources that are either deprecated, insecure, or no longer compliant with internal governance policies. For example, an organization might mandate the use of an internal Stratum 1 server located in their primary data center for all production workloads. If a new web tier is spun up on AWS using an AMI that defaults to pool.ntp.org, it becomes non-compliant immediately.

The risks extend beyond simple timestamp drift. Financial transactions, SSL certificate validation, and distributed tracing in microservices architectures rely on synchronized clocks. A server with a stale configuration might eventually fail to validate certificates or cause log correlation failures across the fleet. This guide focuses on replacing external public pools with an internal authoritative source using Ansible’s idempotent playbooks and dynamic inventory capabilities.

Prerequisites and Lab Environment Setup

Before executing any automation, ensure your environment meets the following requirements. You do not need a physical lab; a standard workstation with Docker or a VM running Ubuntu 22.04 LTS is sufficient for this exercise.

Required Tools:
* Ansible: Version 2.14 or later installed locally (ansible --version).
* Python: Required for Jinja2 templating (usually bundled with Ansible).
* SSH Access: You must have SSH access to a target group of servers. For this lab, we will simulate a hybrid inventory file containing entries for both on-premise hosts and cloud instances.
* Jinja2: The Python template engine used by Ansible for dynamic variable rendering.

Lab Scenario:
Imagine you manage a fleet of 10 servers: 5 running Ubuntu in an on-premise data center and 5 running Debian in the AWS cloud. Currently, all 10 are configured to use time.nist.gov. Your new policy requires all traffic to go through your internal server at ntp.internal.corp.

Step 1: Creating the Jinja2 Configuration Template

The core of this automation is a Jinja2 template that generates the specific configuration file needed for each operating system. This approach handles OS differences gracefully without hardcoding paths.

Create a file named ntp_config.j2 in your project directory with the following content:

{% if ansible_os_family == "Debian" %}
# Configuration for Debian/Ubuntu systems using chrony
{% set server = 'server ntp.internal.corp iburst' %}
{% set driftfile = '/var/lib/chrony/drift' %}
{% set makestep = 'no' %}
{% set commandpath = '/usr/sbin/chronyc' %}

[global]
driftfile {{ driftfile }}
makestep {{ makestep }}
commandpath {{ commandpath }}
rtcsync false
{% for server in servers %}
{{ server }}
{% endfor %}

[leapfile]
/etc/ntp/leap-seconds.file
{% elif ansible_os_family == "RedHat" %}
# Configuration for RHEL/CentOS/Fedora using ntpd
{% set server = 'server ntp.internal.corp iburst' %}

# /etc/ntp.conf
{% for server in servers %}
{{ server }}
{% endfor %}
{% endif %}

Explanation of the Template:
* Conditional Logic ({% if ... %}): The script detects the OS family using Ansible facts. If it is Debian-based, it generates a chrony config; if RedHat-based, it generates an ntpd config.
* Variable Injection: The servers variable will be populated dynamically by the inventory or group variables.
* Safety: This template does not delete existing files; it only prepares the content to be written.

Step 2: Defining the Inventory and Group Variables

Ansible uses an inventory file to manage targets. In a hybrid scenario, you can define specific groups for different environments.

Create an inventory.ini file:

[onprem_ubuntu]
host1 ansible_host=192.168.1.10
host2 ansible_host=192.168.1.11

[cloud_debian]
ec2-web-01 ansible_host=54.123.45.67
ec2-app-01 ansible_host=54.123.45.68

[all:vars]
ntp_servers=["server ntp.internal.corp iburst"]

Note on Hybrid Cloud: In a real-world scenario, you would use Ansible’s dynamic inventory plugins (like the AWS EC2 plugin) to pull live data from cloud providers instead of manually listing IPs. The [all:vars] section ensures that every target receives the new internal NTP server address.

Step 3: Developing the Remediation Playbook

Now, we create the main playbook cleanup_ntp.yml. This script checks for stale configurations and replaces them with the new ones defined in the Jinja2 template.

---
- name: Automate Cleanup of Stale NTP Configurations
  hosts: all
  become: yes
  gather_facts: yes

  tasks:
    - name: Detect current NTP configuration status
      shell: grep -i "pool.ntp.org\|time.nist.gov" /etc/ntp.conf /etc/chrony/chrony.conf 2>/dev/null
      register: stale_config_check
      changed_when: false

    - name: Render new NTP configuration using Jinja2
      template:
        src: ntp_config.j2
        dest: /tmp/new_ntp_config_{{ ansible_os_family }}.conf
      notify: Restart NTP Service

    - name: Backup existing NTP configuration
      copy:
        src: "{{ item }}"
        dest: "/etc/{{ item }}.backup.{{ ansible_date_time.date | date('%Y%m%d%H%M%S') }}"
      loop:
        - ntp.conf
        - chrony.conf
      when: stale_config_check.rc == 0

    - name: Apply new configuration to Debian/Ubuntu systems (chrony)
      lineinfile:
        path: /etc/chrony/chrony.conf
        regexp: '^#?server.*ntp\.internal\.corp'
        line: 'server ntp.internal.corp iburst'
        state: present
      when: ansible_os_family == "Debian"

    - name: Apply new configuration to RedHat systems (ntpd)
      copy:
        src: /tmp/new_ntp_config_{{ ansible_os_family }}.conf
        dest: /etc/ntp.conf
        mode: '0644'
      when: ansible_os_family == "RedHat"

    - name: Restart NTP services to apply changes
      service:
        name: "{{ item }}"
        state: restarted
      loop:
        - chrony
        - ntpd
      notify: Restart NTP Service

Key Components Explained:
* gather_facts: Collects OS information before running tasks.
* template: Renders the Jinja2 file, substituting variables like ansible_os_family.
* lineinfile vs copy: For Debian systems, we use lineinfile to modify an existing config safely. For RedHat, we might prefer replacing the whole file if the structure is complex (as shown in the copy task).
* when conditions: Ensure tasks only run on relevant OS families.

Step 4: Execution and Verification

To execute the playbook, navigate to your project directory and run:

ansible-playbook -i inventory.ini cleanup_ntp.yml -v

Expected Results:
* Ansible will output a summary showing which hosts had changes made (changed: yes) and which were already compliant.
* You should see the backup of old configurations being created.
* The NTP service restart messages will appear in the verbose output.

Verification Steps:
1. Check File Content: SSH into a target host and run cat /etc/chrony/chrony.conf or cat /etc/ntp.conf. Ensure only ntp.internal.corp is listed and no public pools remain.
2. Test Time Sync: On the target, run chronyc tracking or ntpq -p. Verify that the offset is decreasing and the server is locked to the internal source.
3. Review Logs: Check /var/log/syslog or /var/log/messages for any errors related to NTP startup.

Common Errors and Fixes

  • Error: “Permission denied” when writing config files.
    • Fix: Ensure you are using become: yes (sudo) in the playbook header. If specific directories require different permissions, adjust the mode parameter in the copy task.
  • Error: Jinja2 variable undefined.
    • Fix: Check that your inventory file includes the [all:vars] section or that you are passing -e "ntp_servers=..." via the command line.
  • Error: Service restart fails immediately after config change.
    • Fix: Some NTP daemons require a reboot or a specific makestep setting to jump in time. If the service refuses to start, check if the internal server (ntp.internal.corp) is actually reachable and responding.

Industry Application and Student Practice Task

Industry Application:
In a DevOps pipeline, this playbook should be integrated into a CI/CD workflow (e.g., GitLab CI or GitHub Actions). When a new image is deployed to Kubernetes nodes or bare metal servers, the Ansible playbook runs as part of the “Post-Deploy” stage. This ensures that every new node automatically adopts the correct time sync policy without human intervention.

Student Practice Task:
1. Set up two virtual machines: one Ubuntu and one CentOS.
2. Configure both to use pool.ntp.org.
3. Create an Ansible inventory file pointing to these two VMs.
4. Write a simple Jinja2 template that outputs different strings based on the OS family.
5. Run the playbook and verify that both VMs now point to your local machine (or a public test server like time.google.com if you don’t have an internal one).
6. Document the output of the verification commands in a markdown file.

Conclusion

Automating the cleanup of stale NTP configurations is a vital step in maintaining hybrid cloud security and reliability. By leveraging Ansible’s ability to detect OS families and Jinja2 templates for dynamic content generation, engineers can enforce time synchronization policies across diverse infrastructures with minimal manual effort. This approach reduces human error, ensures compliance with internal governance, and secures the temporal integrity of distributed systems. Always remember to backup configurations before making bulk changes and verify connectivity to your authoritative time source before rolling out updates to production environments.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.