Automate the whitelisting of Cloudflare IPs

I use Cloudflare in front of my Traefik proxy. I'd like to whitelist the Cloudflare IPs so that people can't bypass Cloudflare and connect directly to my server's IP address. Because the Cloudflare IPs can change, it would also be great to have some kind of a bash script that adds the new IPs into traefik.yml. Here is my current docker compose file:

services:

  traefik:
    image: traefik:latest
    ports:
      - 80:80
      - 443:443
      - 8080:8080
#      - 853:853
    environment:
      - CF_DNS_API_TOKEN=redacted
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./traefik.yml:/etc/traefik/traefik.yml
      - ./acme.json:/acme.json
      - ./routes/:/routes
networks:
  default:
    name: traefik_access

and my traefik.yml:



certificatesResolvers:
  le-ssl:
    acme:
      email: gregor@gregtech.eu
      storage: /acme.json
      dnsChallenge:
        provider: cloudflare
        resolvers:
          - "1.1.1.1:53"
          - "1.0.0.1:53"

providers:
  docker:
    exposedByDefault: false
    network: traefik_access

log:
  level: DEBUG
accessLog: {}

api:
  dashboard: false
  insecure: false

# Restore Real IP from Cloudflare
entryPoints:
  http:
    address: ":80"
    forwardedHeaders:
      trustedIPs:
        - "103.21.244.0/22"
        - "103.22.200.0/22"
        - "103.31.4.0/22"
        - "104.16.0.0/13"
        - "104.24.0.0/14"
        - "108.162.192.0/18"
        - "141.101.64.0/18"
        - "162.158.0.0/15"
        - "172.64.0.0/13"
        - "173.245.48.0/20"
        - "188.114.96.0/20"
        - "190.93.240.0/20"
        - "197.234.240.0/22"
        - "198.41.128.0/17"
        - "2400:cb00::/32"
        - "2606:4700::/32"
        - "2803:f800::/32"
        - "2c0f:f248::/32"
        - "2a06:98c0::/29"
  https:
    forwardedHeaders:
      trustedIPs:
        - "103.21.244.0/22"
        - "103.22.200.0/22"
        - "103.31.4.0/22"
        - "104.16.0.0/13"
        - "104.24.0.0/14"
        - "108.162.192.0/18"
        - "141.101.64.0/18"
        - "162.158.0.0/15"
        - "172.64.0.0/13"
        - "173.245.48.0/20"
        - "188.114.96.0/20"
        - "190.93.240.0/20"
        - "197.234.240.0/22"
        - "198.41.128.0/17"
        - "2400:cb00::/32"
        - "2606:4700::/32"
        - "2803:f800::/32"
        - "2c0f:f248::/32"
        - "2a06:98c0::/29"

    address: ":443"

Perhaps I could use IPAllowList?

The middleware is only processed after routing, so has no influence on the trustedIPs.

Changing Traefik static config to update trustedIPs would require a restart of the Traefik service.

Not sure if it’s worth the hassle, those IPs usually change very rarely.