Auto-update Pi-hole with systemd timer

I have two Pi-hole servers at home running Fedora with DNS over TLS, both of which auto update on different days (to avoid having both down if something goes wrong).

First, create a script to get the latest updates if any are available, rebooting the Pi-hole if they were successful.

cat << \EOF | sudo tee /usr/local/sbin/update-pihole.sh
#!/bin/bash
PIHOLE_UPDATE="$(pihole -up --check-only)"
if ! grep -q 'Everything is up to date' <<< "${PIHOLE_UPDATE}" ; then
  pihole -up
  if [[ $? -eq 0 ]] ; then
    echo "$(date "+%h %d %T") update: success" >> /var/log/pihole.log
    reboot
  fi
else
    echo "$(date "+%h %d %T") update: nothing to do" >> /var/log/pihole.log
fi
EOF

Make the script executable.

sudo chmod a+x /usr/local/sbin/update-pihole.sh

Next, let’s create a systemd service for the update, which is required to be able to create a timer.

cat << EOF | sudo tee /etc/systemd/system/update-pihole.service 
[Unit]
Description=Update pihole
After=network-online.target
 
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/update-pihole.sh
EOF

Now we can create the systemd timer. Here I am updating weekly on Mondays at midnight (my other Pi-hole updates weekly on Thursdays), feel free to adjust as you see fit. If you have two, perhaps update on alternate days, like I do.

cat << EOF | sudo tee /etc/systemd/system/update-pihole.timer 
[Unit]
Description=Timer for updating pihole
Wants=network-online.target
 
[Timer]
OnBootSec=
OnCalendar=Mon *-*-* 00:00:00
Persistent=true

[Install]
WantedBy=timers.target
EOF

Now that we have the timer, we can tell systemd about it and enable the timer.

sudo systemctl daemon-reload
sudo systemctl enable --now update-pihole.timer

That it’s it! Your systems will now check for updates and be rebooted if necessary. It might be good to pair this with some monitoring to ensure that your Pi-holes are working as expected and be alerted if otherwise…

Leave a Reply

Your email address will not be published. Required fields are marked *