Skip to content
v2.273.0

Actions for AWS IoT Rule ​

Version 2.273.0-alpha.0

Separate package

@aws-cdk/aws-iot-actions-alpha is not part of aws-cdk-lib — install it separately:

sh
npm install @aws-cdk/aws-iot-actions-alpha
pip install aws-cdk.aws-iot-actions-alpha

This module is experimental (alpha): its API may change in any release, without a major version bump.


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.

ts
new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'"),
  actions: [
    new actions.IotRepublishMqttAction('${topic()}/republish', {
      qualityOfService: actions.MqttQualityOfService.AT_LEAST_ONCE, // optional property, default is MqttQualityOfService.ZERO_OR_MORE_TIMES
    }),
  ],
});
python
iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'"),
    actions=[
        actions.IotRepublishMqttAction("${topic()}/republish",
            quality_of_service=actions.MqttQualityOfService.AT_LEAST_ONCE
        )
    ]
)
java
TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'"))
        .actions(List.of(
            IotRepublishMqttAction.Builder.create("${topic()}/republish")
                    .qualityOfService(MqttQualityOfService.AT_LEAST_ONCE)
                    .build()))
        .build();
csharp
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
        }) }
});
go
iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewIotRepublishMqttAction(jsii.String("${topic()}/republish"), &IotRepublishMqttActionProps{
			QualityOfService: actions.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.

ts
const func = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromInline(`
    exports.handler = (event) => {
      console.log("It is test for lambda action of AWS IoT Rule.", event);
    };`
  ),
});

new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'"),
  actions: [new actions.LambdaFunctionAction(func)],
});
python
func = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_inline("""
            exports.handler = (event) => {
              console.log("It is test for lambda action of AWS IoT Rule.", event);
            };""")
)

iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'"),
    actions=[actions.LambdaFunctionAction(func)]
)
java
Function func = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromInline("\n    exports.handler = (event) => {\n      console.log(\"It is test for lambda action of AWS IoT Rule.\", event);\n    };"))
        .build();

TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'"))
        .actions(List.of(new LambdaFunctionAction(func)))
        .build();
csharp
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) }
});
go
func := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromInline(jsii.String(`
	    exports.handler = (event) => {
	      console.log("It is test for lambda action of AWS IoT Rule.", event);
	    };`)),
})

iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id, timestamp() as timestamp, temperature FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewLambdaFunctionAction(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.

ts
const bucket = new s3.Bucket(this, 'MyBucket');

new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
  actions: [new actions.S3PutObjectAction(bucket)],
});
python
bucket = s3.Bucket(self, "MyBucket")

iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
    actions=[actions.S3PutObjectAction(bucket)]
)
java
Bucket bucket = new Bucket(this, "MyBucket");

TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id FROM 'device/+/data'"))
        .actions(List.of(new S3PutObjectAction(bucket)))
        .build();
csharp
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) }
});
go
bucket := s3.NewBucket(this, jsii.String("MyBucket"))

iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewS3PutObjectAction(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:

ts
const bucket = new s3.Bucket(this, 'MyBucket');

new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323(
    "SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'",
  ),
  actions: [
    new actions.S3PutObjectAction(bucket, {
      key: '${year}/${month}/${day}/${topic(2)}',
    }),
  ],
});
python
bucket = s3.Bucket(self, "MyBucket")

iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
    actions=[
        actions.S3PutObjectAction(bucket,
            key="${year}/${month}/${day}/${topic(2)}"
        )
    ]
)
java
Bucket bucket = new Bucket(this, "MyBucket");

TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"))
        .actions(List.of(
            S3PutObjectAction.Builder.create(bucket)
                    .key("${year}/${month}/${day}/${topic(2)}")
                    .build()))
        .build();
csharp
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)}"
        }) }
});
go
bucket := s3.NewBucket(this, jsii.String("MyBucket"))

iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewS3PutObjectAction(bucket, &S3PutObjectActionProps{
			Key: jsii.String("${year}/${month}/${day}/${topic(2)}"),
		}),
	},
})

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

ts
const bucket = new s3.Bucket(this, 'MyBucket');

new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323("SELECT * FROM 'device/+/data'"),
  actions: [
    new actions.S3PutObjectAction(bucket, {
      accessControl: s3.BucketAccessControl.PUBLIC_READ,
    }),
  ],
});
python
bucket = s3.Bucket(self, "MyBucket")

iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
    actions=[
        actions.S3PutObjectAction(bucket,
            access_control=s3.BucketAccessControl.PUBLIC_READ
        )
    ]
)
java
Bucket bucket = new Bucket(this, "MyBucket");

TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT * FROM 'device/+/data'"))
        .actions(List.of(
            S3PutObjectAction.Builder.create(bucket)
                    .accessControl(BucketAccessControl.PUBLIC_READ)
                    .build()))
        .build();
csharp
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
        }) }
});
go
bucket := s3.NewBucket(this, jsii.String("MyBucket"))

iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT * FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewS3PutObjectAction(bucket, &S3PutObjectActionProps{
			AccessControl: s3.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.

ts
import * as logs from 'aws-cdk-lib/aws-logs';

const logGroup = new logs.LogGroup(this, 'MyLogGroup');

new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
  actions: [new actions.CloudWatchLogsAction(logGroup)],
});
python
import aws_cdk.aws_logs as logs


log_group = logs.LogGroup(self, "MyLogGroup")

iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
    actions=[actions.CloudWatchLogsAction(log_group)]
)
java
import software.amazon.awscdk.services.logs.*;


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

TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id FROM 'device/+/data'"))
        .actions(List.of(new CloudWatchLogsAction(logGroup)))
        .build();
csharp
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) }
});
go
import logs "github.com/aws/aws-cdk-go/awscdk"


logGroup := logs.NewLogGroup(this, jsii.String("MyLogGroup"))

iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewCloudWatchLogsAction(logGroup),
	},
})

Capture CloudWatch metrics ​

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

ts
const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323(
    "SELECT topic(2) as device_id, namespace, unit, value, timestamp FROM 'device/+/data'",
  ),
  actions: [
    new actions.CloudWatchPutMetricAction({
      metricName: '${topic(2)}',
      metricNamespace: '${namespace}',
      metricUnit: '${unit}',
      metricValue: '${value}',
      metricTimestamp: '${timestamp}',
    }),
  ],
});
python
topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, namespace, unit, value, timestamp FROM 'device/+/data'"),
    actions=[
        actions.CloudWatchPutMetricAction(
            metric_name="${topic(2)}",
            metric_namespace="${namespace}",
            metric_unit="${unit}",
            metric_value="${value}",
            metric_timestamp="${timestamp}"
        )
    ]
)
java
TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, namespace, unit, value, timestamp FROM 'device/+/data'"))
        .actions(List.of(
            CloudWatchPutMetricAction.Builder.create()
                    .metricName("${topic(2)}")
                    .metricNamespace("${namespace}")
                    .metricUnit("${unit}")
                    .metricValue("${value}")
                    .metricTimestamp("${timestamp}")
                    .build()))
        .build();
csharp
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}"
        }) }
});
go
topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id, namespace, unit, value, timestamp FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewCloudWatchPutMetricAction(&CloudWatchPutMetricActionProps{
			MetricName: jsii.String("${topic(2)}"),
			MetricNamespace: jsii.String("${namespace}"),
			MetricUnit: jsii.String("${unit}"),
			MetricValue: jsii.String("${value}"),
			MetricTimestamp: jsii.String("${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.

ts
const stateMachine = new stepfunctions.StateMachine(this, 'SM', {
  definitionBody: stepfunctions.DefinitionBody.fromChainable(new stepfunctions.Wait(this, 'Hello', { time: stepfunctions.WaitTime.duration(Duration.seconds(10)) })),
});

new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323("SELECT * FROM 'device/+/data'"),
  actions: [
    new actions.StepFunctionsStateMachineAction(stateMachine),
  ],
});
python
state_machine = stepfunctions.StateMachine(self, "SM",
    definition_body=stepfunctions.DefinitionBody.from_chainable(stepfunctions.Wait(self, "Hello", time=stepfunctions.WaitTime.duration(Duration.seconds(10))))
)

iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
    actions=[
        actions.StepFunctionsStateMachineAction(state_machine)
    ]
)
java
StateMachine stateMachine = StateMachine.Builder.create(this, "SM")
        .definitionBody(DefinitionBody.fromChainable(Wait.Builder.create(this, "Hello").time(WaitTime.duration(Duration.seconds(10))).build()))
        .build();

TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT * FROM 'device/+/data'"))
        .actions(List.of(
            new StepFunctionsStateMachineAction(stateMachine)))
        .build();
csharp
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) }
});
go
stateMachine := stepfunctions.NewStateMachine(this, jsii.String("SM"), &StateMachineProps{
	DefinitionBody: stepfunctions.DefinitionBody_FromChainable(stepfunctions.NewWait(this, jsii.String("Hello"), &WaitProps{
		Time: stepfunctions.WaitTime_Duration(awscdk.Duration_Seconds(jsii.Number(10))),
	})),
})

iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT * FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewStepFunctionsStateMachineAction(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:

ts
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';

const metric = new cloudwatch.Metric({
  namespace: 'MyNamespace',
  metricName: 'MyMetric',
  dimensionsMap: { MyDimension: 'MyDimensionValue' },
});
const alarm = new cloudwatch.Alarm(this, 'MyAlarm', {
  metric: metric,
  threshold: 100,
  evaluationPeriods: 3,
  datapointsToAlarm: 2,
});

const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
  actions: [
    new actions.CloudWatchSetAlarmStateAction(alarm, {
      reason: 'AWS Iot Rule action is triggered',
      alarmStateToSet: cloudwatch.AlarmState.ALARM,
    }),
  ],
});
python
import aws_cdk.aws_cloudwatch as cloudwatch


metric = cloudwatch.Metric(
    namespace="MyNamespace",
    metric_name="MyMetric",
    dimensions_map={"MyDimension": "MyDimensionValue"}
)
alarm = cloudwatch.Alarm(self, "MyAlarm",
    metric=metric,
    threshold=100,
    evaluation_periods=3,
    datapoints_to_alarm=2
)

topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id FROM 'device/+/data'"),
    actions=[
        actions.CloudWatchSetAlarmStateAction(alarm,
            reason="AWS Iot Rule action is triggered",
            alarm_state_to_set=cloudwatch.AlarmState.ALARM
        )
    ]
)
java
import software.amazon.awscdk.services.cloudwatch.*;


Metric metric = Metric.Builder.create()
        .namespace("MyNamespace")
        .metricName("MyMetric")
        .dimensionsMap(Map.of("MyDimension", "MyDimensionValue"))
        .build();
Alarm alarm = Alarm.Builder.create(this, "MyAlarm")
        .metric(metric)
        .threshold(100)
        .evaluationPeriods(3)
        .datapointsToAlarm(2)
        .build();

TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id FROM 'device/+/data'"))
        .actions(List.of(
            CloudWatchSetAlarmStateAction.Builder.create(alarm)
                    .reason("AWS Iot Rule action is triggered")
                    .alarmStateToSet(AlarmState.ALARM)
                    .build()))
        .build();
csharp
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
        }) }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


metric := cloudwatch.NewMetric(&MetricProps{
	Namespace: jsii.String("MyNamespace"),
	MetricName: jsii.String("MyMetric"),
	DimensionsMap: map[string]*string{
		"MyDimension": jsii.String("MyDimensionValue"),
	},
})
alarm := cloudwatch.NewAlarm(this, jsii.String("MyAlarm"), &AlarmProps{
	Metric: metric,
	Threshold: jsii.Number(100),
	EvaluationPeriods: jsii.Number(3),
	DatapointsToAlarm: jsii.Number(2),
})

topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewCloudWatchSetAlarmStateAction(alarm, &CloudWatchSetAlarmStateActionProps{
			Reason: jsii.String("AWS Iot Rule action is triggered"),
			AlarmStateToSet: cloudwatch.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.

ts
import * as kinesis from 'aws-cdk-lib/aws-kinesis';

const stream = new kinesis.Stream(this, 'MyStream');

const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323("SELECT * FROM 'device/+/data'"),
  actions: [
    new actions.KinesisPutRecordAction(stream, {
      partitionKey: '${newuuid()}',
    }),
  ],
});
python
import aws_cdk.aws_kinesis as kinesis


stream = kinesis.Stream(self, "MyStream")

topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
    actions=[
        actions.KinesisPutRecordAction(stream,
            partition_key="${newuuid()}"
        )
    ]
)
java
import software.amazon.awscdk.services.kinesis.*;


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

TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT * FROM 'device/+/data'"))
        .actions(List.of(
            KinesisPutRecordAction.Builder.create(stream)
                    .partitionKey("${newuuid()}")
                    .build()))
        .build();
csharp
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()}"
        }) }
});
go
import kinesis "github.com/aws/aws-cdk-go/awscdk"


stream := kinesis.NewStream(this, jsii.String("MyStream"))

topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT * FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewKinesisPutRecordAction(stream, &KinesisPutRecordActionProps{
			PartitionKey: jsii.String("${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.

ts
import * as firehose from 'aws-cdk-lib/aws-kinesisfirehose';

const bucket = new s3.Bucket(this, 'MyBucket');
const stream = new firehose.DeliveryStream(this, 'MyStream', {
  destination: new firehose.S3Bucket(bucket),
});

const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323("SELECT * FROM 'device/+/data'"),
  actions: [
    new actions.FirehosePutRecordAction(stream, {
      batchMode: true,
      recordSeparator: actions.FirehoseRecordSeparator.NEWLINE,
    }),
  ],
});
python
import aws_cdk.aws_kinesisfirehose as firehose


bucket = s3.Bucket(self, "MyBucket")
stream = firehose.DeliveryStream(self, "MyStream",
    destination=firehose.S3Bucket(bucket)
)

topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
    actions=[
        actions.FirehosePutRecordAction(stream,
            batch_mode=True,
            record_separator=actions.FirehoseRecordSeparator.NEWLINE
        )
    ]
)
java
import software.amazon.awscdk.services.kinesisfirehose.*;


Bucket bucket = new Bucket(this, "MyBucket");
DeliveryStream stream = DeliveryStream.Builder.create(this, "MyStream")
        .destination(new S3Bucket(bucket))
        .build();

TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT * FROM 'device/+/data'"))
        .actions(List.of(
            FirehosePutRecordAction.Builder.create(stream)
                    .batchMode(true)
                    .recordSeparator(FirehoseRecordSeparator.NEWLINE)
                    .build()))
        .build();
csharp
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
        }) }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


bucket := s3.NewBucket(this, jsii.String("MyBucket"))
stream := firehose.NewDeliveryStream(this, jsii.String("MyStream"), &DeliveryStreamProps{
	Destination: firehose.NewS3Bucket(bucket),
})

topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT * FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewFirehosePutRecordAction(stream, &FirehosePutRecordActionProps{
			BatchMode: jsii.Boolean(true),
			RecordSeparator: actions.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:

ts
import * as sqs from 'aws-cdk-lib/aws-sqs';

const queue = new sqs.Queue(this, 'MyQueue');

const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323(
    "SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'",
  ),
  actions: [
    new actions.SqsQueueAction(queue, {
      useBase64: true, // optional property, default is 'false'
    }),
  ],
});
python
import aws_cdk.aws_sqs as sqs


queue = sqs.Queue(self, "MyQueue")

topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
    actions=[
        actions.SqsQueueAction(queue,
            use_base64=True
        )
    ]
)
java
import software.amazon.awscdk.services.sqs.*;


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

TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"))
        .actions(List.of(
            SqsQueueAction.Builder.create(queue)
                    .useBase64(true)
                    .build()))
        .build();
csharp
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
        }) }
});
go
import sqs "github.com/aws/aws-cdk-go/awscdk"


queue := sqs.NewQueue(this, jsii.String("MyQueue"))

topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewSqsQueueAction(queue, &SqsQueueActionProps{
			UseBase64: jsii.Boolean(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:

ts
import * as sns from 'aws-cdk-lib/aws-sns';

const topic = new sns.Topic(this, 'MyTopic');

const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323(
    "SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'",
  ),
  actions: [
    new actions.SnsTopicAction(topic, {
      messageFormat: actions.SnsActionMessageFormat.JSON, // optional property, default is SnsActionMessageFormat.RAW
    }),
  ],
});
python
import aws_cdk.aws_sns as sns


topic = sns.Topic(self, "MyTopic")

topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"),
    actions=[
        actions.SnsTopicAction(topic,
            message_format=actions.SnsActionMessageFormat.JSON
        )
    ]
)
java
import software.amazon.awscdk.services.sns.*;


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

TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"))
        .actions(List.of(
            SnsTopicAction.Builder.create(topic)
                    .messageFormat(SnsActionMessageFormat.JSON)
                    .build()))
        .build();
csharp
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
        }) }
});
go
import sns "github.com/aws/aws-cdk-go/awscdk"


topic := sns.NewTopic(this, jsii.String("MyTopic"))

topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewSnsTopicAction(topic, &SnsTopicActionProps{
			MessageFormat: actions.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.

ts
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';

declare const table: dynamodb.Table;

const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323(
    "SELECT * FROM 'device/+/data'",
  ),
  actions: [
    new actions.DynamoDBv2PutItemAction(table)
  ],
});
python
import aws_cdk.aws_dynamodb as dynamodb

# table: dynamodb.Table


topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
    actions=[
        actions.DynamoDBv2PutItemAction(table)
    ]
)
java
import software.amazon.awscdk.services.dynamodb.*;

Table table;


TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT * FROM 'device/+/data'"))
        .actions(List.of(
            new DynamoDBv2PutItemAction(table)))
        .build();
csharp
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) }
});
go
import dynamodb "github.com/aws/aws-cdk-go/awscdk"

var table Table


topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT * FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewDynamoDBv2PutItemAction(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:

ts
import * as iotevents from '@aws-cdk/aws-iotevents-alpha';
import * as iam from 'aws-cdk-lib/aws-iam';

declare const role: iam.IRole;

const input = new iotevents.Input(this, 'MyInput', {
  attributeJsonPaths: ['payload.temperature', 'payload.transactionId'],
});
const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323(
    "SELECT * FROM 'device/+/data'",
  ),
  actions: [
    new actions.IotEventsPutMessageAction(input, {
      batchMode: true, // optional property, default is 'false'
      messageId: '${payload.transactionId}', // optional property, default is a new UUID
      role: role, // optional property, default is a new UUID
    }),
  ],
});
python
import aws_cdk.aws_iotevents_alpha as iotevents
import aws_cdk.aws_iam as iam

# role: iam.IRole


input = iotevents.Input(self, "MyInput",
    attribute_json_paths=["payload.temperature", "payload.transactionId"]
)
topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT * FROM 'device/+/data'"),
    actions=[
        actions.IotEventsPutMessageAction(input,
            batch_mode=True,  # optional property, default is 'false'
            message_id="${payload.transactionId}",  # optional property, default is a new UUID
            role=role
        )
    ]
)
java
import software.amazon.awscdk.services.iotevents.alpha.*;
import software.amazon.awscdk.services.iam.*;

IRole role;


Input input = Input.Builder.create(this, "MyInput")
        .attributeJsonPaths(List.of("payload.temperature", "payload.transactionId"))
        .build();
TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT * FROM 'device/+/data'"))
        .actions(List.of(
            IotEventsPutMessageAction.Builder.create(input)
                    .batchMode(true) // optional property, default is 'false'
                    .messageId("${payload.transactionId}") // optional property, default is a new UUID
                    .role(role)
                    .build()))
        .build();
csharp
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
        }) }
});
go
import iotevents "github.com/aws/aws-cdk-go/awscdkioteventsalpha"
import iam "github.com/aws/aws-cdk-go/awscdk"

var role IRole


input := iotevents.NewInput(this, jsii.String("MyInput"), &InputProps{
	AttributeJsonPaths: []*string{
		jsii.String("payload.temperature"),
		jsii.String("payload.transactionId"),
	},
})
topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT * FROM 'device/+/data'")),
	Actions: []IAction{
		actions.NewIotEventsPutMessageAction(input, &IotEventsPutMessageActionProps{
			BatchMode: jsii.Boolean(true),
			 // optional property, default is 'false'
			MessageId: jsii.String("${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:

ts
const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323(
    "SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'",
  ),
});

topicRule.addAction(
  new actions.HttpsAction('https://example.com/endpoint', {
    confirmationUrl: 'https://example.com',
    headers: [
      { key: 'key0', value: 'value0' },
      { key: 'key1', value: 'value1' },
    ],
    auth: { serviceName: 'serviceName', signingRegion: 'us-east-1' },
  }),
);
python
topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")
)

topic_rule.add_action(
    actions.HttpsAction("https://example.com/endpoint",
        confirmation_url="https://example.com",
        headers=[actions.HttpActionHeader(key="key0", value="value0"), actions.HttpActionHeader(key="key1", value="value1")
        ],
        auth=actions.HttpActionSigV4Auth(service_name="serviceName", signing_region="us-east-1")
    ))
java
TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"))
        .build();

topicRule.addAction(
HttpsAction.Builder.create("https://example.com/endpoint")
        .confirmationUrl("https://example.com")
        .headers(List.of(HttpActionHeader.builder().key("key0").value("value0").build(), HttpActionHeader.builder().key("key1").value("value1").build()))
        .auth(HttpActionSigV4Auth.builder().serviceName("serviceName").signingRegion("us-east-1").build())
        .build());
csharp
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" }
}));
go
topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")),
})

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

You can enable batching to reduce costs and improve efficiency:

ts
import { Size } from 'aws-cdk-lib';

declare const topicRule: iot.TopicRule;

topicRule.addAction(
  new actions.HttpsAction('https://example.com/endpoint', {
    batchConfig: {
      maxBatchOpenDuration: Duration.millis(100),
      maxBatchSize: 5,
      maxBatchSizeBytes: Size.kibibytes(1),
    },
  }),
);
python
from aws_cdk import Size

# topic_rule: iot.TopicRule


topic_rule.add_action(
    actions.HttpsAction("https://example.com/endpoint",
        batch_config=actions.HttpActionBatchConfig(
            max_batch_open_duration=Duration.millis(100),
            max_batch_size=5,
            max_batch_size_bytes=Size.kibibytes(1)
        )
    ))
java
import software.amazon.awscdk.Size;

TopicRule topicRule;


topicRule.addAction(
HttpsAction.Builder.create("https://example.com/endpoint")
        .batchConfig(HttpActionBatchConfig.builder()
                .maxBatchOpenDuration(Duration.millis(100))
                .maxBatchSize(5)
                .maxBatchSizeBytes(Size.kibibytes(1))
                .build())
        .build());
csharp
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)
    }
}));
go
import "github.com/aws/aws-cdk-go/awscdk"

var topicRule TopicRule


topicRule.AddAction(
actions.NewHttpsAction(jsii.String("https://example.com/endpoint"), &HttpsActionProps{
	BatchConfig: &HttpActionBatchConfig{
		MaxBatchOpenDuration: awscdk.Duration_Millis(jsii.Number(100)),
		MaxBatchSize: jsii.Number(5),
		MaxBatchSizeBytes: awscdk.Size_Kibibytes(jsii.Number(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:

ts
import * as opensearch from 'aws-cdk-lib/aws-opensearchservice';
declare const domain: opensearch.Domain;

const topicRule = new iot.TopicRule(this, 'TopicRule', {
  sql: iot.IotSql.fromStringAsVer20160323(
    "SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'",
  ),
});

topicRule.addAction(new actions.OpenSearchAction(domain, {
  id: 'my-id',
  index: 'my-index',
  type: 'my-type',
}));
python
import aws_cdk.aws_opensearchservice as opensearch
# domain: opensearch.Domain


topic_rule = iot.TopicRule(self, "TopicRule",
    sql=iot.IotSql.from_string_as_ver20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")
)

topic_rule.add_action(actions.OpenSearchAction(domain,
    id="my-id",
    index="my-index",
    type="my-type"
))
java
import software.amazon.awscdk.services.opensearchservice.*;
Domain domain;


TopicRule topicRule = TopicRule.Builder.create(this, "TopicRule")
        .sql(IotSql.fromStringAsVer20160323("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'"))
        .build();

topicRule.addAction(OpenSearchAction.Builder.create(domain)
        .id("my-id")
        .index("my-index")
        .type("my-type")
        .build());
csharp
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"
}));
go
import opensearch "github.com/aws/aws-cdk-go/awscdk"
var domain Domain


topicRule := iot.NewTopicRule(this, jsii.String("TopicRule"), &TopicRuleProps{
	Sql: iot.IotSql_FromStringAsVer20160323(jsii.String("SELECT topic(2) as device_id, year, month, day FROM 'device/+/data'")),
})

topicRule.AddAction(actions.NewOpenSearchAction(domain, &OpenSearchActionProps{
	Id: jsii.String("my-id"),
	Index: jsii.String("my-index"),
	Type: jsii.String("my-type"),
}))

Types ​

NameKindSummary
CloudWatchLogsActionClassThe action to send data to Amazon CloudWatch Logs.
CloudWatchLogsActionPropsStructConfiguration properties of an action for CloudWatch Logs.
CloudWatchPutMetricActionClassThe action to capture an Amazon CloudWatch metric.
CloudWatchPutMetricActionPropsStructConfiguration properties of an action for CloudWatch metric.
CloudWatchSetAlarmStateActionClassThe action to change the state of an Amazon CloudWatch alarm.
CloudWatchSetAlarmStateActionPropsStructConfiguration properties of an action for CloudWatch alarm.
CommonActionPropsStructCommon properties shared by Actions it access to AWS service.
DynamoDBv2PutItemActionClassThe action to put the record from an MQTT message to the DynamoDB table.
DynamoDBv2PutItemActionPropsStructConfiguration properties of an action for the dynamodb table.
FirehosePutRecordActionClassThe action to put the record from an MQTT message to the Amazon Data Firehose stream.
FirehosePutRecordActionPropsStructConfiguration properties of an action for the Amazon Data Firehose stream.
FirehoseRecordSeparatorEnumRecord Separator to be used to separate records.
HttpActionBatchConfigStructConfiguration for batching HTTP action messages.
HttpActionHeaderStruct
HttpActionSigV4AuthStruct
HttpsActionClassThe action to send data from an MQTT message to a web application or service.
HttpsActionPropsStructConfiguration properties of an HTTPS action.
IotEventsPutMessageActionClassThe action to put the message from an MQTT message to the IoT Events input.
IotEventsPutMessageActionPropsStructConfiguration properties of an action for the IoT Events.
IotRepublishMqttActionClassThe action to put the record from an MQTT message to republish another MQTT topic.
IotRepublishMqttActionPropsStructConfiguration properties of an action to republish MQTT messages.
KinesisPutRecordActionClassThe action to put the record from an MQTT message to the Kinesis Data stream.
KinesisPutRecordActionPropsStructConfiguration properties of an action for the Kinesis Data stream.
LambdaFunctionActionClassThe action to invoke an AWS Lambda function, passing in an MQTT message.
MqttQualityOfServiceEnumMQTT Quality of Service (QoS) indicates the level of assurance for delivery of an MQTT Message.
OpenSearchActionClassThe action to write data to an Amazon OpenSearch Service domain.
OpenSearchActionPropsStructConfiguration properties of an action for Open Search.
S3PutObjectActionClassThe action to write the data from an MQTT message to an Amazon S3 bucket.
S3PutObjectActionPropsStructConfiguration properties of an action for s3.
SnsActionMessageFormatEnumSNS topic action message format options.
SnsTopicActionClassThe action to write the data from an MQTT message to an Amazon SNS topic.
SnsTopicActionPropsStructConfiguration options for the SNS topic action.
SqsQueueActionClassThe action to write the data from an MQTT message to an Amazon SQS queue.
SqsQueueActionPropsStructConfiguration properties of an action for SQS.
StepFunctionsStateMachineActionClassThe action to put the record from an MQTT message to the Step Functions State Machine.
StepFunctionsStateMachineActionPropsStructConfiguration properties of an action for the Step Functions State Machine.