Only allow Cloudflare IPs for Discourse server

Well, you’re going to need the other rules too, so we might as well only download the list once. You missed replacing real_ip_header with deny all. Here’s a combined version:

run:
  - file:
      path: /tmp/add-cloudflare-ips
      chmod: +x
      contents: |
        #!/bin/bash -e
        # Download list of CloudFlare ips
        wget https://www.cloudflare.com/ips-v4/ -O - > /tmp/cloudflare-ips
        wget https://www.cloudflare.com/ips-v6/ -O - >> /tmp/cloudflare-ips
        # Make into nginx commands and escape for inclusion into sed append command
        CONTENTS1=$(</tmp/cloudflare-ips sed 's/^/allow /' | sed 's/$/;/' | tr '\n' '\\' | sed 's/\\/\\n/g')
        CONTENTS2=$(</tmp/cloudflare-ips sed 's/^/set_real_ip_from /' | sed 's/$/;/' | tr '\n' '\\' | sed 's/\\/\\n/g')

        echo CloudFlare IPs:
        echo $(echo | sed "/^/a $CONTENTS1")

        # Insert into discourse.conf
        sed -i "/sendfile on;/a deny all;$CONTENTS1\n $CONTENTS2\nreal_ip_header CF-Connecting-IP;" /etc/nginx/conf.d/discourse.conf
        # Clean up
        rm /tmp/cloudflare-ips

  - exec: "/tmp/add-cloudflare-ips"
  - exec: "rm /tmp/add-cloudflare-ips"

Save that to your cloudflare.allowdeny and remove the stock version from your app.yml. And then test it, of course :slight_smile:

5 Likes