Can we Integrate AWS lambda with AWS IOT and perform operations in the IOT using this lambda function?

122 views Asked by At

The scenario is like this

I have a microservice which invokes a LAMBDA function whose role will be to delete things from the AWS IOT.

Is there a way I can perform operations in AWS IOT using the lambda function?

Any article, blog regarding this will be a huge help as I'm not able to find any integration document on the web.

1

There are 1 answers

0
Shikhar Chaudhary On BEST ANSWER

I found a way to do several operations in AWS IOT using lambda function by the means of API's.

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iot.html#IoT.Client.delete_thing_group

The above link has description about API's which will help in this case. A sample lambda function script to delete a thing from the IOT is

import json
import boto3


def lambda_handler(event, context):
    thing_name = event['thing_name']
    delete_thing(thing_name=thing_name)

def delete_thing(thing_name):
    c_iot = boto3.client('iot')
    print("  DELETING {}".format(thing_name))
    try:
        r_principals = c_iot.list_thing_principals(thingName=thing_name)
    except Exception as e:
        print("ERROR listing thing principals: {}".format(e))
        r_principals = {'principals': []}
    print("r_principals: {}".format(r_principals))
    
    for arn in r_principals['principals']:
        cert_id = arn.split('/')[1]
        print("  arn: {} cert_id: {}".format(arn, cert_id))
        r_detach_thing = c_iot.detach_thing_principal(thingName=thing_name, principal=arn)
        print("DETACH THING: {}".format(r_detach_thing))
        
        r_upd_cert = c_iot.update_certificate(certificateId=cert_id, newStatus='INACTIVE')
        print("INACTIVE: {}".format(r_upd_cert))
        
        
        r_del_cert = c_iot.delete_certificate(certificateId=cert_id, forceDelete=True)
        print("  DEL CERT: {}".format(r_del_cert))
    r_del_thing = c_iot.delete_thing(thingName=thing_name)
    print("  DELETE THING: {}\n".format(r_del_thing))
    

And the input for this lambda function will be

{
  "thing_name": "MyIotThing"
}