External MQTT sensor through CloudFlare

For anyone else who needs this, assume you’re OK with:

Then I got this working for publishing/subscripting to the mosquito-broker (that is spun-up by the MQTT add-on) externally (to my home-network), again using the websocket protocol by configuring the cloudflared add-on to specify in the additional_hosts section as follows:

       "options": {
-        "additional_hosts": [],
+        "additional_hosts": [
+          {
+            "hostname": "mqtt-home.yourdomain.com",
+            "service": "http://core-mosquitto:1884"
+          }
+        ],

(the above is a diff from the addon.json (i track my changes in git), please YAML’ify it as needed - you’ll then need to restart cloudflared add-on)

I then confirmed/tested it working externally using a container, connecting to the mqtt-home.yourdomain.com:80 (i chose port 80 for simplicity):

$ docker run -it --rm hivemq/mqtt-cli pub -t test/topic -m "Hello MQTT over WebSocket woohoo" -h mqtt-home.yourdomain.com -p 80 -ws -u 'mqtt-user' -pw 'mqtt-password'

In order to confirm messages were arriving, in another window, i would already be running before executing previous command in my local network:

$ docker run -it --rm hivemq/mqtt-cli sub -t test/topic -h homeassistant.lan -p 1884 -ws -u 'mqtt-user' -pw 'mqtt-password'
Hello MQTT over WebSocket woohoo

if TLS is a hard-requirement for you, you could point it to https://core-mosquitto:8884 (and you’d need to update the port you use to one of the HTTPS ports allowed by cloudflare)

I was able to test it using:

$ docker run -it --rm hivemq/mqtt-cli pub -t test/topic -m "Hello MQTT over WebSocket+TLS?" -u 'mqtt-user' -pw 'mqtt-password' -h mqtt-home.mydomain.com -p 443 -ws -s --tls-version TLSv1.2

Note: the device you’re setting up external mqtt-access for needs to be able to support a custom port (80 for non-TLS or 443 for TLS in my case) and the websocket protocol (often specified as ws://mqtt-home.mydomain.com:80/ or wss://mqtt-home.mydomain.com:443/ or using a flag to specify the websocket protocol to be used).