# Actions for AWS IoT Rule

> Version 2.278.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**](https://docs.aws.amazon.com/cdk/api/stability.html) (alpha): its API may change in any release, without a major version bump.
---

![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge)

> 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](https://semver.org/) 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.

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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
        }) }
});
```

Golang:

```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.

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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) }
});
```

Golang:

```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.

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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) }
});
```

Golang:

```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`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.S3PutObjectAction.html) is given the value `${topic()}/${timestamp()}` by default. This `${topic()}`
and `${timestamp()}` is called Substitution templates. For more information see
[this documentation](https://docs.aws.amazon.com/iot/latest/developerguide/iot-substitution-templates.html).
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:

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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)}"
        }) }
});
```

Golang:

```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:

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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
        }) }
});
```

Golang:

```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.

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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) }
});
```

Golang:

```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.

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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}"
        }) }
});
```

Golang:

```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.

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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) }
});
```

Golang:

```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:

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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
        }) }
});
```

Golang:

```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.

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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()}"
        }) }
});
```

Golang:

```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.

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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
        }) }
});
```

Golang:

```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:

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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
        }) }
});
```

Golang:

```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:

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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
        }) }
});
```

Golang:

```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.

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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) }
});
```

Golang:

```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:

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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
        }) }
});
```

Golang:

```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:

TypeScript:

```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:

```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:

```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());
```

C# / .NET:

```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" }
}));
```

Golang:

```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:

TypeScript:

```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:

```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:

```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());
```

C# / .NET:

```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)
    }
}));
```

Golang:

```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](https://docs.aws.amazon.com/iot/latest/developerguide/http_batching.html).

## 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:

TypeScript:

```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:

```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:

```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());
```

C# / .NET:

```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"
}));
```

Golang:

```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

### Classes

- [`CloudWatchLogsAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.CloudWatchLogsAction.html) Class The action to send data to Amazon CloudWatch Logs.
- [`CloudWatchPutMetricAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.CloudWatchPutMetricAction.html) Class The action to capture an Amazon CloudWatch metric.
- [`CloudWatchSetAlarmStateAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.CloudWatchSetAlarmStateAction.html) Class The action to change the state of an Amazon CloudWatch alarm.
- [`DynamoDBv2PutItemAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.DynamoDBv2PutItemAction.html) Class The action to put the record from an MQTT message to the DynamoDB table.
- [`FirehosePutRecordAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.FirehosePutRecordAction.html) Class The action to put the record from an MQTT message to the Amazon Data Firehose stream.
- [`HttpsAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.HttpsAction.html) Class The action to send data from an MQTT message to a web application or service.
- [`IotEventsPutMessageAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.IotEventsPutMessageAction.html) Class The action to put the message from an MQTT message to the IoT Events input.
- [`IotRepublishMqttAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.IotRepublishMqttAction.html) Class The action to put the record from an MQTT message to republish another MQTT topic.
- [`KinesisPutRecordAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.KinesisPutRecordAction.html) Class The action to put the record from an MQTT message to the Kinesis Data stream.
- [`LambdaFunctionAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.LambdaFunctionAction.html) Class The action to invoke an AWS Lambda function, passing in an MQTT message.
- [`OpenSearchAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.OpenSearchAction.html) Class The action to write data to an Amazon OpenSearch Service domain.
- [`S3PutObjectAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.S3PutObjectAction.html) Class The action to write the data from an MQTT message to an Amazon S3 bucket.
- [`SnsTopicAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.SnsTopicAction.html) Class The action to write the data from an MQTT message to an Amazon SNS topic.
- [`SqsQueueAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.SqsQueueAction.html) Class The action to write the data from an MQTT message to an Amazon SQS queue.
- [`StepFunctionsStateMachineAction`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.StepFunctionsStateMachineAction.html) Class The action to put the record from an MQTT message to the Step Functions State Machine.

### Structs

- [`CloudWatchLogsActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.CloudWatchLogsActionProps.html) Struct Configuration properties of an action for CloudWatch Logs.
- [`CloudWatchPutMetricActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.CloudWatchPutMetricActionProps.html) Struct Configuration properties of an action for CloudWatch metric.
- [`CloudWatchSetAlarmStateActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.CloudWatchSetAlarmStateActionProps.html) Struct Configuration properties of an action for CloudWatch alarm.
- [`CommonActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.CommonActionProps.html) Struct Common properties shared by Actions it access to AWS service.
- [`DynamoDBv2PutItemActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.DynamoDBv2PutItemActionProps.html) Struct Configuration properties of an action for the dynamodb table.
- [`FirehosePutRecordActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.FirehosePutRecordActionProps.html) Struct Configuration properties of an action for the Amazon Data Firehose stream.
- [`HttpActionBatchConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.HttpActionBatchConfig.html) Struct Configuration for batching HTTP action messages.
- [`HttpActionHeader`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.HttpActionHeader.html) Struct
- [`HttpActionSigV4Auth`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.HttpActionSigV4Auth.html) Struct
- [`HttpsActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.HttpsActionProps.html) Struct Configuration properties of an HTTPS action.
- [`IotEventsPutMessageActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.IotEventsPutMessageActionProps.html) Struct Configuration properties of an action for the IoT Events.
- [`IotRepublishMqttActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.IotRepublishMqttActionProps.html) Struct Configuration properties of an action to republish MQTT messages.
- [`KinesisPutRecordActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.KinesisPutRecordActionProps.html) Struct Configuration properties of an action for the Kinesis Data stream.
- [`OpenSearchActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.OpenSearchActionProps.html) Struct Configuration properties of an action for Open Search.
- [`S3PutObjectActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.S3PutObjectActionProps.html) Struct Configuration properties of an action for s3.
- [`SnsTopicActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.SnsTopicActionProps.html) Struct Configuration options for the SNS topic action.
- [`SqsQueueActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.SqsQueueActionProps.html) Struct Configuration properties of an action for SQS.
- [`StepFunctionsStateMachineActionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.StepFunctionsStateMachineActionProps.html) Struct Configuration properties of an action for the Step Functions State Machine.

### Enums

- [`FirehoseRecordSeparator`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.FirehoseRecordSeparator.html) Enum Record Separator to be used to separate records.
- [`MqttQualityOfService`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.MqttQualityOfService.html) Enum MQTT Quality of Service (QoS) indicates the level of assurance for delivery of an MQTT Message.
- [`SnsActionMessageFormat`](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-iot-actions-alpha.SnsActionMessageFormat.html) Enum SNS topic action message format options.
