• Documentation
  • Pricing
© 2026 Serverless, Inc. All rights reserved.

Framework

  • Overview
  • Documentation
  • Plugins360
  • Pricing

Learn

  • Blog
  • GuidesUpdated
  • Examples240
  • Courses

Resources

  • Support
  • Security
  • Trust Center
  • Status

Community

  • Slack
  • GitHub47k
  • Forum
  • Meetups

Company

  • About
  • Careers
  • Contact
  • Partners

Legal

  • Terms of Service
  • Privacy Policy
  • Trademark
  • DMCA
Serverless Framework Logo

Serverless Framework

Intro
SetupUpgrading To V4ConceptsTutorialAWS CredentialsLicense Keys
DeployingPackagingBuildingTestingDev ModeServicesFunctions
OverviewHTTP (API Gateway v2)REST (API Gateway v1)ActiveMQApplication Load BalancerAlexa SkillAlexa Smart HomeCloudWatch EventCloudWatch LogCloudFrontCognito User PoolEventBridge EventIoTIoT Fleet ProvisioningKafkaKinesis & DynamoDBMSKRabbitMQS3ScheduleSNSSQSWebsocket
LayersManaged InstancesWeb Apps (Lambda Web Functions)Sandboxes (Lambda MicroVMs)MCP ServersAlertsVersion PruningDomainsIAM Function PermissionsParameters
OverviewSelf-reference serverless.ymlServerless CoreEnvironment VariablesCLI OptionsExternal YAML/JSON FilesJavascript propertiesGitDoppler
OverviewS3 ObjectsSSM Parameter Store & Secrets ManagerCloudFormation Stack Outputs
OverviewVaultTerraform State Output
ResourcesComposing ServicesDeployment BucketStateAgent SkillsPython support
OverviewRuntimeGatewayMemoryBrowserCode InterpreterDev Mode
API Gateway Proxy
OverviewGeneral ConfigurationAuthenticationAPI KeysData SourcesResolversPipeline FunctionsSubstitutionsCachingDelta SyncCustom DomainWAFCLI Commands
Deploying SAM/CFN TemplatesWorkflow Tips
OverviewCreating PluginsCLI OutputCustom CommandsCustom VariablesExtending the Configuration schemaExtending and overriding configuration
OverviewDashboardAxiom
Overviewagent docsagent inspectagent setupagent skills installagent skills list / readdeploydeploy functiondeploy listdevdiffinfoinvokeinvoke localloginlogin awslogin aws ssologsmetricspackageplugin installplugin uninstallprintprunereconcileremoverollbackrollback functionusage
OverviewConcepts
OverviewMetricsTracesTroubleshoot
OverviewNode.jsPython
OutputsProviders
OverviewBranch DeploymentsPreview DeploymentsCustom ScriptsTestingPrivate PackagesNotificationsMono ReposDeploy in your own CI/CDBest PracticesTroubleshootingFAQ
OverviewSetupToolsAWS Integration
Serverless.yml Reference
Examples and TutorialsConfiguration Validation
  1. Usage
  2. Events
  3. Io T

AWS IoT Rule Events

The iot event invokes a Lambda function when devices publish MQTT messages to AWS IoT Core. For each iot event, the Framework creates an AWS IoT topic rule whose SQL statement selects the messages and a Lambda action that passes the result to your function. Use it to process device telemetry or react to device messages; to run code while a device is being provisioned, use IoT fleet provisioning events instead.

The following serverless.yml invokes the ingest function for every message published to a topic under sensors/:

# serverless.yml
service: my-iot-service

provider:
  name: aws
  runtime: nodejs24.x

functions:
  ingest:
    handler: handler.handler
    events:
      - iot:
          sql: "SELECT * FROM 'sensors/+/telemetry'"
          sqlVersion: '2016-03-23'

Quote the whole statement in YAML and put the topic filter in single quotes inside it, as AWS IoT SQL requires. sqlVersion is optional, but AWS IoT uses 2015-10-08 without it, and AWS recommends 2016-03-23 (see SQL version).

iot event settings

The iot event takes an object with these keys:

KeyTypeDefaultDescription
sqlStringRequiredThe rule's AWS IoT SQL statement: SELECT fields FROM a topic filter, with an optional WHERE condition.
sqlVersionStringAWS default 2015-10-08The SQL rules engine version: 2015-10-08, 2016-03-23 or beta.
nameStringGenerated by CloudFormationThe rule name. Letters, digits and underscores only, 1 to 128 characters.
descriptionStringNoneThe rule description.
enabledBooleantrueWhether the rule runs. false deploys the rule disabled.

A function can have several iot events; each creates its own rule and permission.

SQL statement (sql)

The iot event's sql decides which messages invoke the function and what the function receives. The FROM clause is an MQTT topic filter, where + matches one topic level and # matches all remaining levels; WHERE filters messages. The following event invokes the function only for readings above 50 and passes two fields, the message's temperature and the device ID from the topic:

functions:
  ingest:
    handler: handler.handler
    events:
      - iot:
          sql: "SELECT temperature, topic(2) AS deviceId FROM 'sensors/+/telemetry' WHERE temperature > 50"
          sqlVersion: '2016-03-23'

The AWS IoT SQL function topic(N) returns level N of the topic the message arrived on, counting from 1, and topic() returns the whole topic. For a message published to sensors/device-42/telemetry, topic(2) is device-42. To pass the whole message and add the device ID, select * with it: SELECT *, topic(2) AS deviceId FROM 'sensors/+/telemetry' WHERE temperature > 50.

The Framework removes line breaks from sql without adding spaces. To split a long statement over several lines, use a YAML folded block (sql: >), which joins the lines with spaces.

SQL version (sqlVersion)

The iot event's sqlVersion selects the AWS IoT SQL rules engine version:

  • 2016-03-23: recommended by AWS; adds nested object queries and fixes for nested JSON and array queries.
  • 2015-10-08: the original version, and the one AWS IoT uses when sqlVersion is omitted.
  • beta: the most recent beta version, which can introduce breaking changes.

Changing sqlVersion updates the rule in place.

Rule name and description

To give the rule a fixed name, set the iot event's name; to label it in the AWS IoT console, set description:

functions:
  ingest:
    handler: handler.handler
    events:
      - iot:
          name: sensors_telemetry_ingest
          description: Sends sensor telemetry to the ingest function
          sql: "SELECT * FROM 'sensors/+/telemetry'"

AWS IoT rule names allow only letters, digits and underscores, up to 128 characters, and are unique per account and Region, so include the stage in the name when you deploy several stages to one account (for example sensors_ingest_${sls:stage}, with a stage name that has no hyphens). Without name, CloudFormation generates a unique name from the stack and resource names. Changing name replaces the rule. The Framework removes line breaks from name and description.

Disable an IoT rule

To stop the rule from invoking the function without removing it, set the iot event's enabled to false:

functions:
  ingest:
    handler: handler.handler
    events:
      - iot:
          sql: "SELECT * FROM 'sensors/+/telemetry'"
          enabled: false

The rule stays deployed in a disabled state. Set enabled back to true, or remove the key, and deploy again to turn it on.

AWS resources and permissions for iot events

For each iot event, the Framework adds two resources to the stack:

  • An AWS::IoT::TopicRule with the logical ID <FunctionName>IotTopicRule<N> (for example IngestIotTopicRule1). Its only action is a Lambda action that targets the function, or the function's alias when the function uses provisionedConcurrency, SnapStart or durable functions.
  • An AWS::Lambda::Permission with the logical ID <FunctionName>LambdaPermissionIotTopicRule<N>, which lets the principal iot.amazonaws.com call lambda:InvokeFunction, with the source ARN set to that rule's ARN.

The function's execution role needs no extra permissions for this event. The Framework doesn't create things, certificates or AWS IoT policies; devices need their own AWS IoT policies that allow iot:Publish to the topics the rule reads.

The logical IDs start with the function name, with its first letter in uppercase, - replaced by Dash and _ by Underscore: the first iot event of a function named hot-readings creates HotDashreadingsIotTopicRule1.

Error action for an IoT rule

AWS IoT runs a rule's error action when it can't complete one of the rule's actions, for example when it can't invoke the function. The iot event has no error action key: it accepts only the keys in iot event settings. To add an error action, define the rule under resources.Resources with its logical ID, its Type and only ErrorAction. The Framework merges that definition into the rule it generates, so the rule keeps its SQL statement and Lambda action.

The following serverless.yml sends the messages that the ingest function's first iot rule can't deliver to an SQS queue, through an IAM role that AWS IoT assumes to call sqs:SendMessage:

# serverless.yml
service: my-iot-service

provider:
  name: aws
  runtime: nodejs24.x

functions:
  ingest:
    handler: handler.handler
    events:
      - iot:
          sql: "SELECT *, topic(2) AS deviceId FROM 'sensors/+/telemetry' WHERE temperature > 30"
          sqlVersion: '2016-03-23'

resources:
  Resources:
    IngestIotTopicRule1:
      Type: AWS::IoT::TopicRule
      Properties:
        TopicRulePayload:
          ErrorAction:
            Sqs:
              QueueUrl: !Ref IotErrorQueue
              RoleArn: !GetAtt IotErrorActionRole.Arn
    IotErrorQueue:
      Type: AWS::SQS::Queue
    IotErrorActionRole:
      Type: AWS::IAM::Role
      Properties:
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service: iot.amazonaws.com
              Action: sts:AssumeRole
        Policies:
          - PolicyName: iot-error-action
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action: sqs:SendMessage
                  Resource: !GetAtt IotErrorQueue.Arn

The queue receives one message per failed rule run, with the rule name, the topic, the Base64-encoded original payload and the failures, in the error action message format. The SQS action can't send to FIFO queues.

Errors the function throws don't trigger the error action. AWS IoT invokes the function asynchronously, and Lambda accepts the event before the function runs, so Lambda retries a failed invocation and can send it to a failure destination. Configure that with the function's destinations.onFailure and maximumRetryAttempts, described in asynchronous invocation.

Event payload from an AWS IoT rule

AWS IoT invokes the function asynchronously, so the function's return value is discarded and Lambda's asynchronous invocation retry and destination settings apply. The event is the output of the rule's SQL statement, not the raw MQTT message. For example, with the rule SELECT *, topic(2) AS deviceId FROM 'sensors/+/telemetry' WHERE temperature > 30, this message published to sensors/device-42/telemetry:

{
  "temperature": 34.5,
  "humidity": 40
}

invokes the function with this event:

{
  "temperature": 34.5,
  "humidity": 40,
  "deviceId": "device-42"
}

A message with temperature of 30 or lower doesn't invoke the function.

The following handler.mjs logs each event it receives:

// handler.mjs
export const handler = async (event) => {
  console.log('Message from AWS IoT:', JSON.stringify(event))
}

To send a test message, use the MQTT test client in the AWS IoT console and publish to a topic that matches the rule's topic filter.

Examples

  • aws-node-iot-event: a Node.js function with an iot event.
  • Serverless examples: more services to start from.

Related

  • IoT fleet provisioning events: validate devices with a pre-provisioning hook.
  • Rules for AWS IoT: how AWS IoT rules work.
  • serverless.yml reference: IoT: every iot key in one place.
Edit this page
Prev EventBridge EventNextIoT Fleet Provisioning

Contents

  • AWS IoT Rule Events
  • iot event settings
  • SQL statement (sql)
  • SQL version (sqlVersion)
  • Rule name and description
  • Disable an IoT rule
  • AWS resources and permissions for iot events
  • Error action for an IoT rule
  • Event payload from an AWS IoT rule
  • Examples
  • Related

Related

GuidesPluginsExamplesSlack CommunitySupport