Howto generate a correctly incrementing DNS SOA Serial with Ansible

Deploying DNS zone files with Ansible can be annoying to set up if we want the SOA serial to be incremented according to the RFC, which requires a serial in the YYYYMMDDxx format, where YYYYMMDD is the deployment date and xx a daily increment.

The simplest way I found to do it with Ansible is the following variables in your role’s defaults/main.yml file :

today: "{{ lookup('pipe','date +%Y%m%d') }}"
epoch_midnight: "{{ lookup('pipe','date --date={{ today }} +%s') }}"
now: "{{ lookup('pipe','date +%s') }}"
num_secs: "{{ now|int - epoch_midnight|int }}"
day_incr: "{{ (num_secs|int * 99 / 86400)|int }}"
dns_serial : "{{ today }}{{ day_incr }}"

This provides a {{ dns_serial }} variable that you can use in your zone template. The daily increment part is calculated depending on the number of seconds elapsed since today at 00:00:00, multiplied by 99 divided by 86400, which allows for 99 increments in a given day. You may need to wait a few minutes before two deployments of the zone file for the increment to update, but it’s much easier than parsing the previously existing SOA serial.

Hope this helps.