# IoT

Source: /aws/services/iot/

## Introduction

AWS IoT provides cloud services to manage IoT devices and integrate them with other AWS services.

LocalStack supports IoT Core, IoT Data, IoT Analytics.
Common operations for creating and updating things, groups, policies, certificates and other entities are implemented with full CloudFormation support.
The supported APIs are available on our [API Coverage section](#api-coverage).

LocalStack ships a [Message Queuing Telemetry Transport (MQTT)](https://mqtt.org/) broker powered by [Eclipse Mosquitto](https://mosquitto.org/) which supports both pure MQTT and MQTT-over-WSS (WebSockets Secure) protocols.

## Getting Started

This guide is for users that are new to IoT and assumes a basic knowledge of the AWS CLI and LocalStack [`lstk aws`](/aws/developer-tools/running-localstack/lstk/cloud-and-iac-commands/#aws) command.

Start LocalStack using your preferred method.

To retrieve the MQTT endpoint, use the [`DescribeEndpoint`](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeEndpoint.html) operation.

```bash
lstk aws iot describe-endpoint
```

```bash title="Output"
{
    "endpointAddress": "000000000000.iot.eu-central-1.localhost.localstack.cloud:4510"
}
```

:::tip
LocalStack lazy-loads services by default.
The MQTT broker may not be automatically available on a fresh launch of LocalStack.
You can make a `DescribeEndpoint` call to start the broker and identify the port.
:::

This endpoint can then be used with any MQTT client to publish and subscribe to topics.
In this example, we will use the [Hive MQTT CLI](https://hivemq.github.io/mqtt-cli/docs/installation/).

Run the following command to subscribe to an MQTT topic.

```bash
mqtt subscribe \
        --host 000000000000.iot.eu-central-1.localhost.localstack.cloud \
        --port 4510 \
        --topic climate
```

In a separate terminal session, publish a message to this topic.

```bash
mqtt publish \
        --host 000000000000.iot.eu-central-1.localhost.localstack.cloud \
        --port 4510 \
        --topic climate \
        -m "temperature=30°C;humidity=60%"
```

This message will be pushed to all subscribers of this topic, including the one in the first terminal session.

## Authentication

LocalStack IoT maintains its own root certificate authority which is regenerated at every run.
The root CA certificate can be retrieved from [`http://localhost.localstack.cloud:4566/_aws/iot/LocalStackIoTRootCA.pem`](http://localhost.localstack.cloud:4566/_aws/iot/LocalStackIoTRootCA.pem).

:::tip
AWS provides its root CA certificate at [`https://www.amazontrust.com/repository/AmazonRootCA1.pem`](https://www.amazontrust.com/repository/AmazonRootCA1.pem).
[This section](https://docs.aws.amazon.com/iot/latest/developerguide/server-authentication.html#server-authentication-certs) contains information about CA certificates.
:::

When connecting to the endpoints, you will need to provide this root CA certificate for authentication.
This is illustrated below with Python [AWS IoT SDK](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sdks.html),

```py showshowLineNumbers
import awscrt
import boto3
from awsiot import mqtt_connection_builder

region = 'eu-central-1'
iot_client = boto3.client('iot', region=region)
endpoint = aws_client.iot.describe_endpoint()["endpointAddress"]
endpoint, port = endpoint.split(':')

event_loop_group = io.EventLoopGroup(1)
host_resolver = io.DefaultHostResolver(event_loop_group)
client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver)

credentials_provider = awscrt.auth.AwsCredentialsProvider.new_static(
    access_key_id='...',
    secret_access_key='...',
)

client_id = 'example-client'

# Path to root CA certificate downloaded from `/_aws/iot/LocalStackIoTRootCA.pem`
ca_filepath = '...'

mqtt_over_wss = mqtt_connection_builder.websockets_with_default_aws_signing(
    region=region,
    credentials_provider=credentials_provider,
    client_bootstrap=client_bootstrap,
    client_id=client_id,
    endpoint=endpoint,
    port=port,
    ca_filepath=ca_filepath,
)

mqtt_over_wss.connect().result()
mqtt_over_wss.subscribe(...)
```

If you are using pure MQTT, you also need to set the client-side X509 certificates and Application Layer Protocol Negotiation (ALPN) for a successful mutual TLS (mTLS) authentication.
This is not required for MQTT-over-WSS since it does not use mTLS.

AWS IoT SDKs automatically set the ALPN when the endpoint port is 443.
However, because LocalStack does not use this port, this must be done manually.
For details on how ALPN works with AWS, see [this page](https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html).

The client certificate and key can be retrieved using `CreateKeysAndCertificate` operation.
The certificate is signed by the LocalStack root CA.

```py showshowLineNumbers
result = iot_client.create_keys_and_certificate(setAsActive=True)

# Path to file with saved content `result["certificatePem"]`
cert_file = '...'

# Path to file with saved content `result["keyPair"]["PrivateKey"]`
priv_key_file = '...'

tls_ctx_options = awscrt.io.TlsContextOptions.create_client_with_mtls_from_path(
    cert_file, priv_key_file
)
tls_ctx_options.alpn_list = ["x-amzn-mqtt-ca"]

mqtt = mqtt_connection_builder._builder(
    tls_ctx_options,
    cert_filepath=cert_file,
    pri_key_filepath=priv_key_file,
    client_bootstrap=client_bootstrap,
    client_id=client_id,
    endpoint=endpoint,
    port=port,
    ca_filepath=ca_filepath,
)

mqtt.connect().result()
mqtt.subscribe(...)
```

## Lifecycle Events

LocalStack publishes the [lifecycle events](https://docs.aws.amazon.com/iot/latest/developerguide/life-cycle-events.html) to the standard endpoints.

- `$aws/events/presence/connected/clientId`: when a client connects
- `$aws/events/presence/disconnected/clientId`: when a client disconnects
- `$aws/events/subscriptions/subscribed/clientId`: when a client subscribes to a topic
- `$aws/events/subscriptions/unsubscribed/clientId`: when a client unsubscribes from a topic

Currently the `principalIdentifier` and `sessionIdentifier` fields in event payload contain dummy values.

## Registry Events

LocalStack can publish the [registry events](https://docs.aws.amazon.com/iot/latest/developerguide/registry-events.html), if [you enable it](https://docs.aws.amazon.com/iot/latest/developerguide/iot-events.html#iot-events-enable).

```bash
lstk aws iot update-event-configurations \
    --event-configurations '{"THING":{"Enabled": true}}'
```

You can then subscribe or use topic rules on the follow topics:

- `$aws/events/thing/<thingName>/created`: when a new thing is created
- `$aws/events/thing/<thingName>/updated`: when a thing is updated
- `$aws/events/thing/<thingName>/deleted`: when a thing is deleted

## Topic Rules

It is possible to use actions with SQL queries for IoT Topic Rules.

For example, you can use the [`CreateTopicRule`](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateTopicRule.html) operation to define a topic rule with a SQL query `SELECT * FROM 'my/topic' where attr=123` which will execute a trigger whenever a message with attribute `attr=123` is received on the MQTT topic `my/topic`.

The following actions are supported:
- [Lambda](https://docs.aws.amazon.com/iot/latest/developerguide/lambda-rule-action.html)
- [SQS](https://docs.aws.amazon.com/iot/latest/developerguide/sqs-rule-action.html)
- [Kinesis](https://docs.aws.amazon.com/iot/latest/developerguide/kinesis-rule-action.html)
- [Firehose](https://docs.aws.amazon.com/iot/latest/developerguide/kinesis-firehose-rule-action.html)
- [DynamoDBv2](https://docs.aws.amazon.com/iot/latest/developerguide/dynamodb-v2-rule-action.html)
- [HTTP](https://docs.aws.amazon.com/iot/latest/developerguide/https-rule-action.html) (URL confirmation and substitution templating is not implemented)

## Troubleshooting

### Node.js `aws-iot-device-sdk` Connection Issues

When using the [`aws-iot-device-sdk`](https://github.com/aws/aws-iot-device-sdk-js) library, you may encounter SSL certificate errors because Node.js rejects self-signed certificates by default.

**Solution:** Set the environment variable to disable certificate validation:

```bash
export NODE_TLS_REJECT_UNAUTHORIZED=0
```

**For Lambda functions**, you also need to explicitly set the `region` parameter in the device configuration:

```js
const device = new iot.device({
  protocol: 'wss',
  host: endpoint,
  region: process.env.AWS_REGION, // Required for LocalStack
  // ... other options
});
```

And configure the Lambda environment:

```bash
lstk aws lambda update-function-configuration \
  --function-name your-function-name \
  --environment "Variables={NODE_TLS_REJECT_UNAUTHORIZED=0}"
```

:::caution
Only use `NODE_TLS_REJECT_UNAUTHORIZED=0` in development environments. As an alternative, consider using standard MQTT libraries like [MQTT.js](https://github.com/mqttjs/MQTT.js).
:::

## API Coverage


### Internet of Things API coverage

Source service: `iot`. 109 of 272 tracked operations are implemented.

Service documentation: /aws/services/iot/
License availability: available starting with the Base plan. See /aws/licensing/ for current plan details.

| Operation | Status |
| --- | --- |
| AcceptCertificateTransfer | Not implemented |
| AddThingToBillingGroup | Implemented |
| AddThingToThingGroup | Implemented |
| AssociateSbomWithPackageVersion | Not implemented |
| AssociateTargetsWithJob | Not implemented |
| AttachPolicy | Implemented |
| AttachPrincipalPolicy | Implemented |
| AttachSecurityProfile | Not implemented |
| AttachThingPrincipal | Implemented |
| CancelAuditMitigationActionsTask | Not implemented |
| CancelAuditTask | Not implemented |
| CancelCertificateTransfer | Not implemented |
| CancelDetectMitigationActionsTask | Not implemented |
| CancelJob | Implemented |
| CancelJobExecution | Implemented |
| ClearDefaultAuthorizer | Not implemented |
| ConfirmTopicRuleDestination | Not implemented |
| CreateAuditSuppression | Not implemented |
| CreateAuthorizer | Not implemented |
| CreateBillingGroup | Implemented |
| CreateCertificateFromCsr | Implemented |
| CreateCertificateProvider | Not implemented |
| CreateCommand | Not implemented |
| CreateCustomMetric | Not implemented |
| CreateDimension | Not implemented |
| CreateDomainConfiguration | Implemented |
| CreateDynamicThingGroup | Implemented |
| CreateFleetMetric | Not implemented |
| CreateJob | Implemented |
| CreateJobTemplate | Implemented |
| CreateKeysAndCertificate | Implemented |
| CreateMitigationAction | Not implemented |
| CreateOTAUpdate | Not implemented |
| CreatePackage | Not implemented |
| CreatePackageVersion | Not implemented |
| CreatePolicy | Implemented |
| CreatePolicyVersion | Implemented |
| CreateProvisioningClaim | Not implemented |
| CreateProvisioningTemplate | Not implemented |
| CreateProvisioningTemplateVersion | Not implemented |
| CreateRoleAlias | Implemented |
| CreateScheduledAudit | Not implemented |
| CreateSecurityProfile | Not implemented |
| CreateStream | Not implemented |
| CreateThing | Implemented |
| CreateThingGroup | Implemented |
| CreateThingType | Implemented |
| CreateTopicRule | Implemented |
| CreateTopicRuleDestination | Implemented |
| DeleteAccountAuditConfiguration | Not implemented |
| DeleteAuditSuppression | Not implemented |
| DeleteAuthorizer | Not implemented |
| DeleteBillingGroup | Implemented |
| DeleteCACertificate | Implemented |
| DeleteCertificate | Implemented |
| DeleteCertificateProvider | Not implemented |
| DeleteCommand | Not implemented |
| DeleteCommandExecution | Not implemented |
| DeleteCustomMetric | Not implemented |
| DeleteDimension | Not implemented |
| DeleteDomainConfiguration | Implemented |
| DeleteDynamicThingGroup | Implemented |
| DeleteFleetMetric | Not implemented |
| DeleteJob | Implemented |
| DeleteJobExecution | Implemented |
| DeleteJobTemplate | Implemented |
| DeleteMitigationAction | Not implemented |
| DeleteOTAUpdate | Not implemented |
| DeletePackage | Not implemented |
| DeletePackageVersion | Not implemented |
| DeletePolicy | Implemented |
| DeletePolicyVersion | Implemented |
| DeleteProvisioningTemplate | Not implemented |
| DeleteProvisioningTemplateVersion | Not implemented |
| DeleteRegistrationCode | Not implemented |
| DeleteRoleAlias | Implemented |
| DeleteScheduledAudit | Not implemented |
| DeleteSecurityProfile | Not implemented |
| DeleteStream | Not implemented |
| DeleteThing | Implemented |
| DeleteThingGroup | Implemented |
| DeleteThingType | Implemented |
| DeleteTopicRule | Implemented |
| DeleteTopicRuleDestination | Implemented |
| DeleteV2LoggingLevel | Not implemented |
| DeprecateThingType | Implemented |
| DescribeAccountAuditConfiguration | Not implemented |
| DescribeAuditFinding | Not implemented |
| DescribeAuditMitigationActionsTask | Not implemented |
| DescribeAuditSuppression | Not implemented |
| DescribeAuditTask | Not implemented |
| DescribeAuthorizer | Not implemented |
| DescribeBillingGroup | Implemented |
| DescribeCACertificate | Implemented |
| DescribeCertificate | Implemented |
| DescribeCertificateProvider | Not implemented |
| DescribeCustomMetric | Not implemented |
| DescribeDefaultAuthorizer | Not implemented |
| DescribeDetectMitigationActionsTask | Not implemented |
| DescribeDimension | Not implemented |
| DescribeDomainConfiguration | Implemented |
| DescribeEncryptionConfiguration | Not implemented |
| DescribeEndpoint | Implemented |
| DescribeEventConfigurations | Not implemented |
| DescribeFleetMetric | Not implemented |
| DescribeIndex | Not implemented |
| DescribeJob | Implemented |
| DescribeJobExecution | Implemented |
| DescribeJobTemplate | Implemented |
| DescribeManagedJobTemplate | Not implemented |
| DescribeMitigationAction | Not implemented |
| DescribeProvisioningTemplate | Not implemented |
| DescribeProvisioningTemplateVersion | Not implemented |
| DescribeRoleAlias | Implemented |
| DescribeScheduledAudit | Not implemented |
| DescribeSecurityProfile | Not implemented |
| DescribeStream | Not implemented |
| DescribeThing | Implemented |
| DescribeThingGroup | Implemented |
| DescribeThingRegistrationTask | Not implemented |
| DescribeThingType | Implemented |
| DetachPolicy | Implemented |
| DetachPrincipalPolicy | Implemented |
| DetachSecurityProfile | Not implemented |
| DetachThingPrincipal | Implemented |
| DisableTopicRule | Implemented |
| DisassociateSbomFromPackageVersion | Not implemented |
| EnableTopicRule | Implemented |
| GetBehaviorModelTrainingSummaries | Not implemented |
| GetBucketsAggregation | Not implemented |
| GetCardinality | Not implemented |
| GetCommand | Not implemented |
| GetCommandExecution | Not implemented |
| GetEffectivePolicies | Not implemented |
| GetIndexingConfiguration | Implemented |
| GetJobDocument | Implemented |
| GetLoggingOptions | Not implemented |
| GetOTAUpdate | Not implemented |
| GetPackage | Not implemented |
| GetPackageConfiguration | Not implemented |
| GetPackageVersion | Not implemented |
| GetPercentiles | Not implemented |
| GetPolicy | Implemented |
| GetPolicyVersion | Implemented |
| GetRegistrationCode | Implemented |
| GetStatistics | Not implemented |
| GetThingConnectivityData | Not implemented |
| GetTopicRule | Implemented |
| GetTopicRuleDestination | Not implemented |
| GetV2LoggingOptions | Not implemented |
| ListActiveViolations | Not implemented |
| ListAttachedPolicies | Implemented |
| ListAuditFindings | Not implemented |
| ListAuditMitigationActionsExecutions | Not implemented |
| ListAuditMitigationActionsTasks | Not implemented |
| ListAuditSuppressions | Not implemented |
| ListAuditTasks | Not implemented |
| ListAuthorizers | Not implemented |
| ListBillingGroups | Implemented |
| ListCACertificates | Not implemented |
| ListCertificateProviders | Not implemented |
| ListCertificates | Implemented |
| ListCertificatesByCA | Implemented |
| ListCommandExecutions | Not implemented |
| ListCommands | Not implemented |
| ListCustomMetrics | Not implemented |
| ListDetectMitigationActionsExecutions | Not implemented |
| ListDetectMitigationActionsTasks | Not implemented |
| ListDimensions | Not implemented |
| ListDomainConfigurations | Implemented |
| ListFleetMetrics | Not implemented |
| ListIndices | Not implemented |
| ListJobExecutionsForJob | Implemented |
| ListJobExecutionsForThing | Implemented |
| ListJobTemplates | Implemented |
| ListJobs | Implemented |
| ListManagedJobTemplates | Not implemented |
| ListMetricValues | Not implemented |
| ListMitigationActions | Not implemented |
| ListOTAUpdates | Not implemented |
| ListOutgoingCertificates | Not implemented |
| ListPackageVersions | Not implemented |
| ListPackages | Not implemented |
| ListPolicies | Implemented |
| ListPolicyPrincipals | Implemented |
| ListPolicyVersions | Implemented |
| ListPrincipalPolicies | Implemented |
| ListPrincipalThings | Implemented |
| ListPrincipalThingsV2 | Not implemented |
| ListProvisioningTemplateVersions | Not implemented |
| ListProvisioningTemplates | Not implemented |
| ListRelatedResourcesForAuditFinding | Not implemented |
| ListRoleAliases | Implemented |
| ListSbomValidationResults | Not implemented |
| ListScheduledAudits | Not implemented |
| ListSecurityProfiles | Not implemented |
| ListSecurityProfilesForTarget | Not implemented |
| ListStreams | Not implemented |
| ListTagsForResource | Implemented |
| ListTargetsForPolicy | Implemented |
| ListTargetsForSecurityProfile | Not implemented |
| ListThingGroups | Implemented |
| ListThingGroupsForThing | Implemented |
| ListThingPrincipals | Implemented |
| ListThingPrincipalsV2 | Implemented |
| ListThingRegistrationTaskReports | Not implemented |
| ListThingRegistrationTasks | Not implemented |
| ListThingTypes | Implemented |
| ListThings | Implemented |
| ListThingsInBillingGroup | Implemented |
| ListThingsInThingGroup | Implemented |
| ListTopicRuleDestinations | Not implemented |
| ListTopicRules | Implemented |
| ListV2LoggingLevels | Not implemented |
| ListViolationEvents | Not implemented |
| PutVerificationStateOnViolation | Not implemented |
| RegisterCACertificate | Implemented |
| RegisterCertificate | Implemented |
| RegisterCertificateWithoutCA | Implemented |
| RegisterThing | Not implemented |
| RejectCertificateTransfer | Not implemented |
| RemoveThingFromBillingGroup | Implemented |
| RemoveThingFromThingGroup | Implemented |
| ReplaceTopicRule | Implemented |
| SearchIndex | Implemented |
| SetDefaultAuthorizer | Not implemented |
| SetDefaultPolicyVersion | Implemented |
| SetLoggingOptions | Not implemented |
| SetV2LoggingLevel | Not implemented |
| SetV2LoggingOptions | Not implemented |
| StartAuditMitigationActionsTask | Not implemented |
| StartDetectMitigationActionsTask | Not implemented |
| StartOnDemandAuditTask | Not implemented |
| StartThingRegistrationTask | Not implemented |
| StopThingRegistrationTask | Not implemented |
| TagResource | Implemented |
| TestAuthorization | Not implemented |
| TestInvokeAuthorizer | Not implemented |
| TransferCertificate | Not implemented |
| UntagResource | Implemented |
| UpdateAccountAuditConfiguration | Not implemented |
| UpdateAuditSuppression | Not implemented |
| UpdateAuthorizer | Not implemented |
| UpdateBillingGroup | Implemented |
| UpdateCACertificate | Implemented |
| UpdateCertificate | Implemented |
| UpdateCertificateProvider | Not implemented |
| UpdateCommand | Not implemented |
| UpdateCustomMetric | Not implemented |
| UpdateDimension | Not implemented |
| UpdateDomainConfiguration | Implemented |
| UpdateDynamicThingGroup | Implemented |
| UpdateEncryptionConfiguration | Not implemented |
| UpdateEventConfigurations | Implemented |
| UpdateFleetMetric | Not implemented |
| UpdateIndexingConfiguration | Implemented |
| UpdateJob | Not implemented |
| UpdateMitigationAction | Not implemented |
| UpdatePackage | Not implemented |
| UpdatePackageConfiguration | Not implemented |
| UpdatePackageVersion | Not implemented |
| UpdateProvisioningTemplate | Not implemented |
| UpdateRoleAlias | Implemented |
| UpdateScheduledAudit | Not implemented |
| UpdateSecurityProfile | Not implemented |
| UpdateStream | Not implemented |
| UpdateThing | Implemented |
| UpdateThingGroup | Implemented |
| UpdateThingGroupsForThing | Implemented |
| UpdateThingType | Not implemented |
| UpdateTopicRuleDestination | Not implemented |
| ValidateSecurityProfileBehaviors | Not implemented |
