Ansible: syncing Linux to AD time

Requirements: the PDC address is looked up from Active Directory DNS, so the machine you’re running the playbook against must be able to resolve names from the domain namespace. Assumes your timezone is set correctly.

ansible/setup-domaintime-linux/setup-domaintime-linux.yaml :

- hosts: all
  user: localuser
  become: true

  vars:
    pkgs:
      - chrony
      - bind-utils

  vars_prompt:
    - name: domain_fqdn
      prompt: "Enter domain FQDN to search for PDC (example: mydomain.local)"
      private: no

  tasks:

  - name: Checking if running RedHat/CentOS
    fail:
      msg: The system is not running RedHat/CentOS, aborting
    when: ansible_facts['os_family'] != 'RedHat'

  - name: Ensuring ntpdate is absent
    dnf:
      name: ntpdate
      state: absent

  - name: Ensuring chrony and bind-utils are present
    yum: name={{ pkgs }} state=present update_cache=yes

  - name: Masking ntpd service
    systemd:
      name: ntpd
      enabled: no
      masked: yes
      state: stopped

  - name: Looking up PDC in AD DNS
    shell: nslookup -q=SRV _ldap._tcp.pdc._msdcs.{{ domain_fqdn }} | grep _ldap | awk '{print $7}' | head --bytes -2
    register: PDClookup
  - set_fact:
      PDCfqdn : "{{ PDClookup.stdout }}"

  - name: Configuring chrony.conf
    template:
      src: chrony.conf.j2
      dest: /etc/chrony.conf
      owner: root
      group: root
      mode: 0644

  - name: Enabling chronyd service
    systemd:
      name: chronyd
      enabled: yes
      state: restarted

ansible/setup-domaintime-linux/templates/chrony.conf.j2 :

server {{ PDCfqdn }} iburst

driftfile /var/lib/chrony/drift
makestep 0.1 3
rtcsync

logdir /var/log/chrony
log measurements statistics tracking

leapsectz right/UTC

ansible/setup-domaintime-linux/ansible.cfg :

[defaults]
inventory           = hosts
host_key_checking   = False
become_method       = sudo

ansible/setup-domaintime-linux/hosts :

[all]
virtualhostname ansible_host=192.168.1.60 ansible_ssh_user=localuser