Skip to content

Instantly share code, notes, and snippets.

@suzukiken
Created October 31, 2015 08:15
Show Gist options
  • Save suzukiken/83ecc611e9ccafad56e6 to your computer and use it in GitHub Desktop.
Save suzukiken/83ecc611e9ccafad56e6 to your computer and use it in GitHub Desktop.
Amazon Lambda reads S3 bucket information and update IoT Thing's status
import os
import sys
import json
root = os.environ["LAMBDA_TASK_ROOT"]
sys.path.insert(0, root)
import boto3
s3 = boto3.client('s3')
iot = boto3.client('iot-data', region_name='us-east-1')
def lambda_handler (event, context):
try:
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
obj = s3.get_object(Bucket=bucket, Key=key)
objlist = s3.list_objects(Bucket=bucket)
payload = {
"state": {
"desired": {
"Count": len(objlist['Contents']),
"Time": obj['LastModified'].strftime('%Y-%m-%D %H:%M:%S')
}
}
}
iot.publish(
topic='$aws/things/s3thing/shadow/update',
qos=0,
payload=json.dumps(payload)
)
except Exception as e:
print(e)
raise e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment