AWS lambda capture IoT registry event

2019-07-10 07:36发布

问题:

I'm plan to generate new thing in AWS IoT Registry and once the thing is generated successfully, write the thing arn, thing name, cert information into AWS RDS database.

Is this possible to use lambda capture IoT registry event and trigger lambda to write into database?

Any suggestion?

回答1:

AWS IoT publishes a lot of its events through it's own MQTT broker.

In your case you're interested in the $aws/events/thing/<thingName>/created topic (https://docs.aws.amazon.com/iot/latest/developerguide/registry-events.html).

When messages are sent through certain topics you can use the AWS IoT Rule engine to automatically perform actions (https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html).

These actions could be a lambda (if you have more logic outside what you've shared in the question), but there's a dynamodb rule, too, which can be used to solve this problem without writing your own custom code:

  • DynamoDb rules: https://docs.aws.amazon.com/iot/latest/developerguide/iot-rule-actions.html#dynamodb-v2-rule
  • Lambda rules: https://docs.aws.amazon.com/iot/latest/developerguide/iot-rule-actions.html#lambda-rule

So in your case, you might do something like this:

{
  "sql": "SELECT thingId thingName timestamp FROM '$aws/events/thing/+/created'",
  "ruleDisabled": false,
  "awsIotSqlVersion": "2016-03-23",
  "actions": [{
    "dynamoDBv2": {
       "roleArn": "arn:aws:iam::123456789012:role/aws_iot_dynamoDBv2", 
       "putItem": {
         "tableName": "my_ddb_table"
        }
     }
  }]
}

Unfortunately it seems like AWS does not publish the certificate information to a topic on registration. My guess is this is because there isn't a 1-to-1 relationship between certificate and device.

You can get this information by listening to the $aws/events/presence/connected/clientId topic; enforcing that the clientId === thingId (which is typically the case), and recording the principalIdentifier from the message (https://docs.aws.amazon.com/iot/latest/developerguide/life-cycle-events.html#connect-disconnect). You can once again automate this using AWS IoT rules.