Publishing & Subscribing to MQTT Topics Using Mosquitto Client Tools & Microsoft Azure IoT Hub

Public cloud brings a paradigm shift in what can be done, the art of the possible is possible and in the context of this post, I am planning to replicate ~250ish MQTT topics running in a Mosquitto MQTT container in to Azure IoT Hub.

From ML (Machine Learning) through to anomaly detection and everything in between, the bells and whistles Azure graces myself is far and beyond the capabilities of any on premise system, coupled with low administrative effort of consuming a managed service.

Who has the longest showers? Who wakes up first? Which devices are powered on, yet their is no activity? These questions and many can all be answered from the thousands events occurring each day in my house, but first we need to get these events in to Azure.

Today I use Mosquitto (in docker container) locally with Home Assistant, Tasmota devices, a PLC and a Arduino Mega. I publish and consume thousands of messages each day (1.4messages per second, which is mostly PIR data). The easiest path here is to not have these devices publish to Azure IOT Hub, but to have Mosquitto replicate all messages locally through to Azure IoT Hub. Remember the 3 laws of IOT, one of them being the law of physics.

Latency to the cloud can be unacceptable, think crash avoidance system and medical alerts, but here it’s my snarky 10 year old wondering why there is so much lag when a button is pressed.

Therefore some decision-making must continue to be executed locally and in the absence of not having internet, my house must continue to function.

Ideally something like this image below, once we are publishing events in Azure IoT Hub we are then able to leverage these in the Azure platform as described above.

What we want to do

The thing is, you need to crawl before you can walk and in this post I will illustrate how you can create an Azure IoT-Hub, a device and publish/subscribe MQTT (version 3.11 compliant) messages via Mosquitto client tools (mosquitto_pub / mosquitto_sub) to Azure IoT Hub and we will do this using the Azure CLI.

What we will do

What is Azure IoT Hub?
Azure IoT Hub brings highly secure and reliable communication between your Internet of Things (IoT) application and the devices it manages. Some key features are per-device authentication, built-in device management and scaled provisioning. From an IOT perspective it provides AMQP, MQTT and HTTP endpoints and its MQTT we will be focusing on in this post. It does a lot, but in the context of this post, think of it as your MQTT broker in the cloud that you dont need to manage.

How about AZ-CLI?
Simply put, your CLI (Command Line Interface) for Azure. It is a cross-platform CLI to connect to Azure and execute administrative commands on Azure resources. It allows the execution of commands through a terminal using interactive command-line prompts or a script. The Azure CLI, known as AZ CLI is available across Azure services and is designed to get you working quickly with Azure, with an emphasis on automation and I see it as that interim step between the console and using a direct SDK or service API. You can find more information on Azure CLI here.

You can install the Azure CLI locally on Linux, Mac, or Windows computers. It can also be used from a browser through the Azure Cloud Shell (very cool 👍👍) or run from inside a Docker container.

I am not going to cover setting up Azure CLI, see the Azure CLI setup guide for more information on setting up and configuring for your subscription.

Enough about this, lets get started.

High Level Steps
1. Create Azure IoT Hub
2. Extract Connection Strings
3. Create IoT Device
4. Create SAS Policy
5. TLS Certificate
6. Pulling It Together
7. Mosquitto_pub/Mosquitto_sub

Variables You Will Need To Substitute
This post serves as a high level walkthrough for establishing full duplex (publish and subscribe) communication from your local broker in to Azure. You will be presented with outputs from CLI or from your Azure subscription, that you will need to substitute with your values in order to pass in to the Mosquitto client tools. Some key values you need to substitute.

Device name
SAS token 
Connection string

Step 1: Create the Azure IoT Hub
You will need to firstly create your Azure IoT Hub instance. There are many SKU’s but the F1 SKU provides 8000 messages per day for free and is a good way to get started without incurring cost. Alternate SKU’s can be found here.

az iot hub create --resource-group BaldacchinoRG --name Baldacchino-IOTHub -sku F1 --partition-count 2

The output of this command will provide a lot of JSON. Extract your Azure IoT-Hub endpoint. Copy and paste this in to a document in your favourite IDE, we will be adding many values to this document to build out the required.

"hostName": "",

Step 2: Extract the Primary Connection String
You will need to identify the connection string of your IOT-Hub

az iot hub connection-string show

This output of this command will provide your connection string (there is two, this will only show the primary). Copy and paste this in to your document.

    "connectionString": ";SharedAccessKeyName=iothubowner;SharedAccessKey=******************************************************=",
    "name": "Baldacchino-IOTHub"

Step 3: Create your device
You now need to create your MQTT device, for the purpose of this walkthrough we will use a SAS token for authentication.

az iot hub device-identity create -n Baldacchino-IOTHub -d Mosquitto

There is no JSON you will need to copy to your clipboard here but you will notice in the JSON output that the type is SAS and we not using x509 certificates.

"type": "sas",
"x509Thumbprint": {
"primaryThumbprint": null,
"secondaryThumbprint": null
"capabilities": {
"iotEdge": false

Step 4: Generate a SAS token
There are multiple ways to provide Authentication. SAS tokens and x509 certificates are the common approaches.
The SAS token is a string that you generate on the client side, and you pass this string to Azure IoT Hub for authentication. Azure IoT Hub then checks the SAS parameters and the signature to verify that it is valid.

az iot hub generate-sas-token -d Mosquitto -n Baldacchino-IOTHub

Copy and paste the SharedAccessSignature from the JSON output in your document.

  "sas": "SharedAccessSignature"

Step 5: We need TLS
MQTT typically runs on port 1833 in an unsecure manner but Azure IoT Hub mandates MQTT over TLS on 8883. The root CA is not part of your Operating System’s keychain and as such you will need to download the PEM file to use with Mosquitto.

You can download the certificate from GitHub at Copy the Baltimore certificate, to save you some time I have pasted this below, and save it as Baltimore.pem


You can validate your TLS certificate by using openSSL

openssl x509 -in Balitore.pem -text
Version: 3 (0x2)
Serial Number: 33554617 (0x20000b9)
Signature Algorithm: sha1WithRSAEncryption
Issuer: C = IE, O = Baltimore, OU = CyberTrust, CN = Baltimore CyberTrust Root
Not Before: May 12 18:46:00 2000 GMT
Not After : May 12 23:59:00 2025 GMT
Subject: C = IE, O = Baltimore, OU = CyberTrust, CN = Baltimore CyberTrust Root
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
X509v3 Basic Constraints: critical
CA:TRUE, pathlen:3
X509v3 Key Usage: critical
Certificate Sign, CRL Sign
Signature Algorithm: sha1WithRSAEncryption

Step 6: Pulling it together
We will soon be using Mosquitto_pub and Mosquitto_sub to publish and subscribe to messages. I am going to assume you have these installed on your local environment.

You can easily install this on a Debian based environment with the following command.

sudo apt install mosquitto-clients

For Windows and MAC, see the Mosquitto website.
We now have everything we need for Mosquitto but publish and subscribe have different required parameters for publishing and subscribing.

What Mosquitto_pub needs

mosquitto_pub \
-t "MQTT topic name" \
-i "pub_client" \
-u "username" \
-P "password" \
-h "host name" \
-V mqttv311 \
-p 8883 \
--cafile Baltimore.pem
-m '{"key":"value"}'

What Mosquitto_sub needs

mosquitto_sub \
-t "MQTT topic name" \
-i "pub_client" \
-u "username" \
-P "password" \
-h "host name" \
-V mqttv311 \
-p 8883 \
--cafile Baltimore.pem

To publish a MQTT message to Azure, you can not just any topic name. It must be in the following format 


In my example Mosquitto is my DeviceID

Step 7: Example Publishing and Subscribing
We now have all of the data and understand the required paramters to pass to both Mosquitto_pub and Mosquitto_sub. Now lets leverage these command line tools to build our completed commands and publish a message.

Substitute the values in the examples above with your data. My topic in this example is ‘Output-FAN\Kids Bathroom’. I am using ‘-d’ for verbose logging. You can use any topic name you like.


mosquitto_pub -t "devices/Mosquitto/messages/events/" -i "Mosquitto" -u "" -P "SharedAccessSignature" -h "" -V mqttv311 -p 8883 --cafile Balitore.pem -m '{"key":"value"}' -d

Client Mosquitto sending CONNECT
Client Mosquitto received CONNACK (0)
Client Mosquitto sending PUBLISH (d0, q0, r0, m1, 'devices/Mosquitto/messages/events/', ... (12 bytes))
Client Mosquitto sending DISCONNECT


mosquitto_sub -t "devices/Mosquitto/messages/events/" -i "Mosquitto" -u "" -P "SharedAccessSignature" -h "" -V mqttv311 -p 8883 --cafile c:\scripts\cert.pem -d

Client Mosquitto sending CONNECT
Client Mosquitto received CONNACK (0)
Client Mosquitto sending SUBSCRIBE (Mid: 1, Topic: devices/Mosquitto/messages/events/, QoS: 0, Options: 0x00)
Client Mosquitto received SUBACK
Subscribed (mid: 1): 0

We can validate the message has been received via Azure IoT Hub by monitoring incoming events on the end-point

az iot hub monitor-events --hub-name Baldacchino-IOTHub
Starting event monitor, use ctrl-c to stop...
"event": {
"origin": "Mosquitto",
"module": "",
"interface": "",
"component": "",
"payload": "'{key:value}'"

We just walked through how you can use Mosquitto Client Tools (mosquitto_pub / mosquitto_sub) to publish and subscribe MQTT messages to Azure IoT Hub and you did it not via the Azure Portal but via Azure CLI 💪💪.

Whilst this is a baby step, it is the step we need to take before we can look at broker (the Mosquitto daemon) to broker (Azure IOT Hub) replication.

MQTT is the de-facto IOT protocol for devices, from Alexa, through to lights and locks and devices on the factory floor. It is as close to an IOT protocol standard that we have today. Azure IOT on the other hand is your gateway in to the world of cloud. The Azure cloud platform contains more than 200 (and growing) products and cloud services designed to help you bring new solutions to life, solve today’s challenges and create the future.

What this means to my house at this stage I am uncertain but I know, I will be looking next to work on broker to broker communication before feeding the thousands of events that occur in my house daily in to Azure IoT-Hub.

Think-big and happy automating.
Shane Baldacchino

I work for @Microsoft but opinions expressed are my own

Leave a Comment