Skip to main content
net6.0

Receipt rule actions for AWS IoT (Stability: Experimental)

Published
Oct 20, 2026
yesterday
Total Downloads
136.7K
136,699

Install

dotnet add package Amazon.CDK.AWS.IoT.Actions.Alpha --version 2.274.0-alpha.0
ProductVersions
.NET
net6.0

README

Actions for AWS IoT Rule


cdk-constructs: Experimental

The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


This library contains integration classes to send data to any number of supported AWS Services. Instances of these classes should be passed to TopicRule defined in aws-cdk-lib/aws-iot.

Currently supported are:

  • Republish a message to another MQTT topic
  • Invoke a Lambda function
  • Put objects to a S3 bucket
  • Put logs to CloudWatch Logs
  • Capture CloudWatch metrics
  • Change state for a CloudWatch alarm
  • Put records to Kinesis Data stream
  • Put records to Amazon Data Firehose stream
  • Send messages to SQS queues
  • Publish messages on SNS topics
  • Write messages into columns of DynamoDB
  • Put messages IoT Events input
  • Send messages to HTTPS endpoints

Republish a message to another MQTT topic

The code snippet below creates an AWS IoT Rule that republish a message to another MQTT topic when it is triggered.

new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'"),
    Actions = new [] {
        new IotRepublishMqttAction("${topic()}/republish", new IotRepublishMqttActionProps {
            QualityOfService = MqttQualityOfService.AT_LEAST_ONCE
        }) }
});

Invoke a Lambda function

The code snippet below creates an AWS IoT Rule that invoke a Lambda function when it is triggered.

var func = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromInline(@"
        exports.handler = (event) => {
          console.log(""It is test for lambda action of AWS IoT Rule."", event);
        };")
});

new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'"),
    Actions = new [] { new LambdaFunctionAction(func) }
});

Put objects to a S3 bucket

The code snippet below creates an AWS IoT Rule that puts objects to a S3 bucket when it is triggered.

var bucket = new Bucket(this, "MyBucket");

new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
    Actions = new [] { new S3PutObjectAction(bucket) }
});

The property key of S3PutObjectAction is given the value ${topic()}/${timestamp()} by default. This ${topic()} and ${timestamp()} is called Substitution templates. For more information see this documentation. In above sample, ${topic()} is replaced by a given MQTT topic as device/001/data. And ${timestamp()} is replaced by the number of the current timestamp in milliseconds as 1636289461203. So if the MQTT broker receives an MQTT topic device/001/data on 2021-11-07T00:00:00.000Z, the S3 bucket object will be put to device/001/data/1636243200000.

You can also set specific key as following:

var bucket = new Bucket(this, "MyBucket");

new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
    Actions = new [] {
        new S3PutObjectAction(bucket, new S3PutObjectActionProps {
            Key = "${year}/${month}/${day}/${topic(2)}"
        }) }
});

If you wanna set access control to the S3 bucket object, you can specify accessControl as following:

var bucket = new Bucket(this, "MyBucket");

new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT * FROM 'device/+/data'"),
    Actions = new [] {
        new S3PutObjectAction(bucket, new S3PutObjectActionProps {
            AccessControl = BucketAccessControl.PUBLIC_READ
        }) }
});

Put logs to CloudWatch Logs

The code snippet below creates an AWS IoT Rule that puts logs to CloudWatch Logs when it is triggered.

using Amazon.CDK.AWS.Logs;


var logGroup = new LogGroup(this, "MyLogGroup");

new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
    Actions = new [] { new CloudWatchLogsAction(logGroup) }
});

Capture CloudWatch metrics

The code snippet below creates an AWS IoT Rule that capture CloudWatch metrics when it is triggered.

var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id, namespace, unit, value, timestamp FROM 'device/+/data'"),
    Actions = new [] {
        new CloudWatchPutMetricAction(new CloudWatchPutMetricActionProps {
            MetricName = "${topic(2)}",
            MetricNamespace = "${namespace}",
            MetricUnit = "${unit}",
            MetricValue = "${value}",
            MetricTimestamp = "${timestamp}"
        }) }
});

Start Step Functions State Machine

The code snippet below creates an AWS IoT Rule that starts a Step Functions State Machine when it is triggered.

var stateMachine = new StateMachine(this, "SM", new StateMachineProps {
    DefinitionBody = DefinitionBody.FromChainable(new Wait(this, "Hello", new WaitProps { Time = WaitTime.Duration(Duration.Seconds(10)) }))
});

new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT * FROM 'device/+/data'"),
    Actions = new [] {
        new StepFunctionsStateMachineAction(stateMachine) }
});

Change the state of an Amazon CloudWatch alarm

The code snippet below creates an AWS IoT Rule that changes the state of an Amazon CloudWatch alarm when it is triggered:

using Amazon.CDK.AWS.CloudWatch;


var metric = new Metric(new MetricProps {
    Namespace = "MyNamespace",
    MetricName = "MyMetric",
    DimensionsMap = new Dictionary<string, string> { { "MyDimension", "MyDimensionValue" } }
});
var alarm = new Alarm(this, "MyAlarm", new AlarmProps {
    Metric = metric,
    Threshold = 100,
    EvaluationPeriods = 3,
    DatapointsToAlarm = 2
});

var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
    Actions = new [] {
        new CloudWatchSetAlarmStateAction(alarm, new CloudWatchSetAlarmStateActionProps {
            Reason = "AWS Iot Rule action is triggered",
            AlarmStateToSet = AlarmState.ALARM
        }) }
});

Put records to Kinesis Data stream

The code snippet below creates an AWS IoT Rule that puts records to Kinesis Data stream when it is triggered.

using Amazon.CDK.AWS.Kinesis;


var stream = new Stream(this, "MyStream");

var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT * FROM 'device/+/data'"),
    Actions = new [] {
        new KinesisPutRecordAction(stream, new KinesisPutRecordActionProps {
            PartitionKey = "${newuuid()}"
        }) }
});

Put records to Amazon Data Firehose stream

The code snippet below creates an AWS IoT Rule that puts records to Put records to Amazon Data Firehose stream when it is triggered.

using Amazon.CDK.AWS.KinesisFirehose;


var bucket = new Bucket(this, "MyBucket");
var stream = new DeliveryStream(this, "MyStream", new DeliveryStreamProps {
    Destination = new S3Bucket(bucket)
});

var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT * FROM 'device/+/data'"),
    Actions = new [] {
        new FirehosePutRecordAction(stream, new FirehosePutRecordActionProps {
            BatchMode = true,
            RecordSeparator = FirehoseRecordSeparator.NEWLINE
        }) }
});

Send messages to an SQS queue

The code snippet below creates an AWS IoT Rule that send messages to an SQS queue when it is triggered:

using Amazon.CDK.AWS.SQS;


var queue = new Queue(this, "MyQueue");

var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
    Actions = new [] {
        new SqsQueueAction(queue, new SqsQueueActionProps {
            UseBase64 = true
        }) }
});

Publish messages on an SNS topic

The code snippet below creates and AWS IoT Rule that publishes messages to an SNS topic when it is triggered:

using Amazon.CDK.AWS.SNS;


var topic = new Topic(this, "MyTopic");

var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
    Actions = new [] {
        new SnsTopicAction(topic, new SnsTopicActionProps {
            MessageFormat = SnsActionMessageFormat.JSON
        }) }
});

Write attributes of a message to DynamoDB

The code snippet below creates an AWS IoT rule that writes all or part of an MQTT message to DynamoDB using the DynamoDBv2 action.

using Amazon.CDK.AWS.DynamoDB;

Table table;


var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT * FROM 'device/+/data'"),
    Actions = new [] {
        new DynamoDBv2PutItemAction(table) }
});

Put messages IoT Events input

The code snippet below creates an AWS IoT Rule that puts messages to an IoT Events input when it is triggered:

using Amazon.CDK.AWS.IoTEvents.Alpha;
using Amazon.CDK.AWS.IAM;

IRole role;


var input = new Input(this, "MyInput", new InputProps {
    AttributeJsonPaths = new [] { "payload.temperature", "payload.transactionId" }
});
var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT * FROM 'device/+/data'"),
    Actions = new [] {
        new IotEventsPutMessageAction(input, new IotEventsPutMessageActionProps {
            BatchMode = true,  // optional property, default is 'false'
            MessageId = "${payload.transactionId}",  // optional property, default is a new UUID
            Role = role
        }) }
});

Send Messages to HTTPS Endpoints

The code snippet below creates an AWS IoT Rule that sends messages to an HTTPS endpoint when it is triggered:

var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")
});

topicRule.AddAction(
new HttpsAction("https://example.com/endpoint", new HttpsActionProps {
    ConfirmationUrl = "https://example.com",
    Headers = new [] { new HttpActionHeader { Key = "key0", Value = "value0" }, new HttpActionHeader { Key = "key1", Value = "value1" } },
    Auth = new HttpActionSigV4Auth { ServiceName = "serviceName", SigningRegion = "us-east-1" }
}));

You can enable batching to reduce costs and improve efficiency:

using Amazon.CDK;

TopicRule topicRule;

topicRule.AddAction(
new HttpsAction("https://example.com/endpoint", new HttpsActionProps {
    BatchConfig = new HttpActionBatchConfig {
        MaxBatchOpenDuration = Duration.Millis(100),
        MaxBatchSize = 5,
        MaxBatchSizeBytes = Size.Kibibytes(1)
    }
}));

For more information about the batching configuration, see the AWS IoT Core documentation.

Write Data to Open Search Service

The code snippet below creates an AWS IoT Rule that writes data to an Open Search Service when it is triggered:

using Amazon.CDK.AWS.OpenSearchService;
Domain domain;


var topicRule = new TopicRule(this, "TopicRule", new TopicRuleProps {
    Sql = IotSql.FromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")
});

topicRule.AddAction(new OpenSearchAction(domain, new OpenSearchActionProps {
    Id = "my-id",
    Index = "my-index",
    Type = "my-type"
}));

Changes from Previous Version

No structural changes between v2.273.0-alpha.0 and v2.274.0-alpha.0.

Adoption Assessment

A verified publisher signal is available. Assess fit from the package's supported frameworks, license and dependency graph rather than popularity alone.

This version is marked prerelease. Validate its API and upgrade path before production use.Compatibility metadata lists 1 target framework; confirm the exact target used by your application.

Related Guides & Workflows

Learn how to evaluate, integrate, or audit this package in your .NET project.