How to automatically update UFW with Cloudflare IPs

Code for /root/update-cloudflare-ufw.sh:

#!/bin/sh

# Update weekly:
# Add this script to cron, using 'crontab -e'
# 0 0 * * 1 /root/update-cloudflare-ufw.sh > /dev/null 2>&1

TEMPFILE="/root/tmp.cloudflare_ips.tmp"

curl -s https://www.cloudflare.com/ips-v4 -o "$TEMPFILE"
curl -s https://www.cloudflare.com/ips-v6 >> "$TEMPFILE"

## Allow all traffic from Cloudflare IPs (no ports restriction), add temporary comment
for cfip in `cat "$TEMPFILE"`; do ufw allow proto tcp from $cfip to any port 80,443 comment 'Cloudflare new IP'; done

# Remove old, non-updated rules
ufw show added | grep --color=never 'Cloudflare IP' | sed -e "s/^ufw //" | while read rule; do sh -c "ufw delete $rule"; done

# Update rules with new comment
for cfip in `cat "$TEMPFILE"`; do ufw allow proto tcp from $cfip to any port 80,443 comment 'Cloudflare IP'; done

ufw reload > /dev/null
## How to install

This script will maintain itself, automatically removing any old IPs or IP segments found within active rules.

Copy the script to /root/update-cloudflare-ufw.sh, and make it executable:

chomd +x /root/update-cloudflare-ufw.sh

Add it to cron, using crontab -e:

 0 0 * * 1 /root/update-cloudflare-ufw.sh > /dev/null 2>&1