MQTT Client cross-account to connect and publish to AWS IoT MQTT Broker

0

I need to use MQTT Client (ca, crt, key) from Lambda in Account A to connect to the AWS IoT core MQTT broker in Account B through mqtt publish. Here's what I've tried so far but it hasn't worked. Lambda is configured with NodeJS Node.js 20.x. Am I missing something?

const mqtt = require('mqtt');
export const handler = async (event) => {
        const mqttEndpoint = 'xxxxxxxx-ats.iot.us-east-1.amazonaws.com';
        const clientId = 'ThirdParty_xxxxxx_Cloud';
        const topic = 'xxxx/xxxx/xxxx/xxxx/xxxx';

        // Load SSL certificates and private key
        const fs = require('fs');
        const ca = fs.readFileSync('./AmazonRootCA1.pem');
        const cert = fs.readFileSync('./certificate.pem.crt');
        const key = fs.readFileSync('./private.pem.key');

        // Connect to MQTT broker
        const mqttClient = mqtt.connect(mqttEndpoint, {
            protocol: 'mqtts',
            port: 8883,
            clientId: clientId,
            ca: ca,
            cert: cert,
            key: key,
            rejectUnauthorized: true, // Set to false if your broker uses self-signed certificate
        });

        // Handle incoming messages
        mqttClient.on('message', (topic, message) => {
            console.log(`Received message on topic ${topic}: ${message.toString()}`);
            // Handle the message as needed
        });

        // Publish a message
        const message = 'Hello from Lambda!';
        mqttClient.publish(topic, message);

        // Disconnect after a certain period or when done
        setTimeout(() => {
            mqttClient.end();
        }, 5000);
};
Rowen
asked 3 months ago192 views
2 Answers
0

Hi. What's the error you get?

I'm not familiar with MQTT.js, but I think you need to specify the protocol in the endpoint string, as per the MQTT.js example here: https://aws.amazon.com/blogs/iot/use-aws-iot-core-mqtt-broker-with-standard-mqtt-libraries/

profile pictureAWS
EXPERT
Greg_B
answered 3 months ago
0

Hi,

You should follow the guidance of https://docs.aws.amazon.com/iot/latest/developerguide/accessing-cross-account-resources-using-rules.html

See section Cross-account setup for AWS Lambda in particular

Best,

Didier

profile pictureAWS
EXPERT
answered 3 months ago
  • This is to send MQTT messages across accounts through IoT core, but I hope to publish MQTT messages across accounts from Lambda in reverse. Is there any other way? Thank you

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions