AWS CDK AWS IoT Alpha Constructs

2.250.0a0 · active · verified Thu Apr 16

The `aws-cdk-aws-iot-alpha` library provides experimental, higher-level (L2/L3) constructs for defining AWS IoT Core resources using the AWS Cloud Development Kit (CDK). As an 'alpha' module, its APIs are under active development and subject to non-backward compatible changes or removal in any future version. It allows developers to programmatically define IoT rules, logging, scheduled audits, and more, leveraging familiar programming languages. The current version is `2.250.0a0`, released as part of the AWS CDK v2 alpha series, with breaking changes announced in release notes rather than adhering to strict semantic versioning.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart defines an AWS IoT Topic Rule that listens for messages on the MQTT topic `device/+/data` and invokes an AWS Lambda function with the message payload. It demonstrates the use of `TopicRule` and `LambdaFunctionAction` from the alpha modules, showcasing how to connect IoT device messages to other AWS services. Before running, ensure AWS credentials and CDK environment variables (`CDK_DEFAULT_ACCOUNT`, `CDK_DEFAULT_REGION`) are configured.

import os
from aws_cdk import (
    App,
    Stack,
    aws_lambda as lambda_,
    aws_cdk as cdk
)
import aws_cdk.aws_iot_alpha as iot
import aws_cdk.aws_iot_actions_alpha as actions


class IotRuleStack(Stack):
    def __init__(self, scope: App, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Define a Lambda function to be invoked by the IoT Rule
        my_function = lambda_.Function(
            self, "MyIoTFunction",
            runtime=lambda_.Runtime.PYTHON_3_9,
            handler="index.handler",
            code=lambda_.Code.from_inline(
                """import json\n\ndef handler(event, context):\n    print("Received event: {}".format(json.dumps(event)))\n    return {'statusCode': 200, 'body': 'OK'}"""
            )
        )

        # Create an IoT Topic Rule that invokes the Lambda function
        # The SQL statement filters messages on 'device/+/data'
        iot.TopicRule(
            self, "MyTopicRule",
            topic_rule_name="MyCdkExampleTopicRule",
            description="Invokes a Lambda function when a message is published to 'device/+/data'",
            sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, timestamp() as timestamp FROM 'device/+/data'"),
            actions=[actions.LambdaFunctionAction(my_function)]
        )


app = App()
IotRuleStack(app, "IotRuleStack",
             # For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html
             env=cdk.Environment(
                 account=os.environ.get("CDK_DEFAULT_ACCOUNT"),
                 region=os.environ.get("CDK_DEFAULT_REGION")
             )
)

app.synth()

view raw JSON →