Iot DG PDF
Iot DG PDF
Iot DG PDF
Developer Guide
AWS IoT Developer Guide
Table of Contents
What Is AWS IoT? .............................................................................................................................. 1
AWS IoT Components ................................................................................................................. 1
How to Get Started with AWS IoT ................................................................................................ 2
Accessing AWS IoT ..................................................................................................................... 2
Related Services ......................................................................................................................... 3
How AWS IoT Works ................................................................................................................... 3
Getting Started with AWS IoT ............................................................................................................. 5
Sign in to the AWS IoT Console ................................................................................................... 5
Register a Device in the Registry .................................................................................................. 6
Create and Activate a Device Certificate .............................................................................. 15
Create an AWS IoT Policy .................................................................................................. 17
Attach an AWS IoT Policy to a Device Certificate .................................................................. 20
Attach a Certificate to a Thing ........................................................................................... 22
Configure Your Device ............................................................................................................... 25
View Device MQTT Messages with the AWS IoT MQTT Client .......................................................... 25
Configure and Test Rules ........................................................................................................... 27
Create an SNS Topic ......................................................................................................... 27
Subscribe to an Amazon SNS Topic .................................................................................... 29
Create a Rule ................................................................................................................... 30
Test the Amazon SNS Rule ................................................................................................ 36
Next Steps ....................................................................................................................... 37
Create and Track an AWS IoT Job ............................................................................................... 37
Connect Your Device to AWS IoT ........................................................................................ 37
Run the Jobs Sample ........................................................................................................ 37
Create a Job Document ..................................................................................................... 38
Create a Job .................................................................................................................... 38
Execute the Job on a Device .............................................................................................. 45
Tracking Job Progress with Job and Job Execution Events ...................................................... 46
AWS IoT Rules Tutorials .................................................................................................................... 50
Creating an Amazon DynamoDB Rule ......................................................................................... 50
Testing an Amazon DynamoDB Rule ................................................................................... 60
Creating an AWS Lambda Rule ................................................................................................... 61
Create a Lambda Function ................................................................................................. 61
Test Your Lambda Function ............................................................................................... 66
Create a Lambda Rule ....................................................................................................... 68
Test Your Lambda Rule ..................................................................................................... 78
Troubleshooting Lambda Rules .......................................................................................... 79
Creating an Amazon SNS Rule ................................................................................................... 80
AWS IoT SDK Tutorials ...................................................................................................................... 89
Prerequisites ............................................................................................................................ 89
Create an AWS IoT Thing for Your Raspberry Pi ........................................................................... 89
Using the AWS IoT Embedded C SDK ........................................................................................ 102
Set Up the Runtime Environment for the AWS IoT Embedded C SDK ..................................... 102
Sample App Configuration ............................................................................................... 102
Run Sample Applications ................................................................................................. 104
Using the AWS IoT Device SDK for JavaScript ............................................................................. 105
Set Up the Runtime Environment for the AWS IoT Device SDK for JavaScript .......................... 105
Install the AWS IoT Device SDK for JavaScript .................................................................... 106
Prepare to Run the Sample Applications ............................................................................ 106
Run the Sample Applications ........................................................................................... 107
AWS IoT Additional Tutorials ............................................................................................................ 109
AWS IoT Plant Watering Sample ............................................................................................... 109
Module 1: Setting Up AWS IoT and Sending Data with Your Development Computer ................ 109
Module 2: Sending Data with the Raspberry Pi ................................................................... 129
iii
AWS IoT Developer Guide
iv
AWS IoT Developer Guide
v
AWS IoT Developer Guide
vi
AWS IoT Developer Guide
vii
AWS IoT Developer Guide
viii
AWS IoT Developer Guide
ix
AWS IoT Developer Guide
x
AWS IoT Developer Guide
xi
AWS IoT Developer Guide
AWS IoT Components
Device gateway
Provides a secure mechanism for devices and AWS IoT applications to publish and receive messages
from each other. You can use either the MQTT protocol directly or MQTT over WebSocket to publish
and subscribe. You can use the HTTP REST interface to publish.
Rules engine
Provides message processing and integration with other AWS services. You can use an SQL-based
language to select data from message payloads, and then process and send the data to other
services, such as Amazon S3, Amazon DynamoDB, and AWS Lambda. You can also use the message
broker to republish messages to other subscribers.
Security and Identity service
Provides shared responsibility for security in the AWS Cloud. Your devices must keep their
credentials safe in order to securely send data to the message broker. The message broker and rules
engine use AWS security features to send data securely to devices or other AWS services.
Registry
Organizes the resources associated with each device in the AWS Cloud. You register your devices and
associate up to three custom attributes with each one. You can also associate certificates and MQTT
client IDs with each device to improve your ability to manage and troubleshoot them.
Group registry
Groups allow you to manage several devices at once by categorizing them into groups. Groups
can also contain groups—you can build a hierarchy of groups. Any action you perform on a parent
group will apply to its child groups, and to all the devices in it and in all of its child groups as well.
Permissions given to a group will apply to all devices in the group and in all of its child groups.
Device shadow
A JSON document used to store and retrieve current state information for a device.
Device Shadow service
Provides persistent representations of your devices in the AWS Cloud. You can publish updated state
information to a device's shadow, and your device can synchronize its state when it connects. Your
devices can also publish their current state to a shadow for use by applications or other devices.
1
AWS IoT Developer Guide
How to Get Started with AWS IoT
Allows you to provision devices using a template that describes the resources required for your
device: a thing, a certificate, and one or more policies. A thing is an entry in the registry that contains
attributes that describe a device. Devices use certificates to authenticate with AWS IoT. Policies
determine which operations a device can perform in AWS IoT.
The templates contain variables that are replaced by values in a dictionary (map). You can use the
same template to provision multiple devices just by passing in different values for the template
variables in the dictionary.
Custom Authentication service
You can define custom authorizers that allow you to manage your own authentication and
authorization strategy using a custom authentication service and a Lambda function. Custom
authorizers allow AWS IoT to authenticate your devices and authorize operations using bearer token
authentication and authorization strategies.
Custom authorizers can implement various authentication strategies (for example, JSON Web Token
verification, OAuth provider callout, and so on) and must return policy documents that are used by
the device gateway to authorize MQTT operations.
Jobs service
Allows you to define a set of remote operations that are sent to and executed on one or more
devices connected to AWS IoT. For example, you can define a job that instructs a set of devices to
download and install application or firmware updates, reboot, rotate certificates, or perform remote
troubleshooting operations.
To create a job, you specify a description of the remote operations to be performed and a list of
targets that should perform them. The targets can be individual devices, groups or both.
For information about AWS IoT limits, see AWS IoT Limits.
• AWS Command Line Interface (AWS CLI)—Run commands for AWS IoT on Windows, macOS, and
Linux. These commands allow you to create and manage things, certificates, rules, and policies. To get
started, see the AWS Command Line Interface User Guide. For more information about the commands
for AWS IoT, see iot in the AWS CLI Command Reference.
• AWS IoT API—Build your IoT applications using HTTP or HTTPS requests. These API actions allow you
to programmatically create and manage things, certificates, rules, and policies. For more information
about the API actions for AWS IoT, see Actions in the AWS IoT API Reference.
• AWS SDKs—Build your IoT applications using language-specific APIs. These SDKs wrap the HTTP/
HTTPS API and allow you to program in any of the supported languages. For more information, see
AWS SDKs and Tools.
• AWS IoT Device SDKs—Build applications that run on devices that send messages to and receive
messages from AWS IoT. For more information see, AWS IoT SDKs.
2
AWS IoT Developer Guide
Related Services
Related Services
AWS IoT integrates directly with the following AWS services:
• Amazon Simple Storage Service—Provides scalable storage in the AWS Cloud. For more information,
see Amazon S3.
• Amazon DynamoDB—Provides managed NoSQL databases. For more information, see Amazon
DynamoDB.
• Amazon Kinesis—Enables real-time processing of streaming data at a massive scale. For more
information, see Amazon Kinesis.
• AWS Lambda—Runs your code on virtual servers from Amazon EC2 in response to events. For more
information, see AWS Lambda.
• Amazon Simple Notification Service—Sends or receives notifications. For more information, see
Amazon SNS.
• Amazon Simple Queue Service—Stores data in a queue to be retrieved by applications. For more
information, see Amazon SQS.
Devices report their state by publishing messages, in JSON format, on MQTT topics. Each MQTT topic has
a hierarchical name that identifies the device whose state is being updated. When a message is published
on an MQTT topic, the message is sent to the AWS IoT MQTT message broker, which is responsible for
sending all messages published on an MQTT topic to all clients subscribed to that topic.
Communication between a device and AWS IoT is protected through the use of X.509 certificates.
AWS IoT can generate a certificate for you or you can use your own. In either case, the certificate
must be registered and activated with AWS IoT, and then copied onto your device. When your device
communicates with AWS IoT, it presents the certificate to AWS IoT as a credential.
We recommend that all devices that connect to AWS IoT have an entry in the registry. The registry stores
information about a device and the certificates that are used by the device to secure communication with
AWS IoT.
You can create rules that define one or more actions to perform based on the data in a message. For
example, you can insert, update, or query a DynamoDB table or invoke a Lambda function. Rules use
expressions to filter messages. When a rule matches a message, the rules engine triggers the action
using the selected properties. Rules also contain an IAM role that grants AWS IoT permission to the AWS
resources used to perform the action.
3
AWS IoT Developer Guide
How AWS IoT Works
Each device has a shadow that stores and retrieves state information. Each item in the state information
has two entries: the state last reported by the device and the desired state requested by an application.
An application can request the current state information for a device. The shadow responds to the
request by providing a JSON document with the state information (both reported and desired),
metadata, and a version number. An application can control a device by requesting a change in its state.
The shadow accepts the state change request, updates its state information, and sends a message to
indicate the state information has been updated. The device receives the message, changes its state, and
then reports its new state.
4
AWS IoT Developer Guide
Sign in to the AWS IoT Console
For more information about AWS IoT, see What Is AWS IoT (p. 1).
Topics
• Sign in to the AWS IoT Console (p. 5)
• Register a Device in the Registry (p. 6)
• Configure Your Device (p. 25)
• View Device MQTT Messages with the AWS IoT MQTT Client (p. 25)
• Configure and Test Rules (p. 27)
• Create and Track an AWS IoT Job (p. 37)
1. Open the AWS home page and choose Create an AWS Account.
2. Follow the online instructions. Part of the sign-up procedure involves receiving a phone call and
entering a PIN using your phone's keypad.
3. Sign in to the AWS Management Console and open the AWS IoT console.
4. On the Welcome page, choose Get started.
If this is your first time using the AWS IoT console, you see the Welcome to the AWS IoT Console
page.
5
AWS IoT Developer Guide
Register a Device in the Registry
1. On the Welcome to the AWS IoT Console page, in the navigation pane, choose Manage.
2. On the You don't have any things yet page, choose Register a thing.
3. On the Creating AWS IoT things page, choose Create a single thing.
6
AWS IoT Developer Guide
Register a Device in the Registry
4. On the Create a thing page, in the Name field, type a name for your thing, such as MyIotThing.
Choose Next.
Note
We do not recommended using personally identifiable information in your thing name.
7
AWS IoT Developer Guide
Register a Device in the Registry
5. On the Add a certificate for your thing page, choose Create certificate. This generates an X.509
certificate and key pair.
8
AWS IoT Developer Guide
Register a Device in the Registry
6. On the Certificate created! page, download your public and private keys, certificate, and root
certificate authority (CA):
Most web browsers save downloaded files into a Downloads directory. You will copy these files to
a different directory when you run the sample applications. Choose Activate to activate the X.509
certificate, and then choose Attach a policy.
9
AWS IoT Developer Guide
Register a Device in the Registry
7. On the Add a policy for your thing page, choose Register Thing.
After you register your thing, you will need to create and attach a new policy to the certificate.
10
AWS IoT Developer Guide
Register a Device in the Registry
8. On the AWS IoT console, in the navigation pane, choose Secure and Policies.
Choose Create.
This policy allows your device to perform all AWS IoT actions on all AWS IoT resources.
Important
These settings are overly permissive. In a production environment narrow the scope of
the permissions to that which are required by your device. For more information, see
Authorization (p. 192).
11
AWS IoT Developer Guide
Register a Device in the Registry
10. Choose Manage and then choose your AWS IoT thing.
12
AWS IoT Developer Guide
Register a Device in the Registry
13
AWS IoT Developer Guide
Register a Device in the Registry
14. Choose the policy you created (MyIotPolicy) and choose Attach.
14
AWS IoT Developer Guide
Create and Activate a Device Certificate
2. On the Certificate created! page, choose Download for the certificate, private key, and the root CA
for AWS IoT (the public key need not be downloaded). Save each of them to your computer, and
then choose Activate to continue.
Note
The root CA for AWS IoT Download link takes you to the X.509 Certificates and AWS
IoT (p. 180) page where you choose a CA certificate. Unlike the other Download links on
the page, it doesn't directly download a file.
15
AWS IoT Developer Guide
Create and Activate a Device Certificate
Be aware that the downloaded filenames may be different than those listed on the Certificate
created! page. For example:
• 2a540e2346-certificate.pem.crt
• 2a540e2346-private.pem.key
• 2a540e2346-public.pem.key
Note
Although it is unlikely, root CA certificates are subject to expiration and/or revocation. If
this should occur, you must copy new a root CA certificate onto your device.
3. Choose Done to return to the AWS IoT console main page.
16
AWS IoT Developer Guide
Create an AWS IoT Policy
When working with a device you will need to copy the private key and rootCA certificate onto your
device. This guide assumes you are not using a device and are trying out AWS IoT using the console.
1. In the left navigation pane, choose Secure, and then Policies. On the You don't have a policy yet
page, choose Create a policy.
17
AWS IoT Developer Guide
Create an AWS IoT Policy
2. On the Create a policy page, in the Name field, type a name for the policy (for example,
MyIotPolicy).
Note
We do not recommended using personally identifiable information in your policy names.
In the Action field, type iot:Connect. In the Resource ARN field, type *. Select the Allow check box.
This allows all clients to connect to AWS IoT.
18
AWS IoT Developer Guide
Create an AWS IoT Policy
Note
You can restrict which clients (devices) are able to connect by specifying a client ARN as the
resource. The client ARNs follow this format:
arn:aws:iot:your-region:your-aws-account:client/<my-client-id>
Select the Add Statement button to add another policy statement. In the Action field, type
iot:Publish. In the Resource ARN field, type the ARN of the topic to which your device will publish.
Note
The topic ARN follows this format:
arn:aws:iot:your-region:your-aws-account:topic/<your/topic>
For example:
arn:aws:iot:us-east-1:123456789012:topic/my/topic
Finally, select the Allow check box. This allows your device to publish messages to the specified
topic.
3. After you have entered the information for your policy, choose Create.
19
AWS IoT Developer Guide
Attach an AWS IoT Policy to a Device Certificate
20
AWS IoT Developer Guide
Attach an AWS IoT Policy to a Device Certificate
2. In the box for the certificate you created, choose ... to open a drop-down menu, and then choose
Attach policy.
3. In the Attach policies to certificate(s) dialog box, select the check box next to the policy you
created in the previous step, and then choose Attach.
21
AWS IoT Developer Guide
Attach a Certificate to a Thing
1. In the box for the certificate you created, choose ... to open a drop-down menu, and then choose
Attach thing.
22
AWS IoT Developer Guide
Attach a Certificate to a Thing
2. In the Attach things to certificate(s) dialog box, select the check box next to the thing you
registered, and then choose Attach.
3. To verify the thing is attached, select the box representing the certificate.
23
AWS IoT Developer Guide
Attach a Certificate to a Thing
4. On the Details page for the certificate, in the left navigation pane, choose Things.
5. To verify the policy is attached, on the Details page for the certificate, in the left navigation pane,
choose Policies.
24
AWS IoT Developer Guide
Configure Your Device
If you don't have an IoT-ready device, you can use the MQTT client, the AWS IoT Device SDKs or the AWS
CLI. For more information, see the AWS IoT SDK Tutorials (p. 89) section. The tutorials there use a
Raspberry Pi but can easily be adapted for use with other types of computers.
Devices publish MQTT messages on topics. You can use the AWS IoT MQTT client to subscribe to these
topics to see these messages.
1. In the AWS IoT console, in the left navigation pane, choose Test.
2. Subscribe to the topic on which your IoT thing publishes. Continuing with this example, in Subscribe
to a topic, in the Subscription topic field, type my/topic, and then choose Subscribe to topic.
25
AWS IoT Developer Guide
View Device MQTT Messages
with the AWS IoT MQTT Client
Choosing Subscribe to topic above, results in the topic my/topic appearing in the Subscriptions
column.
• On the MQTT client page, in the Publish section, in the Specify a topic and a message to publish…
field, type my/topic.
Note
We do not recommend using personally identifiable information in topic names.
{
"message": "Hello, world",
"clientType": "MQTT client"
}
26
AWS IoT Developer Guide
Configure and Test Rules
Choose Publish to topic. You should see the message in the AWS IoT MQTT client (choose my/topic
in the Subscription column to see the message).
27
AWS IoT Developer Guide
Create an SNS Topic
4. Type a topic name and a display name, and then choose Create topic.
28
AWS IoT Developer Guide
Subscribe to an Amazon SNS Topic
Note
We do not recommend using personally identifiable information in Amazon SNS topic
names.
5. Make a note of the ARN for the topic you just created.
1. In the Amazon SNS console, select the check box next to the topic you just created. From the
Actions menu, choose Subscribe to topic.
In the Endpoint field, type the phone number of an SMS-enabled cell phone, and then choose
Create subscription.
Note
Enter the phone number using numbers and dashes only.
29
AWS IoT Developer Guide
Create a Rule
The Amazon SNS console will display the following message, but you may not receive a confirmation
message.
Create a Rule
AWS IoT rules consist of a topic filter, a rule action, and, in most cases, an IAM role. Messages published
on topics that match the topic filter trigger the rule. The rule action defines which action to take when
the rule is triggered. The IAM role contains one or more IAM policies that determine which AWS services
the rule can access. You can create multiple rules that listen on a single topic. Likewise, you can create
a single rule that is triggered by multiple topics. The AWS IoT rules engine continuously processes
messages published on topics that match the topic filters defined in the rules.
In this example, you will create a rule that uses Amazon SNS to send an SMS notification to a cell phone
number.
1. In the AWS IoT console, in the left navigation pane, choose Act.
30
AWS IoT Developer Guide
Create a Rule
3. On the Create a rule page, in the Name field, type a name for your rule.
Note
We do not recommended using personally identifiable information in your rule name.
4. Scroll down to Rule query statement. Choose the latest version from the Using SQL version drop-
down list. In the Rule query statement field, type SELECT * FROM 'my/topic'.
SELECT * specifies that you want to send the entire MQTT message that triggered the rule. FROM
'my/topic' is the topic filter. The rules engine uses the topic filter to determine which rules to
trigger when an MQTT message is received.
31
AWS IoT Developer Guide
Create a Rule
6. On the Select an action page, select Send a message as an SNS push notification, and then choose
Configure action.
32
AWS IoT Developer Guide
Create a Rule
7. On the Configure action page, under SNS target, choose Select to expand the SNS topic drop down.
Then choose Select next to the Amazon SNS topic you created earlier. Under Message format select
JSON.
8. Now give AWS IoT permission to publish to the Amazon SNS topic on your behalf when the rule is
triggered. Choose Create a new role. Enter a name for your new role in the IAM role name field.
After you have entered the name, choose Create a new role.
33
AWS IoT Developer Guide
Create a Rule
9. Under IAM role name, choose Update role to apply the permissions to the newly created role,
choose the newly created role, and choose Add action.
34
AWS IoT Developer Guide
Create a Rule
35
AWS IoT Developer Guide
Test the Amazon SNS Rule
For more information about creating rules, see AWS IoT Rules .
1. In the AWS IoT console, in the left navigation pane, choose Test.
2. On the MQTT client page, in the Publish section, in the Specify a topic and a message to publish…
field, type my/topic or the topic you used in the rule. In the message payload section, type the
following JSON:
{
"default": "Hello, from AWS IoT console",
"message": "Hello, from AWS IoT console"
}
3. Choose Publish to topic. You should receive an Amazon SNS message on your cell phone.
Congratulations! You have successfully created and configured a rule that sends data received from a
device to an Amazon SNS topic.
36
AWS IoT Developer Guide
Next Steps
Next Steps
For more information about AWS IoT rules, see AWS IoT Rule Tutorials (p. 50) and AWS IoT
Rules (p. 243).
This topic shows how to create and deploy a sample job to a device. It walks you through the steps
required to create a job and track its events on a device that is configured to communicate with AWS IoT.
These instructions assume that you're using a Raspberry Pi, but they could be adapted for other Linux-
based devices.
1. Complete the Connecting Your Raspberry Pi tutorial. When you're done, you'll have an AWS IoT
thing registered in your AWS account named MyRaspberryPi. You'll also have fully configured
security certificates on your device.
2. Complete the Using the AWS IoT Device SDK for JavaScript tutorial. When you're done, your device
will be connected to AWS IoT, and you'll be able to run the sample code that comes with the AWS
IoT Device SDK for JavaScript.
You can run this sample by using the following command. Use the REST endpoint of your Raspberry Pi as
the value of the -H parameter.
If you've created a configuration file that contains the thing name and the host endpoint (the REST
endpoint of your device), you can use the following command.
37
AWS IoT Developer Guide
Create a Job Document
{
"operation":"customJob",
"otherInfo":"someValue"
}
For more sample job documents, see the documentation for the jobs-agent.js sample.
Create a Job
Now you're ready to create a job that delivers the job document to all of the devices that you specify. To
create a job, you can use the AWS IoT console, the AWS IoT SDK, or the AWS IoT CLI.
The following example shows how to create a job by using the AWS IoT CLI.
If you store your job document in Amazon Simple Storage Service, use the –document-source
parameter instead of the –document parameter to specify the Amazon S3 URL for the job document.
If you prefer to use the AWS IoT console, follow these steps to create a job:
1. Upload the job document to an Amazon S3 bucket. For information about uploading documents to
Amazon S3, see How Do I Upload Files and Folders to an S3 Bucket? in the Amazon Simple Storage
Service Console User Guide.
2. In the AWS IoT console, choose Manage, and then choose Jobs.
3. Choose Create a job.
38
AWS IoT Developer Guide
Create a Job
39
AWS IoT Developer Guide
Create a Job
40
AWS IoT Developer Guide
Create a Job
Under Select devices to update, select the device that you connected to AWS IoT.
41
AWS IoT Developer Guide
Create a Job
42
AWS IoT Developer Guide
Create a Job
6. Scroll down to Add a job file and choose the job document file that you uploaded to Amazon S3.
Under Job type, select Your job will complete after deploying to the selected devices/groups
(snapshot). (The other option, Your job will continue deploying to any devices added to the
selected groups (continuous), is for deploying a job to groups of devices as devices are added to
each group.) Leave the Job executions rollout configuration unchanged. Choose Create.
43
AWS IoT Developer Guide
Create a Job
44
AWS IoT Developer Guide
Execute the Job on a Device
For more information about creating and deploying jobs, see the AWS IoT Jobs documentation.
When you refresh the Jobs page, you can see that your job has successfully completed.
45
AWS IoT Developer Guide
Tracking Job Progress with Job and Job Execution Events
This is a helpful way to alert users, system administrators, or other members of your system that a job
is complete or that a job execution has changed its status. For example, you can alert a user about a
firmware update on a device or inform a system administrator about an issue in their device fleet that
needs to be investigated and resolved.
Job events for the job in this example are published to the following topics when the job is completed or
canceled.
$aws/events/job/example-job-01/completed
$aws/events/job/example-job-01/canceled
Job execution events for the job in this example are sent to the following topics when the job execution
reaches one of the possible final statuses.
$aws/events/jobExecution/example-job-01/succeeded
$aws/events/jobExecution/example-job-01/failed
$aws/events/jobExecution/example-job-01/rejected
$aws/events/jobExecution/example-job-01/canceled
$aws/events/jobExecution/example-job-01/removed
46
AWS IoT Developer Guide
Tracking Job Progress with Job and Job Execution Events
When the job execution on your device succeeds, AWS IoT publishes a JobExecutionsucceeded event.
You can see this event by navigating to the AWS IoT Test page and subscribing to the $aws/events/
jobExecution/example-job-01/succeeded topic in the MQTT client.
The following message appears when the job execution for your device has successfully completed.
47
AWS IoT Developer Guide
Tracking Job Progress with Job and Job Execution Events
AWS IoT also publishes a completed job event. You can see this event by subscribing to the $aws/
events/job/example-job-01/completed topic in the MQTT client.
48
AWS IoT Developer Guide
Tracking Job Progress with Job and Job Execution Events
49
AWS IoT Developer Guide
Creating an Amazon DynamoDB Rule
The scenario in this tutorial is a greenhouse with rows of plants. Each plant has a moisture sensor. At a
predetermined interval, the moisture sensor sends its data to AWS IoT. The AWS IoT rules engine receives
this data and writes it to a DynamoDB table. You create a rule to write data to DynamoDB and emulate
the sensors using the AWS IoT MQTT client.
An AWS IoT rule consists of an SQL SELECT statement, a topic filter, and a rule action. Devices send
information to AWS IoT by publishing messages to MQTT topics. The SQL SELECT statement allows you
to extract data from an incoming MQTT message. The topic filter of an AWS IoT rule specifies one or
more MQTT topics. The rule is triggered when an MQTT message is received on a topic that matches
the topic filter. Rule actions allow you to take the information extracted from an MQTT message and
send it to another AWS service. Rule actions are defined for AWS services like Amazon DynamoDB, AWS
Lambda, Amazon SNS, and Amazon S3. By using a Lambda rule, you can call other AWS or third-party
web services. For a complete list of rule actions, see AWS IoT Rule Actions (p. 249).
In these tutorials, we assume that you're using the AWS IoT MQTT client and that you are using my/
greenhouse as the topic filter in the rules.
You can also use your own device, but you must know on which MQTT topic your device publishes so you
can specify it as the topic filter in the rule. For more information, see AWS IoT Rules (p. 243).
50
AWS IoT Developer Guide
Creating an Amazon DynamoDB Rule
3. On the Create a rule page, enter a name and description for your rule.
Note
We do not recommend the use of personally identifiable information in your rule names or
descriptions.
4. Under Rule query statement, choose the latest version from the Using SQL version list. For Rule
query statement, enter:
("SELECT *" specifies that you want to send the entire MQTT message that triggered the rule.
"FROM 'my/greenhouse'" tells the rules engine to trigger this rule when an MQTT message is
received whose topic matches this topic filter. Choose Add action.
51
AWS IoT Developer Guide
Creating an Amazon DynamoDB Rule
5. On the Select an action page, choose Insert a message into a DynamoDB table, and then choose
Configure action.
52
AWS IoT Developer Guide
Creating an Amazon DynamoDB Rule
53
AWS IoT Developer Guide
Creating an Amazon DynamoDB Rule
54
AWS IoT Developer Guide
Creating an Amazon DynamoDB Rule
8. On the Create DynamoDB table page, enter a name in Table name. In Partition key, enter Row.
Select Add sort key, and then enter PositionInRow in the Sort key field. Row represents a row
of plants in a greenhouse. PositionInRow represents the position of a plant in the row. Choose
String for both the partition and sort keys, and then choose Create. It takes a few seconds to create
your DynamoDB table. Close the browser tab where the Amazon DynamoDB console is open. If you
don't close the tab, your DynamoDB table is not displayed in the Table name list on the Configure
action page of the AWS IoT console.
9. On the Configure action page, choose your new table from the Table name list. In Partition key
value, enter ${row}. This instructs the rule to take the value of the row attribute from the MQTT
55
AWS IoT Developer Guide
Creating an Amazon DynamoDB Rule
message and write it into the Row column in the DynamoDB table. In Sort key value, enter ${row}.
This writes the value of the index attribute into the PositionInRow column. Leave Write message
data to this column blank. By default, the entire message is written to a column in the table named
Payload. Choose Create a new role.
10. In Create a new role, enter a unique name in Name, and then choose Create role.
56
AWS IoT Developer Guide
Creating an Amazon DynamoDB Rule
57
AWS IoT Developer Guide
Creating an Amazon DynamoDB Rule
58
AWS IoT Developer Guide
Creating an Amazon DynamoDB Rule
59
AWS IoT Developer Guide
Testing an Amazon DynamoDB Rule
{
"row" : "0",
"index" : "0",
"moisture" : "75"
}
60
AWS IoT Developer Guide
Creating an AWS Lambda Rule
Select the GreenhouseTable and then choose the Items tab. Your data is displayed on the Items tab.
In this tutorial, you use the AWS IoT MQTT client to send a message that triggers the rule.
61
AWS IoT Developer Guide
Create a Lambda Function
2. On the Create function page, choose Use a blueprint. In the Blueprints filter field, enter hello-
world, and then press Enter. Choose the hello-world-python blueprint, and then choose
Configure.
62
AWS IoT Developer Guide
Create a Lambda Function
4. From Execution Role, choose Create a new role from AWS policy templates. Under Role name,
enter a name for the role. From Policy templates, choose Amazon SNS publish policy. Click outside
of the drop-down menu to dismiss it.
63
AWS IoT Developer Guide
Create a Lambda Function
64
AWS IoT Developer Guide
Create a Lambda Function
6. In the Lambda console, choose the name of your Lambda function. Information about your Lambda
function is displayed. Scroll down to the Function code section and replace the existing code with
the following:
import json
import boto3
print('Loading function')
# Print the parsed JSON message to the console; you can view this text in the
Monitoring tab in the Lambda console or in the CloudWatch Logs console
print('Received event: ', eventText)
print(response)
Note
Replace the value of TopicArn with the ARN of the Amazon SNS topic you created earlier.
Choose Save.
65
AWS IoT Developer Guide
Test Your Lambda Function
2. On Configure test event, enter a name for your test event and replace the message JSON with the
following:
{
"message" : "Hello, world"
}
Choose Create.
66
AWS IoT Developer Guide
Test Your Lambda Function
3. In the upper right of the Lambda function detail page, choose Test to test your Lambda function
with the message you specified in the test event.
67
AWS IoT Developer Guide
Create a Lambda Rule
4. Under your Lambda function code, on the Execution result tab, you see the output from the
Lambda function.
1. Browse to the AWS IoT console, and from the navigation pane, choose Act.
68
AWS IoT Developer Guide
Create a Lambda Rule
69
AWS IoT Developer Guide
Create a Lambda Rule
6. Under Select an action, choose Send a message to a Lambda function, and then choose Configure
action.
70
AWS IoT Developer Guide
Create a Lambda Rule
71
AWS IoT Developer Guide
Create a Lambda Rule
72
AWS IoT Developer Guide
Create a Lambda Rule
10. On the Create a rule page, in Error action, choose Add action.
11. On the Set an action as error action page, choose Republish a message to an AWS IoT topic, and
then choose Configure action.
73
AWS IoT Developer Guide
Create a Lambda Rule
74
AWS IoT Developer Guide
Create a Lambda Rule
13. Under Choose or create a role to grant AWS IoT access to perform this action, choose Create Role.
14. In Create a new role, enter a name for the role, and then choose Create role.
75
AWS IoT Developer Guide
Create a Lambda Rule
76
AWS IoT Developer Guide
Create a Lambda Rule
77
AWS IoT Developer Guide
Test Your Lambda Rule
2. In the MQTT client, under Subscription topic, enter lambda/error, and then choose Subscribe to
topic.
3. Under Publish, enter my/lambda/topic, and then choose Publish to topic to publish the default
JSON message.
78
AWS IoT Developer Guide
Troubleshooting Lambda Rules
Publishing this message should trigger the rule and call your Lambda function. Your Lambda function
pushes an Amazon SNS message to a phone number subscribed to your Amazon SNS topic. If you do not
get a text message, in the MQTT client, check to see if any messages were published to lambda/error.
79
AWS IoT Developer Guide
Creating an Amazon SNS Rule
6. The log stream displays the logs written by your Lambda function.
80
AWS IoT Developer Guide
Creating an Amazon SNS Rule
In this tutorial, you create a rule that sends the name of the AWS IoT thing that triggered the rule to all
subscribers of an Amazon SNS topic.
81
AWS IoT Developer Guide
Creating an Amazon SNS Rule
(The topic filter following the "FROM" specifies the topics that trigger the rule's action when a
message is published to them. The plus sign (+) used in the topic filter is a wildcard character that
matches any thing name. The "topic(3)" attribute following "SELECT" appends the thing name,
which is the third topic field, onto the message contents.)
6. Under Select an action, choose Send a message as an SNS push notification, and then choose
Configure action.
82
AWS IoT Developer Guide
Creating an Amazon SNS Rule
83
AWS IoT Developer Guide
Creating an Amazon SNS Rule
8. Enter a topic name in the dialog box that opens, and then choose Create.
9. On the Configure action page, for SNS target, choose the SNS topic you just created. For Message
format, choose JSON. Under Choose or create a role to grant AWS IoT access to perform this
action, choose Create Role.
84
AWS IoT Developer Guide
Creating an Amazon SNS Rule
10. Enter a name for the role, and then choose Create role.
85
AWS IoT Developer Guide
Creating an Amazon SNS Rule
86
AWS IoT Developer Guide
Creating an Amazon SNS Rule
87
AWS IoT Developer Guide
Creating an Amazon SNS Rule
To test the rule, add a subscription to the SNS topic you created, and update the shadow of any AWS IoT
thing.
You can use the AWS IoT console to find a thing, open its detail page, and change the device's
shadow. When the Device Shadow service is notified of the change, it publishes a message on $aws/
things/MySNSThing/shadow/update/accepted. Your rule is triggered and all subscribers to your
SNS topic receive a message that contains your thing's name.
88
AWS IoT Developer Guide
Prerequisites
These tutorials provide step-by-step instructions for connecting your Raspberry Pi to the Message Broker
for AWS IoT (p. 233), using with the AWS IoT Device SDK for Embedded C and the AWS IoT Device SDK
for JavaScript. After following these instructions, you can connect to the AWS IoT platform and run the
sample applications included with the AWS IoT Device SDKs.
Contents
• Prerequisites (p. 89)
• Create an AWS IoT Thing for Your Raspberry Pi (p. 89)
• Using the AWS IoT Embedded C SDK (p. 102)
• Using the AWS IoT Device SDK for JavaScript (p. 105)
Prerequisites
This tutorial requires the following:
1. On your Raspberry Pi, open a web browser and go to the AWS IoT console. You may be prompted to
sign in.
2. In the AWS IoT console, you see the Monitor page. In the navigation pane, choose Manage.
89
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
3. Choose Create.
90
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
4. On the Creating AWS IoT things page, choose Create a single thing.
91
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
5. On the Add your device to the device registry page, enter MyRaspberryPi for the device Name.
Leave the default values for all the other fields, and then choose Next.
92
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
6. On the Add a certificate for your thing page, choose Create certificate. This generates an X.509
certificate and key pair.
93
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
7. On the Certificate created! page, download your public and private keys, certificate, and root
certificate authority (CA). Save them on your Raspbery Pi, you will copy them to a different directory
later on in this tutorial. Choose Activate to activate the X.509 certificate, and then choose Attach a
policy.
94
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
8. On the Add a policy for your thing page, choose Register Thing.
After you register your thing, you will need to create and attach a new policy to the certificate.
95
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
9. On the AWS IoT console, in the navigation pane, choose Secure and Policies. In the Policies page,
choose Create a policy.
96
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
11. In the AWS IoT console, choose Manage and Things. On the Things page, choose MyRaspberryPi.
97
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
12. On the thing's Details page, in the left navigation pane, choose Interact.
98
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
13. Make a note of the REST API endpoint. You will need it to connect to AWS IoT. In the navigation
pane, choose Security.
99
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
100
AWS IoT Developer Guide
Create an AWS IoT Thing for Your Raspberry Pi
101
AWS IoT Developer Guide
Using the AWS IoT Embedded C SDK
16. On the Attach policies to certificate(s) page, choose the policy you created, and then choose
Attach.
Copy the contents of the mbed TLS directory into the aws-iot-device-sdk-embedded-C/external_libs/
mbedTLS directory.
1. Follow the instructions on Getting Started with AWS IoT (p. 5) to create an IoT thing, certificate,
private key, and IoT policy.
102
AWS IoT Developer Guide
Sample App Configuration
2. Copy your certificate, private key, and root CA certificate into the aws-iot-device-sdk-
embedded-C/certs directory.
Note
Device and root CA certificates are subject to expiration or revocation. If this should occur,
you must copy a new CA certificate or private key and device certificate onto your device.
3. Navigate to the aws-iot-device-sdk-embedded-C/samples/linux/
subscribe_publish_sample directory. You must configure your personal AWS IoT endpoint,
private key, and certificate. The personal endpoint is the REST API endpoint you noted earlier. If you
don't remember the endpoint and you have access to a machine with the AWS CLI installed, you can
use the aws iot describe-endpoint command to find your personal endpoint URL. Or, go to the AWS
IoT console:
a. Choose Registry.
b. Choose Things.
c. choose the thing that represents your Raspberry Pi. On the Details page for the thing, in the left
navigation pane, choose Interact.
d. Copy everything, including ".com", from REST API endpoint.
4. Open the aws_iot_config.h file and, in the //Get from console section, update the values for
the following:
AWS_IOT_MQTT_HOST
103
AWS IoT Developer Guide
Run Sample Applications
AWS_IOT_ROOT_CA_FILENAME
Your certificate.
AWS_IOT_PRIVATE_KEY_FILENAME
For example:
make -f Makefile
2. Run the subscribe_publish_sample_app. You should see output similar to the following:
104
AWS IoT Developer Guide
Using the AWS IoT Device SDK for JavaScript
Your Raspberry Pi is now connected to AWS IoT using the AWS IoT Device SDK for Embedded C.
1. To add the Node repository, open a terminal and run the following command:
node -v
and
npm -v
If a version number is displayed by these commands, node and npm are installed correctly.
105
AWS IoT Developer Guide
Install the AWS IoT Device SDK for JavaScript
mkdir deviceSDK
After the installation is complete, you should find a node_modules directory in your ~/deviceSDK
directory.
To run the AWS IoT Device SDK for JavaScript samples, you need the following information:
You can find the region you are using by browsing to the AWS IoT console and looking at the URL.
The region appears immediately after the https:// in the URL. For example:
https://us-west-2.console.aws.amazon.com/iot/home?region=us-west-2#/
dashboard
The AWS Region also appears after the ? in the URL. For more information, see AWS Regions and
Endpoints. For region information specific to AWS IoT, see AWS IoT Regions and Endpoints.
A client ID
The fully-qualified path to your private key on your Raspberry Pi. This is the key that is generated
when you registered your Raspberry Pi with AWS IoT.
Your AWS IoT X.509 certificate
The fully-qualified path to your AWS IoT certificate on your Raspberry Pi. This is the certifiate that is
generated when you registered your Raspberry Pi with AWS IoT.
The STS Amazon root CA
You can find your endpoint by running the describe-endpoint CLI command:
You can also find your endpoint by browsing to the AWS IoT console, choosing the IoT thing for your
Raspberry Pi, and then choosing Interact. Your endpoint is displayed under HTTPS and Update your
Device Shadow using this Rest API endpoint.
106
AWS IoT Developer Guide
Run the Sample Applications
This is the name you specifed when you registered your Raspberry Pi with AWS IoT.
Your Raspberry Pi is now connected to AWS IoT using the AWS IoT SDK for JavaScript.
If the sample instances are running correctly, the output from the instance running in mode 1 should
look like this:
The output from the instance running in mode 2 should look like this:
107
AWS IoT Developer Guide
Run the Sample Applications
...
If the sample does not run correctly, try adding the -d option when running the sample to display debug
information.
108
AWS IoT Developer Guide
AWS IoT Plant Watering Sample
Each tutorial will provide a list of prerequisites, including any specific hardware needs. Where possible,
the tutorials will provide alternatives if you don't have all of the needed hardware.
To get real soil moisture readings, this sample uses hardware such as a Raspberry Pi and a soil moisture
sensor kit, and a common houseplant. If you don’t have this hardware or the houseplant, you can
simulate the soil moisture readings by generating random readings from your development computer
instead. This sample shows you both approaches.
Contents
• Module 1: Setting Up AWS IoT and Sending Data with Your Development Computer (p. 109)
• Prerequisites for Steps 1–5 (p. 110)
• Step 1: Create the AWS IoT Policy (p. 110)
• Step 2: Create the Thing (p. 112)
• Step 3: Send and Receive Test Data for the Thing (p. 115)
• Step 4: Set Up Email Alerts for Low Moisture Readings (p. 122)
• Step 5: Simulate Random Moisture Levels (p. 126)
• Module 2: Sending Data with the Raspberry Pi (p. 129)
• Prerequisites for Steps 6–12 (p. 129)
• Prerequisites for Steps 6–12 (p. 129)
• Step 6: Begin Preparing the microSDHC Card (p. 131)
• Step 7: Download Raspbian to the microSDHC Card (p. 132)
• Step 8: Finish Preparing the microSDHC card (p. 134)
• Step 9: Connect to the Raspberry Pi and Set Up Raspbian (p. 135)
• Step 10: Set Up the Soil Moisture Sensor Kit (p. 139)
• Step 11: Capture Data from the Soil Moisture Sensor Kit (p. 145)
• Step 12: Send Soil Moisture Sensor Readings to AWS IoT (p. 145)
• Cleaning Up (p. 148)
• Next Steps (p. 152)
109
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
Pi. You then set up AWS IoT to send email alerts through Amazon Simple Notification Service (Amazon
SNS) that are based on those readings.
Finally, you use your development computer to simulate soil moisture readings by generating random
data. You then push those readings into AWS IoT . When the readings get too low, Amazon SNS
automatically sends an email alert.
In Module 2 (p. 129), you can generate real soil moisture readings with a Raspberry Pi and then push
those real readings into AWS IoT .
• An AWS account
• An IAM administrator user in the AWS account. (You can use the AWS account root user instead of an
IAM administrator user. However, we don’t recommend it.)
• A desktop or laptop development computer to work with the AWS IoT console from a web browser,
and to push simulated soil moisture readings into AWS IoT . This computer can be running a Windows,
macOS, Linux, or Unix operating system. (This sample was tested with a laptop computer running
Windows 10 Enterprise edition.)
X.509 certificates are used to authenticate devices with AWS IoT . AWS IoT policies are used to authorize
devices to perform AWS IoT operations, such as subscribing or publishing to MQTT topics.
If you use the Raspberry Pi hardware for this sample, the Raspberry Pi presents its certificate when
sending messages to AWS IoT . If you use your development computer to simulate the soil moisture
readings, your computer presents its certificate when sending messages to AWS IoT instead.
1. Use your operating system’s web browser to sign in to the AWS Management Console, at https://
aws.amazon.com.
Note
For this sample walkthrough, we recommend that you sign in using the credentials of an
IAM administrator user in your AWS account.
2. On the AWS navigation bar, choose the AWS Region where you want to create the AWS IoT resources
in your AWS account. This sample was tested with the US East (N. Virginia) Region.
3. Open the AWS IoT console. To do this, on the AWS navigation bar, choose Services. In the Find a
service by name or feature box, enter IoT Core, and then press Enter.
4. In the AWS IoT console, if a Get started button appears, choose it.
5. In the service navigation pane, expand Secure, and then choose Policies.
110
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
6.
7. If a You don’t have any policies yet dialog box appears, choose Create a policy. Otherwise, choose
Create.
8. Provide a Name that represents this policy, for example PlantWateringPolicy.
Note
If you choose to use a different name, be sure to substitute it throughout this sample.
9. For Action, enter iot:*.
10. For Resource ARN, replace the suggested value with an asterisk (*).
11. For Effect, choose Allow.
12. Choose Create.
111
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
Devices connected to AWS IoT are represented by things in the AWS IoT registry. The registry enables
you to keep a record of all of the devices that are connected to your AWS account in AWS IoT .
1. With the AWS IoT console open, in the service navigation pane, choose Manage.
2. If an Introducing AWS IoT Device Management dialog box is displayed, choose Show me later, or
press Esc.
3. In the service navigation pane, with Manage expanded, choose Things.
112
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
4. If a You don’t have any things yet dialog box is displayed, choose Register a thing. Otherwise,
choose Create.
5. On the Creating AWS IoT things page, for Register a single AWS IoT thing, choose Create a single
thing.
113
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
6. On the Add your device to the device registry page, provide a Name that represents your Raspberry
Pi (or your development computer as a device simulator), for example, MyRPi.
Note
If you choose to use a different name, be sure to substitute it throughout this sample.
7. Leave the rest of this page unchanged, and then choose Next.
8. On the Add a certificate for your thing page, choose Create certificate.
9. For A certificate for this thing, choose Download. Then follow your web browser’s onscreen
directions to save the file ending in certificate.pem.crt.txt to your local development
computer.
114
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
Note
Although the dialog box shows a file ending in cert.pem, the file that you download ends
in certificate.pem.crt.txt.
10. Repeat the previous step in this section for A public key, A private key, and A root CA for AWS IoT.
Save the files ending in public.pem.key, private.pem.key, and .pem, respectively, to your
development computer.
When you choose the Download link next to A root CA for AWS IoT, the Server
Authentication (p. 181) section of the AWS IoT Developer Guide is displayed. From there, to get
the root CA for AWS IoT , click the Amazon Root CA 1 link in that section, which downloads the RSA
2048 bit key for the Amazon Trust Services endpoint.
Important
You can download the files for A certificate for this thing and A root CA for AWS at any
time. However, this is your only opportunity to download the files for A public key and A
private key for this thing.
11. Choose Activate.
115
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
A device's shadow is a JSON document, stored in AWS IoT , that AWS IoT uses to save and retrieve
current state information for a device. The Device Shadow Service for AWS IoT (p. 321) maintains a
shadow for each device you connect to AWS IoT . You can use the shadow to get and set the state of a
device, regardless of whether the device is connected to the internet.
2. Choose Interact.
3. For MQTT, make a note of the value for each of the following MQTT topics, which enable you to set
and get updates to the shadow:
116
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
117
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
7. For Subscription topic, enter the MQTT topic value that you noted in step 3 of this procedure for
Update to this device shadow (for example, $aws/things/MyRPi/shadow/update), and then
choose Subscribe to topic.
Important
If you named your thing something other than MyRPi, be sure to substitute your thing’s
name for MyRPi in the preceding MQTT topic name and other MQTT topic names
throughout Step 3. Otherwise, the subscribed MQTT topic won’t display any activity.
8. Choose Subscribe to a topic.
118
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
9. Repeat steps 7 and 8 in this procedure for the MQTT topic values that you noted for Get this device
shadow (for example, $aws/things/MyRPi/shadow/get) and Get this device shadow accepted
(for example, $aws/things/MyRPi/shadow/get/accepted).
10. Now push some test data into the shadow. To do this, in the MQTT client navigation pane, choose
the MQTT topic value for Update to this device shadow (for example, $aws/things/MyRPi/
shadow/update). You might need to pause your mouse over a truncated topic value to see its full
value.
11. 11. In the message payload area, replace the current payload with the following payload:
{
"state": {
"desired": {
"welcome": null
},
"reported": {
"welcome": null,
"moisture": "low"
}
}
}
The preceding payload removes the default welcome value for the shadow and adds a moisture
value with the value low to the shadow.
12. Choose Publish to topic.
119
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
13. To get that data from the shadow, choose the MQTT topic value for Get this device shadow (for
example, $aws/things/MyRPi/shadow/get).
14. In the message payload area, replace the current payload with the following payload:
{}
You specify empty curly braces here because the Get this thing shadow MQTT topic takes only an
empty payload.
15. Choose Publish to topic.
A green dot is displayed next to the MQTT value for Get this device shadow accepted. This means
that there is new information displayed for that MQTT topic.
120
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
16. Choose the MQTT topic value for Get this device shadow accepted (for example, $aws/things/
MyRPi/shadow/get/accepted), and note the output, for example:
{
"state": {
"reported": {
"moisture": "low"
}
},
"metadata": {
"reported": {
"moisture": {
"timestamp": 1539272338
}
}
},
"version": 19,
"timestamp": 1539272436
}
In the preceding output, the moisture value that was reported earlier is shown, along with the time
each corresponding event happened and the current shadow document version.
17. Make another update to the shadow. To do this, in the MQTT client navigation pane, choose the
MQTT topic value for Update to this device shadow (for example, $aws/things/MyRPi/shadow/
update).
18. In the message payload area, replace the current payload with the following payload to change the
current moisture value:
{
"state": {
"reported": {
"moisture": "okay"
}
}
}
{}
22. Choose Publish to topic. A green dot is displayed next to the MQTT value for Get this device
shadow accepted.
23. Choose the MQTT topic value for Get this device shadow accepted (for example, $aws/things/
MyRPi/shadow/get/accepted), and note the output, for example:
{
"state": {
"reported": {
"moisture": "okay"
121
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
}
},
"metadata": {
"reported": {
"moisture": {
"timestamp": 1539272823
}
}
},
"version": 20,
"timestamp": 1539272827
}
In the preceding output, the moisture value that was just changed is shown, along with the time
that each corresponding event happened and the new current shadow document version.
1. Create an AWS IoT rule to trigger the email alert through Amazon SNS. To do this, with the AWS IoT
console open, in the service navigation pane, choose Act.
2. If a You don’t have any rules yet dialog box appears, choose Create a rule. Otherwise, choose
Create.
3. On the Create a rule page, enter a Name for this rule, for example,
MyRPiLowMoistureAlertRule. If you use a different name, be sure to substitute it throughout
this sample.
4. For Description, provide a meaningful description for this rule, for example, Sends an alert
whenever soil moisture level readings are too low.
122
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
5. For Rule query statement, with Using SQL version set to 2016-03-23, in the Rule query statement
box, enter the following AWS IoT SQL statement as a single line, without any line breaks:
This statement triggers the rule whenever the moisture value is reported as low for the specified
MQTT topic.
Important
If you named your thing something other than MyRPi, be sure to substitute your thing’s
name in the preceding AWS IoT SQL statement. Otherwise, the rule might never be
triggered.
6. For Set one or more actions, choose Add action.
7. On the Select an action page, choose Send a message as an SNS push notification.
123
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
124
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
125
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
20. In the Create subscription dialog box, for Protocol, choose Email.
21. For Endpoint, enter your email address.
22. Choose Create subscription.
23. Watch your inbox for a subscription confirmation email titled AWS Notification – Subscription
Confirmation from [email protected]. When it arrives, open it, and then click the
Confirm subscription link. After you click the link, a confirmation page is displayed in your web
browser. You can close this confirmation page.
Important
Until you confirm this subscription, you won’t receive any email alerts from this Amazon
SNS topic, even though AWS IoT might be sending email alerts to it.
1. Make sure that your development computer has Python and pip installed.
pip is included with Python versions 3.4 and later. To check your installed version of Python, run the
command python --version from the command prompt running in Admin mode for Windows, or
126
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
from a terminal session running in macOS, Linux, or Unix. To check whether pip is also installed, run
the command pip --version.
2. Use pip to install the AWS IoT Device SDK for Python on your development computer. To do this, run
the command pip install AWSIoTPythonSDK.
3. 3. Use a text editor to create a new file on your development computer with the following code:
127
AWS IoT Developer Guide
Module 1: Setting Up AWS IoT and Sending
Data with Your Development Computer
if moisture:
myDeviceShadow.shadowUpdate(
'{"state":{"reported":{"moisture":"okay"}}}',
myShadowUpdateCallback, 5)
else:
myDeviceShadow.shadowUpdate(
'{"state":{"reported":{"moisture":"low"}}}',
myShadowUpdateCallback, 5)
• AmazonRootCA1.pem with the name of the root CA for AWS IoT, which you saved earlier to your
development computer.
• yourkeyid-private.pem.key with the name of the private key for your device in AWS IoT,
which you saved earlier to your development computer.
• yourkeyid-certificate.pem.crt.txt with the name of the root certificate file for your
device in AWS IoT, which you saved earlier to your development computer.
• The 60 in time.sleep(60) with the number of seconds to wait for each new random simulated
reading to be generated. The lower the value that you use for this number, the more frequently
you might get email alerts.
4. Save the file with the extension .py, for example, moisture.py, in the same directory where
you saved your root CA for AWS IoT, the private key file for your device in AWS IoT, and the root
certificate file for your device in AWS IoT. If you choose to use a different name for the .py file, be
sure to substitute it throughout this sample.
128
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
5. From the command prompt running in Admin mode for Windows, or from a terminal session in
macOS, Linux, or Unix, switch to the directory that contains the moisture.py file. Then run the
command python moisture.py for Python to start running the moisture.py script.
Every 60 seconds, the script generates a random True or False value. If the value is True, Python
sends a "moisture okay" reading to AWS IoT. If the value is False, Python sends a low moisture
reading to AWS IoT. Whenever AWS IoT receives a low moisture reading, it triggers a rule that sends
an alert to your email address through Amazon SNS.
6. 6. When you are done, press Ctrl+C to stop running the script.
If you don’t have a Raspberry Pi, you have reached the end of this sample walkthrough, and you can
skip ahead to Cleaning Up (p. 148). Otherwise, continue to Module 2: Sending Data with the Raspberry
Pi (p. 129) to begin preparing your Raspberry Pi.
129
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
• A Raspberry Pi 3 micro USB adapter power supply with at least 5V 2.5A. This sample was tested with a
5V 2.5A power supply.
• A micro SD card with at least 16 GB. This sample was tested with a microSDHC 16 GB card.
• A desktop or laptop development computer with either a slot for the micro SD card or a micro SD card
reader that can connect to the computer. This sample was tested with a laptop running Windows 10
Enterprise that has a built-in SD card reader.
• A network to connect the Raspberry Pi to AWS IoT and, optionally, to connect your development
computer to the Raspberry Pi. This setup can be either a wireless network, or a physical network router
that you can connect to with Ethernet cables. The Raspberry Pi 3 Model B provides both built-in Wi-Fi
and an Ethernet port. This sample was tested with a wireless network.
• If you don’t want to access the Raspberry Pi from your development computer, you need to connect
the Raspberry Pi to a separate keyboard, mouse, and monitor. The Raspberry Pi 3 Model B provides
four USB ports and a full-size HDMI port. This sample was tested with a USB keyboard, a USB mouse,
and a monitor with HDMI input.
• A soil moisture sensor kit compatible with Raspberry Pi. This includes the sensor module (the “probe”)
and a microcontroller. You also need two female-to-female connection wires from the sensor module
to the microcontroller, and three female-to-female connection wires from the microcontroller to the
Raspberry Pi’s onboard GPIO pins. This sample was tested with a Gikfun soil moisture sensor.
130
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
• A glass of water.
• A common houseplant.
If you already have a Raspberry Pi with an operating system such as Raspbian installed, then connect to
your Raspberry Pi and skip ahead to Step 10: Set Up the Soil Moisture Sensor Kit (p. 139).
Insert a blank microSDHC card into your desktop or laptop computer. Use an SD card formatting app or
utility to format the SD card. For example, if you are using Windows or macOS, complete the following
steps:
131
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
When prompted to continue formatting the microSDHC card, choose Yes. The format operation can
take a while.
132
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
4. Use an image flashing app or utility to flash the .zip file that you just downloaded onto the
microSDHC card. For example, for Windows, macOS, or Linux:
133
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
1. If you plan to connect to the Raspberry Pi from your desktop or laptop computer, create a blank file
named ssh in the root of the microSDHC card. This file allows you to connect to the Raspberry Pi
from an SSH connection tool (such as PuTTY for Windows, the SSH utility in GitBash for Windows, or
the SSH utility for macOS, Linux, or Unix) after the Raspberry Pi boots.
For example, for Windows, in the command prompt running in Admin mode, run the following
command, which creates a blank file named ssh in the root of the microSDHC card. This command
assumes the microSDHC card is connected as drive letter D.
2. If you plan to connect to the Raspberry Pi from your desktop or laptop computer, create a blank file
named wpa_supplicant.conf in the root of the microSDHC card. This file enables the Raspberry
Pi to connect to a wireless network.
For example, for Windows, in the same command prompt, run the following command, which
creates a blank file named wpa_supplicant.conf in the root of the microSDHC card. This
command assumes the microSDHC card is connected as drive letter D.
3. If you created the blank wpa_supplicant.conf file, open a text editor and add the following
content to the wpa_supplicant.conf file. Then save the file.
134
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
network={
ssid="MyWirelessNetworkName"
psk="MyWirelessNetworkPassword"
key_mgmt=WPA-PSK
}
In the preceding content, replace MyWirelessNetworkName with the name of the wireless
network. Replace MyWirelessNetworkPassword with the password for the wireless network. For
more information, see Wireless Connectivity on the Raspberry Pi website.
4. Create a folder in the root of the microSDHC card named deviceSDK.
5. Copy the files that AWS IoT generated for you earlier ending in .certificate.pem.ct.txt (the
root certificate file for your device in AWS IoT), private.pem.key (the private key for your device
in AWS IoT), and .pem (the root CA for AWS IoT) into this new deviceSDK folder.
6. Copy the file named moisture.py from Step 5: Simulate Random Moisture Levels (p. 126) into
this new deviceSDK folder.
7. Eject the microSDHC card from your desktop or laptop computer.
1. Insert the microSDHC card into the Raspberry Pi. The card slot is on the underside of the
motherboard. The card goes in the slot only one way, typically with the writing on the card facing
down.
135
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
2. If you want to access the Raspberry Pi directly, instead of from your development computer, connect
a separate keyboard, mouse, and monitor directly to the Raspberry Pi, for example, by using the USB
and HDMI ports. Although the Raspberry Pi 3 provides Bluetooth connectivity, you won’t be able to
connect via Bluetooth until you boot the Raspberry Pi for the first time.
136
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
3. Insert the prongs of the micro USB adapter power supply into your power source, and then plug the
micro USB end into its slot in the Raspberry Pi.
137
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
The Raspberry Pi red power LED light turns on, the green activity LED light begins flickering, and
the Raspbian operating system automatically boots. If you plan to access the Raspberry Pi from your
development computer, the Raspberry Pi attempts to connect to the wireless network using the
password that you specified earlier in the wpa_supplicant.conf file.
4. If you don’t want to access the Raspberry Pi from your development computer, skip ahead to step 5
in this procedure.
To access the Raspberry Pi from your development computer, get the IP address of the Raspberry
Pi that is now connected to the wireless network. For example, if you can log in to your wireless
network router as an administrator, you should be able to look up the IP address from there.
Otherwise, you could use a utility such as ping or an application such as Nmap for Windows.
After you get the Raspberry Pi’s IP address, connect from your Windows desktop or laptop computer
to the Raspberry Pi using an SSH connection tool such as PuTTY, or the SSH utility in Git Bash for
Windows.
138
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
If you use PuTTY, for Host Name (or IP address), use the format [email protected]. For SSH, use ssh
[email protected]. In either case, pi is the default user name, and X.X.X.X is the Raspberry Pi’s IP address.
When prompted for a password, use the default password, raspberry.
Skip ahead to Step 10: Set Up the Soil Moisture Sensor Kit (p. 139).
5. To access the Raspberry Pi directly instead of from your development computer, turn on your
monitor to the correct input source (for example, HDMI input).
A dialog box might appear, notifying you that SSH is enabled on the Raspberry Pi and the default
password for the user pi has not been changed. You can close this dialog box now, because you get
an opportunity to change this password later in this step.
6. The first time you start the Raspberry Pi, a Welcome to Raspberry Pi dialog box is displayed. Choose
Next.
7. On the Set Country page, choose the Country, Language, and Timezone you want. If you have a US
keyboard, select the US keyboard box.
8. Choose Next.
9. On the Change Password page, enter a new password for the default user pi.
Note
You can complete this procedure whether or not you set a new password, but setting a new
password helps keep your device secure.
10. Choose Next.
11. On the Select WiFi Network page, choose the wireless network to connect to, and then choose
Next.
12. On the Update Software page, choose Next. When the update is complete, choose OK.
13. On the Setup Complete page, choose Reboot, and wait while the Raspberry Pi restarts.
1. Connect two female-to-female connector wires from the two pins on the sensor module to the two
pins on the microcontroller. The connector wires can be connected in either order, but be sure to
connect to the two and only two pins on the one side of the microcontroller, and not to any of the
four pins on the other side of the microcontroller.
139
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
2. Connect three female-to-female connector wires from three specific pins on the microcontroller to
three specific pins on the Raspberry Pi, as follows:
1. Connect from the VCC 5v+ power pin on the microcontroller to one of the 5V power pins on the
Raspberry Pi (for example, pin 2).
2. Connect from the GND ground pin on the microcontroller to one of the GND ground pins on the
Raspberry Pi (for example, pin 6).
3. Connect from the DO digital data pin on the microcontroller to one of the GPIO pins on the
Raspberry Pi (for example, GPIO21 on pin 40).
4. Do not connect anything to the AO analog data pin on the microcontroller.
To see a graphical list of pins and their labels, you can run the pinout command on the
Raspberry Pi, or go to https://pinout.xyz.
140
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
141
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
If the connections are correct, the PWR power LED light is displayed on the microcontroller.
142
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
The LED lights on some microcontrollers might display in green while others might display in red.
Both colors mean the same thing.
3. Place the prongs on the sensor module into a mug of water. If the sensor detects water, the DO
digital data LED light is displayed on the microcontroller. If the DO LED light isn’t displayed, with
the prongs still in the water, use a slotted screwdriver to change the sensitivity of the potentiometer
on the microcontroller until the DO light is displayed. Move the prongs in and out of the water to
check whether the DO light goes on and off, adjusting the potentiometer on the microcontroller as
needed.
143
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
144
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
Step 11: Capture Data from the Soil Moisture Sensor Kit
In this step, you use the Python programming language to run some code on the Raspberry Pi to capture
data from the soil moisture sensor kit.
1. Use an available code editor on the Raspberry Pi (for example, nano, IDLE, or vi) to create a file with
the following code.
This code listens every five seconds for input from the soil moisture sensor kit on the GPIO21 BCM
pin (the 40th pin) on the Raspberry Pi. If the sensor’s microcontroller light is off, a value of 1 is
reported. If the light is on, a value of 0 is reported.
2. Save the file with the extension .py, for example, gpio.py, in the deviceSDK folder. If you choose
to use a different name for the .py file, be sure to substitute it throughout this sample.
3. From the command prompt in PuTTY or SSH, or from the terminal in Raspbian, run commands to
switch to the deviceSDK folder, and then use Python to run the gpio.py file, for example, cd /
deviceSDK && python gpio.py.
4. Every 5–10 seconds, place the prongs on the sensor module into a glass of water, or remove
the prongs from the water. Every 5 seconds, Python prints No water detected or Water
detected!, depending on whether the prongs are in the water.
5. When you’re done, stop running the script by pressing Ctrl+C.
To do this, you integrate some of the code that you wrote in the previous step into the code that you
wrote in moisture.py for Step 5: Simulate Random Moisture Levels (p. 126).
145
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
1. Use an available code editor on the Raspberry Pi to open the moisture.py file that you created in
Step 5: Simulate Random Moisture Levels (p. 126).
2. Add some of the code from the gpio.py file that you wrote into the moisture.py file, and make a
few changes to the existing code in the moisture.py file, as indicated between the ### BEGIN and
### END comments, as follows. The final code is listed immediately after the following code to be
changed.
# The relative path to the correct root CA file for AWS IoT,
# that you have already saved onto this device.
ROOT_CA = "AmazonRootCA1.pem"
146
AWS IoT Developer Guide
Module 2: Sending Data with the Raspberry Pi
while True:
if GPIO.input(channel):
myDeviceShadow.shadowUpdate(
'{"state":{"reported":{"moisture":"low"}}}',
myShadowUpdateCallback, 5)
else:
myDeviceShadow.shadowUpdate(
'{"state":{"reported":{"moisture":"okay"}}}',
myShadowUpdateCallback, 5)
Note
In the preceding code, note that the following values will not match your code:
5. Run commands to switch to the deviceSDK folder if you're not already there. Then use Python to
run the moisture.py file, for example, cd /deviceSDK && python moisture.py.
6. Every 45–60 seconds, place the prongs on the sensor module into a glass of water, or remove the
prongs from the water. Every 60 seconds, Python reports "moisture": "low" or "moisture":
"okay" to AWS IoT, depending on whether the prongs are in the water. Whenever AWS IoT receives
a low moisture reading, it triggers a rule that sends an alert to your email address through Amazon
SNS.
7. When you’re done, press Ctrl+C to stop running the script.
8. You can now replace the glass of water with a common houseplant. Place the prongs on the sensor
module into the houseplant’s soil. Adjust the potentiometer on the sensor’s microcontroller to get
the right sensitivity of soil moisture that you want.
9. In the moisture.py file, change the 60 in time.sleep(60) to the number of seconds between
times you want to check the soil. For example, to check once an hour, change 60 to 3600. To check
once a day, change 60 to 86400.
10. Restart the moisture.py script by running the command python moisture.py.
11. After each interval of seconds in time.sleep passes, Python reports "moisture": "low"
or "moisture": "okay" to AWS IoT. This depends on whether the DO light on the sensor’s
147
AWS IoT Developer Guide
Cleaning Up
microcontroller is off or on, the soil moisture level, and the potentiometer’s sensitivity setting.
Whenever AWS IoT receives a low moisture reading, it triggers a rule that sends an alert to your
email address through Amazon SNS.
12. When you’re done, stop running the script by pressing Ctrl+C.
Cleaning Up
If you no longer want to use the AWS resources in AWS IoT, Amazon SNS, and IAM that you created for
this sample, you can delete those resources by following the instructions in this section.
Note
If you don’t delete these AWS resources, then any ongoing usage of those resources might start
generating charges to your AWS account.
1. In the AWS Management Console, open the AWS IoT console, if it isn’t already open. To do this, on
the AWS navigation bar, choose Services. In the Find a service by name or feature box, enter IoT
Core, and then press Enter.
2. In the service navigation pane, expand Manage.
3. If an Introducing AWS IoT Device Management dialog box is displayed, choose Show me later, or
press Esc.
4. Choose Things.
5. In the list of things, in the card for the name of the thing you want to delete (for example, MyRPi),
choose the ellipsis (…), and then choose Delete.
1. In the AWS IoT console, in the service navigation pane, expand Secure, and then choose
Certificates.
2. In the list of certificates, in the card for the thing’s certificate, choose the ellipsis (...), and then
choose Delete.
148
AWS IoT Developer Guide
Cleaning Up
If you’re not sure which certificate to delete, then in the list of certificates, choose the ID for the
certificate that you think is the correct one. Then choose Things.
If your thing’s name is displayed, this is the correct certificate to delete. Choose Actions, and then
choose Delete.
If, however, your thing isn't displayed, this isn’t the correct certificate. Choose the back button to
return to the list of certificates.
149
AWS IoT Developer Guide
Cleaning Up
1. In the AWS IoT console, in the service navigation pane, expand Secure, and then choose Policies.
2. In the list of policies, in the card for the thing’s policy (for example, PlantWateringPolicy), choose
the ellipsis (...), and then choose Delete.
1. In the AWS IoT console, in the service navigation pane, choose Act.
2. In the list of rules, in the card for the thing’s rule (for example, MyRPiLowMoistureAlertRule),
choose the ellipsis (...), and then choose Delete.
1. Open the Amazon SNS console. To do this, on the AWS navigation bar, choose Services. In the Find a
service by name or feature box, enter SNS, and then press Enter.
2. In the service navigation pane, choose Subscriptions.
3. In the list of subscriptions, select the box for the row where Topic ARN contains the name of the
related topic (for example, MyRPiLowMoistureTopic) and Endpoint contains your email address.
4. Choose Actions, Delete subscriptions.
150
AWS IoT Developer Guide
Cleaning Up
1. In the Amazon SNS console, in the service navigation pane, choose Topics.
2. In the list of topics, select the box for the row where Name contains the name of the related topic
(for example, MyRPiLowMoistureTopic).
3. Choose Actions, Delete topics.
1. Open the IAM console. To do this, on the AWS navigation bar, choose Services. In the Find a service
by name or feature box, enter IAM, and then press Enter.
2. In the service navigation pane, choose Roles.
3. In the list of roles, select the box where Role name contains the name of the related role (for
example, MyRPiLowMoistureTopicRole). If you can’t find the role, then in the Search box, enter the
name of the role. Then press Enter.
4. Choose Delete role.
151
AWS IoT Developer Guide
Next Steps
Next Steps
Learn more about how to use AWS IoT. See the following resources.
1. AWS IoT Developer Guide – Learn more about the concepts in this sample walkthrough, including how
to work more extensively with things, rules, and shadows. Then learn about thing types, thing groups,
jobs, and services such as AWS IoT Device Defender.
2. AWS IoT Greengrass Developer Guide – Learn how AWS IoT Greengrass enables you to securely
run local compute, messaging, data caching, sync, and machine language inference capabilities for
connected devices.
3. AWS IoT Analytics User Guide – Learn how AWS IoT Analytics, a fully managed service, makes it easy
to run and operationalize sophisticated analytics on massive volumes of IoT data. With AWS IoT
Analytics, you don’t have to worry about the cost and complexity typically required to build an IoT
analytics platform.
The AWS IoT Analytics console also has a Quick start feature that allows you to create a channel, data
store, pipeline, and data store with one click. Look for this page when you enter the AWS IoT Analytics
console:
152
AWS IoT Developer Guide
Next Steps
4. AWS IoT 1-Click Developer Guide – Learn how to use AWS IoT 1-Click, a service that enables simple
devices to trigger AWS Lambda functions to execute actions.
5. Amazon FreeRTOS User Guide – Learn how to use Amazon FreeRTOS, an operating system for
microcontrollers that makes small, low-power edge devices easy to program, deploy, secure, connect,
and manage.
6. AWS IoT Events Developer Guide – Learn how to use AWS IoT Events to monitor your equipment and
device fleets for failures or changes in operation, and to trigger actions when such events occur.
153
AWS IoT Developer Guide
How to Manage Things with the Registry
Information about a thing is stored in the registry as JSON data. Here is an example thing:
{
"version": 3,
"thingName": "MyLightBulb",
"defaultClientId": "MyLightBulb",
"thingTypeName": "LightBulb",
"attributes": {
"model": "123",
"wattage": "75"
}
}
Things are identified by a name. Things can also have attributes, which are name-value pairs you can use
to store information about the thing, such as its serial number or manufacturer.
A typical device use case involves the use of the thing name as the default MQTT client ID. Although we
do not enforce a mapping between a thing’s registry name and its use of MQTT client IDs, certificates,
or shadow state, we recommend you choose a thing name and use it as the MQTT client ID for both the
registry and the Device Shadow service. This provides organization and convenience to your IoT fleet
without removing the flexibility of the underlying device certificate model or shadows.
You do not need to create a thing in the registry to connect a device to AWS IoT. Adding things to the
registry allows you to manage and search for devices more easily.
Create a Thing
The following command shows how to use the AWS IoT CreateThing command from the CLI to create a
thing:
The CreateThing command displays the name and ARN of your new thing:
{
"thingArn": "arn:aws:iot:us-east-1:123456789012:thing/MyLightBulb",
"thingName": "MyLightBulb"
"thingId": "12345678abcdefgh12345678ijklmnop12345678"
154
AWS IoT Developer Guide
List Things
Note
We do not recommend using personally identifiable information in your thing names.
List Things
You can use the ListThings command to list all things in your account:
You can use the ListThings command to search for all things associated with a thing type name:
{
"things": [
{
"thingTypeName": "LightBulb",
"attributes": {
"model": "123",
155
AWS IoT Developer Guide
Update a Thing
"wattage": "75"
},
"version": 1,
"thingName": "MyRGBLight"
},
{
"thingTypeName": "LightBulb",
"attributes": {
"model": "123",
"wattage": "75"
},
"version": 1,
"thingName": "MySecondLightBulb"
}
]
}
You can use the ListThings command to search for all things that have an attribute with a specific value:
{
"things": [
{
"thingTypeName": "StopLight",
"attributes": {
"model": "123",
"wattage": "75"
},
"version": 3,
"thingName": "MyLightBulb"
},
{
"thingTypeName": "LightBulb",
"attributes": {
"model": "123",
"wattage": "75"
},
"version": 1,
"thingName": "MyRGBLight"
},
{
"thingTypeName": "LightBulb",
"attributes": {
"model": "123",
"wattage": "75"
},
"version": 1,
"thingName": "MySecondLightBulb"
}
]
}
Update a Thing
You can use the UpdateThing command to update a thing:
156
AWS IoT Developer Guide
Delete a Thing
The UpdateThing command does not produce output. You can use the DescribeThing command to see
the result:
Delete a Thing
You can use the DeleteThing command to delete a thing:
This command returns successfully with no error if the deletion is successful or you specify a thing that
doesn't exist.
Thing Types
Thing types allow you to store description and configuration information that is common to all things
associated with the same thing type. This simplifies the management of things in the registry. For
example, you can define a LightBulb thing type. All things associated with the LightBulb thing type share
a set of attributes: serial number, manufacturer, and wattage. When you create a thing of type LightBulb
(or change the type of an existing thing to LightBulb) you can specify values for each of the attributes
defined in the LightBulb thing type.
Although thing types are optional, their use provides better discovery of things.
157
AWS IoT Developer Guide
Create a Thing Type
Thing types are immutable. You cannot change a thing type name after it has been created. You can
deprecate a thing type at any time to prevent new things from being associated with it. You can also
delete thing types that have no things associated with them.
The CreateThingType command returns a response that contains the thing type and its ARN:
{
"thingTypeName": "LightBulb",
"thingTypeId": "df9c2d8c-894d-46a9-8192-9068d01b2886",
"thingTypeArn": "arn:aws:iot:us-west-2:123456789012:thingtype/LightBulb"
}
The ListThingTypes command returns a list of the thing types defined in your AWS account:
{
"thingTypes": [
{
"thingTypeName": "LightBulb",
"thingTypeProperties": {
"searchableAttributes": [
"wattage",
"model"
],
"thingTypeDescription": "light bulb type"
},
"thingTypeMetadata": {
"deprecated": false,
"creationDate": 1468423800950
}
}
]
}
158
AWS IoT Developer Guide
Associate a Thing Type with a Thing
{
"thingTypeProperties": {
"searchableAttributes": [
"model",
"wattage"
],
"thingTypeDescription": "light bulb type"
},
"thingTypeId": "df9c2d8c-894d-46a9-8192-9068d01b2886",
"thingTypeArn": "arn:aws:iot:us-west-2:123456789012:thingtype/LightBulb",
"thingTypeName": "LightBulb",
"thingTypeMetadata": {
"deprecated": false,
"creationDate": 1544466338.399
}
}
You can use the UpdateThing command at any time to change the thing type associated with a thing:
You can also use the UpdateThing command to disassociate a thing from a thing type.
{
"thingTypeName": "StopLight",
"thingTypeProperties": {
"searchableAttributes": [
"wattage",
159
AWS IoT Developer Guide
Delete a Thing Type
"numOfLights",
"model"
],
"thingTypeDescription": "traffic light type",
},
"thingTypeMetadata": {
"deprecated": true,
"creationDate": 1468425854308,
"deprecationDate": 1468446026349
}
}
Deprecating a thing type is a reversible operation. You can undo a deprecation by using the --undo-
deprecate flag with the DeprecateThingType CLI command:
You can use the DescribeThingType CLI command to see the result:
{
"thingTypeName": "StopLight",
"thingTypeArn": "arn:aws:iot:us-east-1:123456789012:thingtype/StopLight",
"thingTypeId": "12345678abcdefgh12345678ijklmnop12345678"
"thingTypeProperties": {
"searchableAttributes": [
"wattage",
"numOfLights",
"model"
],
"thingTypeDescription": "traffic light type"
},
"thingTypeMetadata": {
"deprecated": false,
"creationDate": 1468425854308,
}
}
Note
You must wait five minutes after you deprecate a thing type before you can delete it.
Thing Groups
Thing groups allow you to manage several things at once by categorizing them into groups. Groups can
also contain groups — you can build a hierarchy of groups. You can attach a policy to a parent group and
it will be inherited by its child groups, and by all of the things in the group and in its child groups as well.
This makes control of permissions easy for large numbers of things.
160
AWS IoT Developer Guide
Create a Thing Group
Attaching and detaching policies to groups can enhance the security of your AWS IoT operations in a
number of significant ways. The per device method of attaching a policy to a certificate, which is then
attached to a thing, is time consuming and makes it difficult to quickly update or change policies across
a fleet of devices. Having a policy attached to the thing's group saves steps when it is time to rotate
the certificates on a thing. And policies are dynamically applied to things when they change group
membership, so you aren't required to re-create a complex set of permissions each time a device changes
membership in a group.
The CreateThingGroup command returns a response that contains the thing group, its ID, and ARN:
{
"thingGroupName": "LightBulbs",
"thingGroupId": "abcdefgh12345678ijklmnop12345678qrstuvwx",
"thingGroupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs"
161
AWS IoT Developer Guide
Describe a Thing Group
Note
We do not recommend using personally identifiable information in your thing group names.
Here is an example that specifies a parent of the thing group when it is created:
As before, the CreateThingGroup command returns a response that contains the thing group, its ID, and
ARN:
{
"thingGroupName": "RedLights",
"thingGroupId": "abcdefgh12345678ijklmnop12345678qrstuvwx",
"thingGroupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RedLights",
}
Important
Keep in mind the following limits when creating group hierarchies:
{
"thingGroupName": "RedLights",
"thingGroupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RedLights",
"thingGroupId": "12345678abcdefgh12345678ijklmnop12345678",
"version": 1,
"thingGroupMetadata": {
"creationDate": 1478299948.882
"parentGroupName": "Lights",
"rootToParentThingGroups": [
{
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/ShinyObjects",
"groupName": "ShinyObjects"
},
{
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs",
"groupName": "LightBulbs"
}
]
},
"thingGroupProperties": {
162
AWS IoT Developer Guide
Add a Thing to a Thing Group
"attributePayload": {
"attributes": {
"brightness": "3400_lumens"
},
},
"thingGroupDescription": "string"
},
}
The ListThingsInThingGroup command returns a list of the things in the given group:
{
"things":[
"TestThingA"
]
}
With the --recursive parameter, you can list things belonging to a group and those in any of its child
groups as well:
163
AWS IoT Developer Guide
List Thing Groups
"things":[
"TestThingA",
"MyLightBulb"
]
}
Note
This operation is eventually consistent. In other words, changes to the thing group might not be
reflected immediately.
The ListThingGroups command returns a list of the groups defined in your AWS account:
{
"thingGroups": [
{
"groupName": "LightBulbs",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs"
},
{
"groupName": "RedLights",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RedLights"
},
{
"groupName": "RedLEDLights",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RedLEDLights"
},
{
"groupName": "RedIncandescentLights",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/
RedIncandescentLights"
}
{
"groupName": "ReplaceableObjects",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/ReplaceableObjects"
}
]
}
Use the optional filters to list those groups that have a given group as parent (--parent-group)
or groups whose name begins with a given prefix (--name-prefix-filter.) The --recursive
parameter allows you to list all children groups, not just direct child groups of a thing group:
In this case, the ListThingGroups command returns a list of the direct child groups of the thing group
defined in your AWS account:
{
"childGroups":[
{
"groupName": "RedLights",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RedLights"
}
164
AWS IoT Developer Guide
List Groups for a Thing
]
}
Use the --recursive parameter with the ListThingGroups command to list all child groups of a thing
group, not just direct children:
The ListThingGroups command returns a list of all child groups of the thing group:
{
"childGroups":[
{
"groupName": "RedLights",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RedLights"
},
{
"groupName": "RedLEDLights",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RedLEDLights"
},
{
"groupName": "RedIncandescentLights",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/
RedIncandescentLights"
}
]
}
Note
This operation is eventually consistent. In other words, changes to the thing group might not be
reflected immediately.
The ListThingGroupsForThing command returns a list of the thing groups this thing belongs to,
including any parent groups:
{
"thingGroups":[
{
"groupName": "LightBulbs",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs"
},
{
"groupName": "RedLights",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RedLights"
},
{
"groupName": "ReplaceableObjects",
"groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/ReplaceableObjects"
}
]
}
165
AWS IoT Developer Guide
Update a Thing Group
The UpdateThingGroup command returns a response that contains the group's version number after the
update:
{
"version": 4
}
Note
A group can have up to 50 attributes.
You must delete any child groups first before you delete the group.
You can delete a group that has child things, but any permissions granted to the things by membership
in the group no longer apply. Before deleting a group that has a policy attached, check carefully that
removing those permissions would not stop the things in the group from being able to function properly.
Also, note that commands that show which groups a thing belongs to (for example, ListGroupsForThing)
might continue to show the group while records in the cloud are being updated.
166
AWS IoT Developer Guide
Detach a Policy from a Thing Group
Note
We do not recommend using personally identifiable information in your policy names.
The --target parameter can be a thing group ARN (as above), a certificate ARN, or an Amazon Cognito
Identity. For more information about policies, certificates and authentication, see Security and Identity
for AWS IoT (p. 179).
The --target parameter can be a thing group ARN (as above), a certificate ARN, or an Amazon Cognito
Identity.
Add the optional --recursive parameter to include all policies attached to the group's parent groups
as well.
{
"policies": [
"MyLightBulbPolicy"
...
]
}
Add the optional --page-size number parameter to specify the maximum number of results to be
returned for each query, and the --marker string parameter on subsequent calls to retrieve the next
set of results, if any.
The ListTargetsForPolicy command returns a list of targets and the token to use to retrieve more results:
{
"nextMarker": "string",
"targets": [ "string" ... ]
}
167
AWS IoT Developer Guide
Get Effective Policies for a Thing
Use the --principal parameter to specify the ARN of the certificate attached to the thing. If you are
using Amazon Cognito Identity authentication, use the --cognito-identity-pool-id parameter
and, optionally, add the --principal parameter to specify a specific Cognito Identity. (If you specify
only the --cognito-identity-pool-id then the policies associated with that identity pool's role for
unauthenticated users are returned. If you use both, the policies associated with that identity pool's role
for authenticated users are returned.
The --thing-name parameter is optional and may be used instead of the --principal parameter.
When used, the policies attached to any group the thing belongs to, and the policies attached to any
parent groups of these groups (up to the root group in the hierarchy) will be returned.
{
"effectivePolicies": [
{
"policyArn": "string",
"policyDocument": "string",
"policyName": "string"
}
...
]
}
Use the --principal parameter to specify the ARN of the certificate attached to the thing. If using
Amazon Cognito Identity authentication, specify a Cognito Identity as the --principal or use the --
cognito-identity-pool-id parameter, or both. (If you specify only the --cognito-identity-
pool-id then the policies associated with that identity pool's role for unauthenticated users are
considered. If you use both, the policies associated with that identity pool's role for authenticated users
are considered.
Specify one or more MQTT actions you want to test by listing sets of resources and action types
following the --auth-infos parameter. The actionType field should contain "PUBLISH",
"SUBSCRIBE", "RECEIVE", or "CONNECT". The resources field should contain a list of resource ARNs. See
AWS IoT Policies (p. 193) for more information.
168
AWS IoT Developer Guide
Dynamic Thing Groups
You can test the effects of adding policies by specifying them with the --policy-names-to-add
parameter. Or you can test the effects of removing policies by them with the --policy-names-to-
skip parameter.
You can use the optional --client-id parameter to further refine your results.
The TestAuthorization command returns details on actions that were allowed or denied for each set of
--auth-infos queries you specified:
{
"authResults": [
{
"allowed": {
"policies": [
{
"policyArn": "string",
"policyName": "string"
}
]
},
"authDecision": "string",
"authInfo": {
"actionType": "string",
"resources": [ "string" ]
},
"denied": {
"explicitDeny": {
"policies": [
{
"policyArn": "string",
"policyName": "string"
}
]
},
"implicitDeny": {
"policies": [
{
"policyArn": "string",
"policyName": "string"
}
]
}
},
"missingContextValues": [ "string" ]
}
]
}
You can apply a policy to a dynamic thing group. A thing can belong to at most 10 dynamic groups. If
a search query string defines a dynamic thing group that contains a thing that already belongs to 10
dynamic thing groups, the policy is not applied to that thing.
Because dynamic thing groups are tied to your fleet index, you must enable the fleet indexing service
to use them. You can preview the things in a dynamic thing group before you create the group with a
169
AWS IoT Developer Guide
Create a Dynamic Thing Group
fleet indexing search query. For more information, see Fleet Indexing Service and Fleet Indexing Service:
Query Syntax.
You can specify a dynamic thing group as a target for a job. Only things that meet the criteria that define
the dynamic thing group perform the job.
For example, suppose that you want to update the firmware on your devices, but, to minimize the chance
that the update is interrupted, you only want to update firmware on devices with battery life greater
than 80%. You can create a dynamic thing group that only includes devices with a reported battery life
above 80%, and you can use that dynamic thing group as the target for your firmware update job. Only
devices that meet your battery life criteria receive the firmware update. As devices reach the 80% battery
life criteria, they are added to the dynamic thing group and receive the firmware update.
For more information about specifying thing groups as job targets, see Using the AWS IoT Jobs APIs.
Dynamic thing groups differ from static thing groups in the following ways:
• Thing membership is not explicitly defined. To create a dynamic thing group, you must define a query
string that defines group membership.
• Dynamic thing groups cannot be part of a hierarchy.
• You use a different set of commands to create, update, and delete dynamic thing groups. For all other
operations, the same commands that you use to interact with static thing groups can be used to
interact with dynamic thing groups.
• A single account can have no more than 100 dynamic thing groups defined.
For more information about static thing groups, see Thing Groups (p. 160).
As an example, suppose we create a dynamic group that contains all rooms in a data warehouse whose
temperature is greater than 60 degrees Fahrenheit. When a room's temperature is 61 degrees or higher,
it is added to the RoomTooWarm dynamic thing group. All rooms in the RoomTooWarm dynamic
thing group have cooling fans turned on. When a room's temperature falls to 60 degrees or lower, it is
removed from the dynamic thing group and its fan would be turned off.
Note
We do not recommend using personally identifiable information in your dynamic thing group
names.
The CreateDynamicThingGroup command returns a response that contains the index name, query
string, query version, thing group name, thing group ID, and thing group ARN:
{
"indexName": "AWS_Things",
"queryVersion": "2017-09-30",
"thingGroupName": "RoomTooWarm",
"thingGroupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RoomTooWarm",
"queryString": "attributes.temperature>60\n",
"thingGroupId": "abcdefgh12345678ijklmnop12345678qrstuvwx"
}
170
AWS IoT Developer Guide
Describe a Dynamic Thing Group
Dynamic thing group creation is not instantaneous. The dynamic thing group backfill takes time to
complete. When a dynamic thing group is created, the status of the group is set to BUILDING. When the
backfill is complete, the status changes to ACTIVE. To check the status of your dynamic thing group, use
the DescribeThingGroup command.
{
"status": "ACTIVE",
"indexName": "AWS_Things",
"thingGroupName": "RoomTooWarm",
"thingGroupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RoomTooWarm",
"queryString": "attributes.temperature>60\n",
"version": 1,
"thingGroupMetadata": {
"creationDate": 1548716921.289
},
"thingGroupProperties": {},
"queryVersion": "2017-09-30",
"thingGroupId": "84dd9b5b-2b98-4c65-84e4-be0e1ecf4fd8"
}
Running DescribeThingGroup on a dynamic thing group returns attributes that are specific to dynamic
thing groups, such as the queryString and the status.
The status of a dynamic thing group can take the following values:
ACTIVE
The dynamic thing group is being created, and thing membership is being processed.
REBUILDING
The dynamic thing group's membership is being updated, following the adjustment of the group's
search query.
Note
After you create a dynamic thing group, you can use the group, regardless of its status. Only
dynamic thing groups with an ACTIVE status include all of the things that match the search
query for that dynamic thing group. Dynamic thing groups with BUILDING and REBUILDING
statuses might not include all of the things that match the search query.
171
AWS IoT Developer Guide
Delete a Dynamic Thing Group
The UpdateDynamicThingGroup command returns a response that contains the group's version number
after the update:
{
"version": 2
}
Dynamic thing group updates are not instantaneous. The dynamic thing group backfill takes time to
complete. When a dynamic thing group is updated, the status of the group changes to REBUILDING
while the group updates its membership. When the backfill is complete, the status changes to ACTIVE.
To check the status of your dynamic thing group, use the DescribeThingGroup command.
Before you delete a group that has a policy attached, be sure that removing those permissions does
not stop the things in the group from functioning properly. Commands that show which groups a thing
belongs to (for example, ListGroupsForThing) might continue to show the group while records in the
cloud are being updated.
172
AWS IoT Developer Guide
Limitations and Conflicts
over dynamic thing groups. With overrideDynamicGroups enabled, if a thing belongs to 10 thing
groups, and one or more of those groups is dynamic, adding the thing to a static thing group removes it
from the newest dynamic thing group.
For example, suppose that you create a dynamic thing group named DynamicGroup1, and then you
create nine more dynamic thing groups, with DynamicGroup10 being the last group that you created.
If Thing1 belongs to all 10 dynamic thing groups, manually adding Thing1 to a static group with
OverrideDynamicGroups enabled removes the thing from DynamicGroup10.
173
AWS IoT Developer Guide
Tag Basics
To help you manage your costs related to things, you can create billing groups (p. 176) that contain
things. You can then assign tags containing your metadata to each of these billing groups. This section
also discusses billing groups and the commands available to create and manage them.
Tag Basics
Tags enable you to categorize your AWS IoT resources in different ways, for example, by purpose, owner,
or environment. This is useful when you have many resources of the same type — you can quickly
identify a specific resource based on the tags you've assigned to it. Each tag consists of a key and
optional value, both of which you define. For example, you could define a set of tags for your thing types
that helps you track devices by type. We recommend that you create a set of tag keys that meets your
needs for each kind of resource. Using a consistent set of tag keys makes it easier for you to manage your
resources.
You can search for and filter resources based on the tags you add or apply. You can also use billing group
tags to categorize and track your costs. You can also use tags to control access to your resources as
described in Using Tags with IAM Policies (p. ).
For ease of use, the Tag Editor in the AWS Management Console provides a central, unified way to create
and manage your tags. For more information, see Working with Tag Editor in Working with the AWS
Management Console.
You can also work with tags using the AWS CLI and the AWS IoT API. You can associate tags with thing
groups, thing types, topic rules, jobs, security profiles, and billing groups when you create them by using
the "Tags" field in the following commands:
You can add, modify, or delete tags for existing resources that support tagging by using the following
commands:
174
AWS IoT Developer Guide
Tag Restrictions and Limitations
You can edit tag keys and values, and you can remove tags from a resource at any time. You can set the
value of a tag to an empty string, but you can't set the value of a tag to null. If you add a tag that has
the same key as an existing tag on that resource, the new value overwrites the old value. If you delete a
resource, any tags associated with the resource are also deleted.
Note
The condition context keys and values in an IAM policy apply only to those AWS IoT actions
where an identifier for a resource capable of being tagged is a required parameter. For example,
the use of DescribeEndpoint (p. 773) will not be allowed or denied on the basis of condition
context keys and values because no taggable resource (thing groups, thing types, topic rules,
jobs, or security profile) is referenced in this request.
Controlling Access Using Tags in the AWS Identity and Access Management User Guide has additional
information on using tags. The IAM JSON Policy Reference section of that guide has detailed syntax,
descriptions, and examples of the elements, variables, and evaluation logic of JSON policies in IAM.
The following example policy applies two tag-based restrictions. An IAM user restricted by this policy:
• Cannot give a resource the tag "env=prod" (in the example, see the line "aws:RequestTag/env" :
"prod"
175
AWS IoT Developer Guide
Billing Groups
• Cannot modify or access a resource that has an existing tag "env=prod" (in the example, see the line
"aws:ResourceTag/env" : "prod").
{
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Deny",
"Action" : "iot:*",
"Resource" : "*",
"Condition" : {
"StringEquals" : {
"aws:RequestTag/env" : "prod"
}
}
},
{
"Effect" : "Deny",
"Action" : "iot:*",
"Resource" : "*",
"Condition" : {
"StringEquals" : {
"aws:ResourceTag/env" : "prod"
}
}
},
{
"Effect": "Allow",
"Action": [
"iot:*"
],
"Resource": "*"
}
]
}
You can also specify multiple tag values for a given tag key by enclosing them in a list, like this:
"StringEquals" : {
"aws:ResourceTag/env" : ["dev", "test"]
}
Note
If you allow or deny users access to resources based on tags, you must consider explicitly
denying users the ability to add those tags to or remove them from the same resources.
Otherwise, it's possible for a user to circumvent your restrictions and gain access to a resource
by modifying its tags.
Billing Groups
AWS IoT doesn't allow you to directly apply tags to individual things, but it does allow you to place
things in billing groups and to apply tags to these. For AWS IoT, allocation of cost and usage data based
on tags is limited to billing groups.
176
AWS IoT Developer Guide
Viewing Cost Allocation and Usage Data
• Be registered as a thing in AWS IoT (see Managing Devices with AWS IoT (p. 154)).
• Connect to the AWS IoT message broker via MQTT using only the thing's name as the client ID
(see Message Broker for AWS IoT (p. 233)).
• Authenticate using a client certificate associated with the thing.
The following pricing dimensions are available for billing groups (based on the activity of things
associated with the billing group):
Cost and usage data based on tags (and reported for a billing group) doesn't reflect the following
activities:
• Device registry operations (including updates to things, thing groups, and thing types; see Managing
Devices with AWS IoT (p. 154))
• Thing group index updates (when adding a thing group)
• Index search queries
• Device Provisioning (p. 461)
• Audit (p. 483) reports
177
AWS IoT Developer Guide
Limits
Limits
• A thing can belong to exactly one billing group.
• Unlike thing groups, billing groups cannot be organized into hierarchies.
• In order for its usage to be registered for tagging or billing purposes, a device must:
• Be registered as a thing in AWS IoT.
• Communicate with AWS IoT using MQTT only.
• Authenticate with AWS IoT using only its thing name as the clientID.
• Use only an X.509 certificate or Amazon Cognito Identity to authenticate.
Additional information can be found in Managing Devices with AWS IoT (p. 154), Security
and Identity for AWS IoT (p. 179), and Device Provisioning (p. 461). The API command
AttachThingPrincipal (p. 669), can be used to attach a certificate or other credential to a thing.
• The maximum number of billing groups per account is 20,000.
178
AWS IoT Developer Guide
AWS IoT Authentication
• You are responsible for managing device credentials (X.509 certificates, AWS credentials) on your
devices and policies in AWS IoT. You are responsible for assigning unique identities to each device and
managing the permissions for a device or group of devices.
• Your devices should connect using X.509 certificates or Amazon Cognito identities over a secure
connection according to the AWS IoT connection model. During research and development, and for
some applications that make API calls or use WebSockets you can also use IAM users and groups, or
custom authentication tokens.
• When using AWS IoT authentication, the message broker authenticates and authorizes all actions in
your account. The message broker is responsible for authenticating your devices, securely ingesting
device data, and adhering to the access permissions you place on devices using policies.
• When using custom authentication, a custom authorizer is responsible for authenticating your devices
and providing an AWS IoT/IAM policy to authorize actions in your account.
• The AWS IoT rules engine forwards device data to other devices and other AWS services according
to rules you define. It uses AWS access management systems to securely transfer data to its final
destination.
• X.509 certificates
• IAM users, groups, and roles
• Amazon Cognito identities
• Federated identities
These identities can be used with mobile applications, web applications, or desktop applications.
They can even be used by a user typing AWS IoT CLI commands. Typically, AWS IoT devices use X.509
179
AWS IoT Developer Guide
X.509 Certificates
certificates, while mobile applications use Amazon Cognito identities. Web and desktop applications use
IAM or federated identities. CLI commands use IAM.
X.509 Certificates
X.509 certificates are digital certificates that use the X.509 public key infrastructure standard to
associate a public key with an identity contained in a certificate. X.509 certificates are issued by a trusted
entity called a certification authority (CA). The CA maintains one or more special certificates called
CA certificates that it uses to issue X.509 certificates. Only the certification authority has access to CA
certificates.
Note
We recommend that each device be given a unique certificate to enable fine-grained
management including certificate revocation.
Devices must support rotation and replacement of certificates in order to ensure smooth
operation as certificates expire.
• SHA256WITHRSA
• SHA384WITHRSA
• SHA384WITHRSA
• SHA512WITHRSA
• RSASSAPSS
• DSA_WITH_SHA256
• ECDSA-WITH-SHA256
• ECDSA-WITH-SHA384
• ECDSA-WITH-SHA512
Certificates provide several benefits over other identification and authentication mechanisms.
Certificates enable asymmetric keys to be used with devices. This means you can burn private keys
into secure storage on a device. This way, sensitive cryptographic material never leaves the device.
Certificates provide stronger client authentication over other schemes, such as user name and password
or bearer tokens, because the secret key never leaves the device.
AWS IoT authenticates certificates using the TLS protocol’s client authentication mode. TLS is available in
many programming languages and operating systems and is commonly used for encrypting data. In TLS
client authentication, AWS IoT requests a client X.509 certificate and validates the certificate’s status and
AWS account against a registry of certificates. It then challenges the client for proof of ownership of the
private key that corresponds to the public key contained in the certificate.
To use AWS IoT certificates, clients must support all of the following in their TLS implementation:
• TLS 1.2.
• SHA-256 RSA certificate signature validation.
• One of the cipher suites from the TLS cipher suite support section.
180
AWS IoT Developer Guide
X.509 Certificates
2049-12-31T23:59:59Z, that is at midnight GMT on December 31, 2049.) The expiry date and time for
certificates signed by a CA certificate are set when the certificate is created.
Note
We recommend that each device be given a unique certificate to enable fine-grained
management including certificate revocation.
Devices must support rotation and replacement of certificates in order to ensure smooth
operation as certificates expire.
To use a certificate that is not created by AWS IoT, you must register a CA certificate. All device
certificates must be signed by the CA certificate you register.
You can use the AWS IoT console or CLI to perform the following operations:
For more information about the CLI commands to use to perform these operations, see AWS IoT CLI
Reference.
For more information about using the AWS IoT console to create certificates, see Create and Activate a
Device Certificate.
Server Authentication
Server certificates allow your devices to verify that they're communicating with AWS IoT and not another
server impersonating AWS IoT. Service certificates need to be copied onto your device and referenced
when connecting to AWS IoT. For more information, see the AWS IoT Device SDKs (p. 615). AWS IoT
server certificates are signed by one of the following CA certificates:
• RSA 2048 bit key: VeriSign Class 3 Public Primary G5 root CA certificate
We recommend that all customers create an Amazon Trust Services (ATS) endpoint and load these
CA certificates onto their devices to avoid any issues with the widespread distrust by browsers of
Symantec CAs (including VeriSign) that occurred in October 2018. For backward-compatibility reasons,
we still support customers using these endpoints. Customers can create an ATS endpoint by calling the
describe-endpoint API with the iot:Data-ATS endpointType. Devices operating on ATS endpoints
are fully interoperable with devices operating on Symantec endpoints in the same account and do not
require any reregistration.
181
AWS IoT Developer Guide
X.509 Certificates
Storing all of these certificates on your device can take up valuable memory space. If your devices
implement RSA-based validation, you can omit the Amazon Root CA 3 and Amazon Root CA 4 ECC
certificates. If your devices implement ECC-based certificate validation, you can omit the Amazon Root
CA 1 and Amazon Root CA 2 RSA certificates.
All new AWS IoT Core regions, beginning with the May 9, 2018 launch of AWS IoT Core in the Asia Pacific
(Mumbai) Region, will serve only ATS certificates.
Note
CA certificates have an expiration date after which they cannot be used to validate a server's
certificate. CA certificates might have to be replaced before their expiration date. Make sure that
you can update the root CA certificates on all of your devices to ensure ongoing connectivity
and to keep up-to-date with security best practices.
For a complete list of CA certificates used by AWS IoT see, Amazon Trust Services.
1. Sign in to the AWS Management Console and open the AWS IoT console.
2. In the left navigation pane, choose Security to expand the choices, and then choose Certificates.
Choose Create.
3. Choose One-click certificate creation - Create certificate. Alternatively, to generate a certificate
with a certificate signing request (CSR), choose Create with CSR.
4. Use the links to the public key, private key, and certificate to download each to a secure location.
5. Choose Activate.
• create-keys-and-certificate
The CreateKeysAndCertificate API creates a private key, public key, and X.509 certificate.
• create-certificate-from-csr
182
AWS IoT Developer Guide
X.509 Certificates
Contents
• Registering Your CA Certificate (p. 183)
• Creating a Device Certificate Using Your CA Certificate (p. 184)
• Registering a Device Certificate (p. 185)
• Registering Device Certificates Manually (p. 185)
• Using Automatic/Just-in-Time Registration for Device Certificates (p. 185)
• Deactivate the CA Certificate (p. 186)
• Revoke the Device Certificate (p. 186)
If you do not have a CA certificate, you can use OpenSSL tools to create one.
To create a CA certificate
2. Use the private key from the key pair to generate a CA certificate.
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
The Common Name field in the private key verification certificate must be set to the registration code
generated by the get-registration-code CLI command. A single registration code is generated
per AWS account. You can use the register-ca-certificate command or the AWS IoT console to
register CA certificates.
Note
A CA certificate cannot be registered to more than one account in the same region. However,
a CA certificate can be registered to more than one account if the accounts are in different
regions.
To register a CA certificate
1. Get a registration code from AWS IoT. This code is used as the Common Name of the private key
verification certificate.
183
AWS IoT Developer Guide
X.509 Certificates
3. Create a CSR for the private key verification certificate. Set the Common Name field of the certificate
to your registration code.
You are prompted for some information, including the Common Name, for the certificate.
5. Register the CA certificate with AWS IoT. Pass in the CA certificate and the private key verification
certificate to the register-ca-certificate CLI command.
You can use a CA certificate registered with AWS IoT to create a device certificate. The device certificate
must be registered with AWS IoT before use.
184
AWS IoT Developer Guide
X.509 Certificates
openssl x509 -req -in deviceCert.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -
out deviceCert.pem -days 500 -sha256
Note
You must use the CA certificate registered with AWS IoT to create device certificates. If you
have more than one CA certificate (with the same subject field and public key) registered in
your AWS account, you must specify the CA certificate used to create the device certificate
when you register your device certificate.
4. Register a device certificate.
You must use the CA certificate registered with AWS IoT to sign device certificates. If you have more than
one CA certificate (with the same subject field and public key) registered in your AWS account, you must
specify the CA certificate used to sign the device certificate when you register your device certificate. You
can register each device certificate manually, or you can use automatic registration, which allows devices
to register their certificate when they connect to AWS IoT for the first time.
To register device certificates automatically when devices first connect to AWS IoT, you must enable
automatic registration for your CA certificate. This registers any device certificate signed by your CA
certificate when it connects to AWS IoT.
You can also set the auto-registration-status to ENABLE when you use the register-ca-
certificate API to register your CA certificate:
When a device first attempts to connect to AWS IoT, as part of the TLS handshake, it must present
a registered CA certificate and a device certificate. AWS IoT recognizes the CA certificate as a
185
AWS IoT Developer Guide
X.509 Certificates
registered CA certificate and automatically registers the device certificate and sets its status to
PENDING_ACTIVATION. This means that the device certificate was automatically registered and is
awaiting activation. A certificate must be in the ACTIVE state before it can be used to connect to AWS
IoT. When AWS IoT automatically registers a certificate or when a certificate in PENDING_ACTIVATION
status connects, AWS IoT publishes a message to the following MQTT topic:
$aws/events/certificates/registered/caCertificateID
Where caCertificateID is the ID of the CA certificate that issued the device certificate.
{
"certificateId": "certificateID",
"caCertificateId": "caCertificateId",
"timestamp": timestamp,
"certificateStatus": "PENDING_ACTIVATION",
"awsAccountId": "awsAccountId",
"certificateRegistrationTimestamp": "certificateRegistrationTimestamp"
}
You can create a rule that listens on this topic and performs some actions. We recommend that you
create a Lambda rule that verifies the device certificate is not on a certificate revocation list (CRL),
activates the certificate, and creates and attaches a policy to the certificate. The policy determines which
resources the device is able to access. For more information about how to create a Lambda rule that
listens on the $aws/events/certificates/registered/caCertificateID topic and performs
these actions, see Just-in-Time Registration.
When you register a device certificate, AWS checks if the associated CA certificate is ACTIVE. If the CA
certificate is INACTIVE, AWS IoT does not allow the device certificate to be registered. By marking the
CA certificate as INACTIVE, you prevent any new device certificates issued by the compromised CA to
be registered in your account. You can use the update-ca-certificate API to deactivate the CA
certificate:
Note
Any registered device certificates that were signed by the compromised CA certificate continue
to work until you explicitly revoke them.
Use the ListCertificatesByCA API to get a list of all registered device certificates that were signed
by the compromised CA. For each device certificate signed by the compromised CA certificate, use the
UpdateCertificate API to revoke the device certificate to prevent it from being used.
If you detect suspicious activity on a registered device certificate, you can use the update-
certificate API to revoke it:
If any error or exception occurs during the auto-registration of the device certificates, AWS IoT sends
events or messages to your logs in CloudWatch Logs. For more information about setting up the logs for
your account, see the Amazon CloudWatch documentation.
186
AWS IoT Developer Guide
IAM Users, Groups, and Roles
IAM roles also allow AWS IoT to access other AWS resources in your account on your behalf. For example,
if you want to have a device publish its state to a DynamoDB table, IAM roles allow AWS IoT to interact
with Amazon DynamoDB. For more information, see IAM Roles.
For message broker connections over HTTP, AWS IoT authenticates IAM users, groups, and roles using the
Signature Version 4 signing process. For information, see Signing AWS API Requests.
When using AWS Signature Version 4 with AWS IoT, clients must support the following in their TLS
implementation:
You can attach an AWS IoT policy to an Amazon Cognito identity using the AttachPrincipalPolicy API
and give fine-grained permissions to an individual user of your AWS IoT application. In this way, you can
assign permissions between specific customers and their devices. For more information, see Amazon
Cognito Identity.
Custom Authentication
AWS IoT allows you to define custom authorizers that allow you to manage your own authentication and
authorization strategy using a custom authentication service and a Lambda function. Custom authorizers
187
AWS IoT Developer Guide
Custom Authorizers
allow AWS IoT to authenticate your devices and authorize operations using bearer token authentication
and authorization strategies.
When an HTTP connection is established (and optionally upgraded to a WebSocket connection) and
Signature Version 4 headers are not present, the AWS IoT device gateway checks if a custom authorizer is
configured for the endpoint, and if so, it is used to authenticate the connection and authorize the device.
Custom authorizers can implement various authentication strategies (for example: JWT verification,
OAuth provider callout, and so on) and must return policy documents that are used by the device
gateway to authorize MQTT operations.
Custom Authorizers
Custom authorizers consist of:
Name
An ARN of a Lambda function that implements the authentication logic and returns authorization
policies.
Public key
The public key from a key pair that is used to prevent unauthorized calls to the authorizer's Lambda
function.
openssl genrsa
-out myKeyPair.pem 2048
Use the following command to extract the public key from the key pair:
The key name used to extract tokens from the WebSocket connection headers.
This function takes a token presented by a device, authenticates the device, and returns the following
information:
isAuthenticated
A Boolean value that indicates whether the token was authenticated. If this is false, the rest of the
response fields should be ignored.
principalId
188
AWS IoT Developer Guide
Configure a Custom Authorizer
policyDocuments
A list of policies that specifies which operations the token bearer can perform.
DisconnectAfterInSecs
The length of time, in seconds, after which the Lambda function is invoked to refresh the policies.
Context
Additional information derived after validating the token. This information is made available in AWS
IoT rules engine SQL statements and IAM/AWS IoT policy variables.
You must grant permission to the AWS IoT service principal to invoke the Lambda function that
implements the custom authentication/authorization logic. You can do this with the following CLI
command:
function-name
The name of the Lambda function to which you are granting invocation permission.
statement-id
A statement identifier
action
The ARN of the custom authorizer, specifying this value ensures your Lambda function can only be
invoked by the intended custom authorizer.
For more information about granting permission to call Lambda functions, see AWS Lambda Permissions.
You can set a default authorizer that is used when authorizer information is not included in a connection
request:
189
AWS IoT Developer Guide
Custom Authorizer Workflow
{
"isAuthenticated": true,
"principalId": "xxxxxxxx",
"disconnectAfterInSeconds": 86400,
"refreshAfterInSeconds": 300,
"policyDocuments": [
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"...\",\"Effect\":
\"Allow|Deny\",\"Resource\":\"...\"}]}"
],
"context": {
"username": "johnDoe123",
"city": "Seattle",
"country": "USA"
}
}
The return value of the Lambda function should be similar to the above. It can be either a JSON
serialized or non-serialized object.
2. Register a custom authorizer with AWS IoT using the create-authorizer API.
The test-invoke-authorizer API can be used to test if the custom authorizer Lambda function
has been configured correctly, as shown:
Note
<TOKEN_SIGNATURE> must be signed with the private key of the public/private key pair
uploaded to AWS IoT used in the create-authorizer call. One method of locally creating
<TOKEN_SIGNATURE> from a UNIX-like command line is as follows:
You must trim all newline characters from the result of the prior command before passing
the <TOKEN_SIGNATURE> value to the test-invoke-authorizer API.
190
AWS IoT Developer Guide
Custom Authorizer Workflow
When a device attempts to connect to AWS IoT, it sends the following information in HTTP headers:
The following is an example HTTP request to connect to AWS IoT over the WebSocket protocol.
In this example, the x-amz-customauthorizer-name header specifies the custom authorizer to use,
the x-amz-customauthorizer-signature header contains the digital signature used to verify the
token, and the token-key-name is the token key name specified by the --token-key-name passed to the
create-authorizer API.
Note
Some web browsers may not support custom HTTP headers.
The AWS IoT device gateway validates the digital signature and if valid, calls the specified authorizer. The
following is an example payload AWS IoT sends to the custom authenticator's Lambda function.
{
"token": "some-token"
}
The authorizer validates the token and returns a principal ID, its associated AWS IoT/IAM policy, and
time-to-live (TTL) information for the connection.
{
"isAuthenticated":true,
"principalId": "xxxxxxxx",
"disconnectAfterInSeconds": 86400,
"refreshAfterInSeconds", 300,
"policyDocuments": [
"{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Action\": \"...\", \"Effect\":
\"Allow|Deny\", \"Resource\": \"...\" } ] }"
]
}
The return value of the Lambda function should be similar to the above and can be either a JSON
serialized or non-serialized object.
The AWS IoT device gateway then establishes the WebSocket connection. AWS IoT caches the policies
associated with the principal so subsequent calls can be authorized without having to reauthenticate
the device. Any failure that occurs during custom authentication results in authentication failure and
connection termination.
191
AWS IoT Developer Guide
Authorization
For an end-to-end example of this workflow, see How to Use Your Own Identity and Access Management
Systems to Control Access to AWS IoT Resources.
Authorization
Policies determine what an authenticated identity can do. An authenticated identity is used by devices,
mobile applications, web applications, and desktop applications. An authenticated identity can even be
a user typing AWS IoT CLI commands. The identity can execute AWS IoT operations only if it has a policy
that grants it permission.
Both AWS IoT policies and IAM policies are used with AWS IoT to control the operations an identity (also
called a principal) can perform. The policy type you use depends on the type of identity you are using to
authenticate with AWS IoT. The following table shows the identity types, the protocols they use, and the
policy types that can be used for authorization.
• Control plane API allows you to perform administrative tasks like creating or updating certificates,
things, rules, and so on.
• Data plane API allows you send data to and receive data from AWS IoT.
The type of policy you use depends on whether you are using control plane or data plane API.
192
AWS IoT Developer Guide
AWS IoT Policies
AWS IoT policies are attached to X.509 certificates or Amazon Cognito identities. IAM policies are
attached to an IAM user, group, or role. If you use the AWS IoT console or the AWS IoT CLI to attach the
policy (to a certificate or Amazon Cognito Identity), you use an AWS IoT policy. Otherwise, you use an
IAM policy.
Policy-based authorization is a powerful tool. It gives you complete control over what a device, user, or
application can do in AWS IoT. For example, consider a device connecting to AWS IoT with a certificate.
You can allow the device to access all MQTT topics, or you can restrict its access to a single topic. In
another example, consider a user typing CLI commands at the command line. By using a policy, you
can allow or deny access to any command or AWS IoT resource for the user. You can also control an
application's access to AWS IoT resources.
AWS IoT defines a set of policy actions that describe the operations and resources to which you can grant
or deny access. For example:
AWS IoT policies allow you to control access to the AWS IoT data plane. The AWS IoT data plane
consists of operations that allow you to connect to the AWS IoT message broker, send and receive
MQTT messages, and get or update a device's shadow. For more information, see AWS IoT Policy
Actions (p. 194).
An AWS IoT policy is a JSON document that contains one or more policy statements. Each statement
contains an Effect, an Action, and a Resource. The Effect specifies whether the action is allowed
or denied. The Action specifies the action the policy is allowing or denying. The Resource specifies the
resource or resources on which the action is allowed or denied.
For devices registered as things in the AWS IoT Registry, the following policy grants permission to
connect to AWS IoT with a client id matching the thing name and restricts the device to publishing
on a client-id/thing name specific MQTT topic. In order for a connection to be successful, the thing
name must be registered in the AWS IoT Registry and be authenticated using an identity/principal
attached to the thing:
193
AWS IoT Developer Guide
AWS IoT Policies
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action":["iot:Publish"],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/
${iot:Connection.Thing.ThingName}"]
},
{
"Effect": "Allow",
"Action": ["iot:Connect"],
"Resource": ["arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"]
}
]
}
For devices not registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT with client id "client1" and restricts the device to publishing on a client-id
specific MQTT topic:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action":["iot:Publish"],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${iot:clientId}"]
},
{
"Effect": "Allow",
"Action": ["iot:Connect"],
"Resource": ["arn:aws:iot:us-east-1:123456789012:client/client1"]
}
]
}
iot:Connect
Represents the permission to connect to the AWS IoT message broker. The iot:Connect permission
is checked every time a CONNECT request is sent to the broker. The message broker does not allow
two clients with the same client ID to stay connected at the same time. After the second client
connects, the broker detects this case and disconnects one of the clients. The iot:Connect
permission can be used to ensure only authorized clients can connect using a specific client ID.
iot:Publish
Represents the permission to publish on an MQTT topic. This permission is checked every time a
PUBLISH request is sent to the broker. This can be used to allow clients to publish to specific topic
patterns.
194
AWS IoT Developer Guide
AWS IoT Policies
Note
You must also grant iot:Connect permission to grant iot:Publish permission.
iot:Receive
Represents the permission to receive a message from AWS IoT. The iot:Receive permission is
checked every time a message is delivered to a client. Because this permission is checked on every
delivery, it can be used to revoke permissions to clients that are currently subscribed to a topic.
iot:Subscribe
Represents the permission to subscribe to a topic filter. This permission is checked every time a
SUBSCRIBE request is sent to the broker. This can be used to allow clients to subscribe to topics that
match specific topic patterns.
Note
You must also grant iot:Connect permission to grant iot:Subscribe permission.
iot:DeleteThingShadow
Note
The job execution policy actions apply only for the HTTP TLS endpoint. If you use the MQTT
endpoint, you must use MQTT policy actions defined in this topic.
iot:DescribeJobExecution
Represents the permission to retrieve a job execution for a given thing. The
iot:DescribeJobExecution permission is checked every time a request is made to get the job
execution.
iot:GetPendingJobExecutions
Represents the permission to retrieve the list of jobs that are not in a terminal status for a thing. The
iot:GetPendingJobExecutions permission is checked every time a request is made to retrieve
the list.
iot:UpdateJobExecution
Represents the permission to get and start the next pending job execution for a thing. (That
is, to update a job execution with status QUEUED or IN_PROGRESS to IN_PROGRESS.) The
iot:StartNextPendingJobExecution permission is checked every time a request is made to
start the next pending job execution.
195
AWS IoT Developer Guide
AWS IoT Policies
Action Resources
To specify a resource for an AWS IoT policy action, you must use the ARN of the resource. All resource
ARNs are of the following form:
The following table shows the resource to specify for each action type:
Action Resource
• iot:ClientId: The client ID used to connect to the AWS IoT message broker.
196
AWS IoT Developer Guide
AWS IoT Policies
• aws:SourceIp: The IP address of the client connected to the AWS IoT message broker.
The following AWS IoT policy shows the use of policy variables:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Connect"],
"Resource": [
"arn:aws:iot:us-east-1:123451234510:client/${iot:ClientId}"
]
},
{
"Effect": "Allow",
"Action": ["iot:Publish"],
"Resource": [
"arn:aws:iot:us-east-1:123451234510:topic/my/topic/${iot:ClientId}"
]
}
]
}
In these examples, ${iot:ClientId} is replaced by the ID of the client connected to the AWS IoT
message broker when the policy is evaluated. When you use policy variables like ${iot:ClientId},
you can inadvertently open access to unintended topics. For example, if you use a policy that uses
${iot:ClientId} to specify a topic filter:
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/my/${iot:ClientId}/topic"
]
}
A client can connect using + as the client ID. This would allow the user to subscribe to any topic matching
the topic filter my/+/topic. To protect against such security gaps, use the iot:Connect policy action
to control which client IDs are able to connect. For example, this policy allows only clients whose client
ID is clientid1 to connect:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Connect"],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/clientid1"
]
}
]
}
197
AWS IoT Developer Guide
AWS IoT Policies
Issuer Attributes
The following AWS IoT policy variables allow you to allow or deny permissions based on certificate
attributes set by the certificate issuer.
• iot:Certificate.Issuer.DistinguishedNameQualifier
• iot:Certificate.Issuer.Country
• iot:Certificate.Issuer.Organization
• iot:Certificate.Issuer.OrganizationalUnit
• iot:Certificate.Issuer.State
• iot:Certificate.Issuer.CommonName
• iot:Certificate.Issuer.SerialNumber
• iot:Certificate.Issuer.Title
• iot:Certificate.Issuer.Surname
• iot:Certificate.Issuer.GivenName
• iot:Certificate.Issuer.Initials
• iot:Certificate.Issuer.Pseudonym
• iot:Certificate.Issuer.GenerationQualifier
Subject Attributes
The following AWS IoT policy variables allow you to grant or deny permissions based on certificate
subject attributes set by the certificate issuer.
• iot:Certificate.Subject.DistinguishedNameQualifier
• iot:Certificate.Subject.Country
• iot:Certificate.Subject.Organization
• iot:Certificate.Subject.OrganizationalUnit
• iot:Certificate.Subject.State
• iot:Certificate.Subject.CommonName
• iot:Certificate.Subject.SerialNumber
• iot:Certificate.Subject.Title
• iot:Certificate.Subject.Surname
• iot:Certificate.Subject.GivenName
• iot:Certificate.Subject.Initials
• iot:Certificate.Subject.Pseudonym
• iot:Certificate.Subject.GenerationQualifier
X.509 certificates allow these attributes to contain one or more values. By default, the
policy variables for each multi-value attribute return the first value. For example, the
198
AWS IoT Developer Guide
AWS IoT Policies
For devices registered as things in the AWS IoT Registry, the following policy allows
clients with a thing name registered in the AWS IoT Registry to connect, but restricts the
right to publish to a thing name specific topic to those clients with certificates whose
Certificate.Subject.Organization attribute is set to "Example Corp" or "AnyCompany".
This restriction is accomplished by using a "Condition" field that specifies a condition which
must be met in order to allow the preceding action. In this case the condition is that the
Certificate.Subject.Organization attribute associated with the certificate must include one
of the values listed:
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"iot:Connect"
],
"Resource":[
"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
]
},
{
"Effect":"Allow",
"Action":[
"iot:Publish"
],
"Resource":[
"arn:aws:iot:us-east-1:123456789012:topic/my/topic/
${iot:Connection.Thing.ThingName}"
],
"Condition":{
"ForAllValues:StringEquals":{
"iot:Certificate.Subject.Organization.List":[
"Example Corp",
"AnyCompany"
]
}
}
}
]
}
For devices not registered as things in the AWS IoT Registry, the following policy grants
permission to connect to AWS IoT with client ids "client1", "client2", and "client3", but restricts
the right to publish to a client-id specific topic to those clients with certificates whose
Certificate.Subject.Organization attribute is set to "Example Corp" or "AnyCompany".
This restriction is accomplished by using a "Condition" field that specifies a condition which
must be met in order to allow the preceding action. In this case the condition is that the
199
AWS IoT Developer Guide
AWS IoT Policies
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"iot:Connect"
],
"Resource":[
"arn:aws:iot:us-east-1:123456789012:client/client1",
"arn:aws:iot:us-east-1:123456789012:client/client2",
"arn:aws:iot:us-east-1:123456789012:client/client3"
]
},
{
"Effect":"Allow",
"Action":[
"iot:Publish"
],
"Resource":[
"arn:aws:iot:us-east-1:123456789012:topic/my/topic/${iot:ClientId}"
],
"Condition":{
"ForAllValues:StringEquals":{
"iot:Certificate.Subject.Organization.List":[
"Example Corp",
"AnyCompany"
]
}
}
}
]
}
The following AWS IoT policy variables allow you to grant or deny permissions based on issuer alternate
name attributes set by the certificate issuer.
• iot:Certificate.Issuer.AlternativeName.RFC822Name
• iot:Certificate.Issuer.AlternativeName.DNSName
• iot:Certificate.Issuer.AlternativeName.DirectoryName
• iot:Certificate.Issuer.AlternativeName.UniformResourceIdentifier
• iot:Certificate.Issuer.AlternativeName.IPAddress
The following AWS IoT policy variables allow you to grant or deny permissions based on subject
alternate name attributes set by the certificate issuer.
• iot:Certificate.Subject.AlternativeName.RFC822Name
• iot:Certificate.Subject.AlternativeName.DNSName
• iot:Certificate.Subject.AlternativeName.DirectoryName
• iot:Certificate.Subject.AlternativeName.UniformResourceIdentifier
200
AWS IoT Developer Guide
AWS IoT Policies
• iot:Certificate.Subject.AlternativeName.IPAddress
Other Attributes
You can use iot:Certificate.SerialNumber to allow or deny access to AWS IoT resources based on
the serial number of a certificate. The iot:Certificate.AvailableKeys policy variable contains the
name of all certificate policy variables that contain values.
Wildcards
If wildcard characters are present in certificate attributes, the policy variable is not replaced by the
certificate attribute value, leaving the ${policy-variable} text in the policy document. This
might cause authorization failure.
Array fields
Certificate attributes that contain arrays are limited to five items. Additional items are ignored.
String length
All string values are limited to 1024 characters. If a certificate attribute contains a string longer than
1024 characters, the policy variable is not replaced by the certificate attribute value, leaving the
${policy-variable} in the policy document. This might cause authorization failure.
• iot:Connection.Thing.ThingName
• iot:Connection.Thing.ThingTypeName
• iot:Connection.Thing.Attributes[attributeName]
• iot:Connection.Thing.IsAttached
iot:Connection.Thing.ThingName
This resolves to the name of the thing for which the policy is being evaluated. The thing name is set to
the client ID of the MQTT/WebSocket connection. This policy variable is available only when connecting
over MQTT or MQTT over the WebSocket protocol.
iot:Connection.Thing.ThingTypeName
This resolves to the thing type associated with the thing for which the policy is being evaluated. The
thing name is set to the client ID of the MQTT/WebSocket connection. The thing type name is obtained
by a call to the DescribeThing API. This policy variable is available only when connecting over MQTT
or MQTT over the WebSocket protocol.
201
AWS IoT Developer Guide
AWS IoT Policies
iot:Connection.Thing.Attributes[attributeName]
This resolves to the value of the specified attribute associated with the thing for which the policy is
being evaluated. A thing can have up to 50 attributes. Each attribute is available as a policy variable:
iot:Connection.Thing.Attributes[attributeName] where attributeName is the name of the
attribute. The thing name is set to the client ID of the MQTT/WebSocket connection. This policy variable
is only available when connecting over MQTT or MQTT over the WebSocket protocol.
iot:Connection.Thing.IsAttached
This resolves to true if the thing for which the policy is being evaluated has a certificate or Amazon
Cognito identity attached.
Example Policies
AWS IoT policies are specified in a JSON document. These are the components of an AWS IoT policy:
Version
Client - arn:aws:iot:region:account-id:client/client-id
{
"Version": "2012-10-17",
"Statement": [
{
202
AWS IoT Developer Guide
AWS IoT Policies
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1"
]
}
]
}
The following policy denies permission to connect to AWS IoT with client ids "client1" and "client2", while
allowing devices to connect using a client id that matches the name of a thing registered in the AWS IoT
Registry:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1",
"arn:aws:iot:us-east-1:123456789012:client/client2"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
]
}
]
}
The following policy grants permission for a device to connect using its thing name as the client ID
and to subscribe to the topic filter my/topic/filter. The device must be registered with AWS IoT.
When connecting to AWS IoT, the device must provide the certificate associated with the IoT thing in
the AWS IoT Registry:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/${iot:Connection.Thing.ThingName}"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
203
AWS IoT Developer Guide
AWS IoT Policies
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/my/topic/filter"
]
}
]
}
For devices not registered as things in the AWS IoT Registry, the following policy grants permission
to connect using client id "client1" and to subscribe to topic filter my/topic:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/my/topic"
]
}
]
}
When you specify topic filters in AWS IoT policies for MQTT clients, MQTT wildcard characters "+" and "#"
are treated as literal characters. Their use might result in unexpected behavior.
For devices registered as things in the AWS IoT Registry, the following policy grants permission to
connect to AWS IoT with the client id that matches the thing name, and to subscribe to the topic
filter some/+/topic only:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
204
AWS IoT Developer Guide
AWS IoT Policies
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/some/+/topic"
]
}
]
}
For devices not registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT with client id "client1" and subscribe to the topic filter some/+/topic only:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/some/+/topic"
]
}
]
}
Note
Within a policy, the MQTT wildcard character '+' is treated as a literal, not a wildcard. Attempts
to subscribe to topic filters that match the pattern some/+/topic will fail and cause the client
to disconnect.
You can use "*" as a wildcard in the resource attribute of the policy. For example, if each device in your
account must publish on a unique topic reserved for it alone, use the following policy:
For devices registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT using a client id that matches the thing name and to publish to any topic
prefixed by the thing name:
205
AWS IoT Developer Guide
AWS IoT Policies
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}",
]
}
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/
${iot:Connection.Thing.ThingName}/*"
]
}
]
}
For devices not registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT using client id "client1", "client2", or "client3" and to publish to any topic
prefixed by the client id:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1",
"arn:aws:iot:us-east-1:123456789012:client/client2",
"arn:aws:iot:us-east-1:123456789012:client/client3"
]
}
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/${iot:ClientId}/*"
]
}
]
}
You can also use the "*" wildcard at the end of a topic filter. Using wildcard characters could lead to
granting unintended privileges, so they should only be used after careful consideration. One situation in
which they might be useful is when devices must subscribe to messages with many different topics, for
example if a device must subscribe to reports from temperature sensors in multiple locations.
206
AWS IoT Developer Guide
AWS IoT Policies
For devices registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT using the device's thing name as the client id, and to subscribe to a topic
prefixed by the thing name, followed by "room", followed by any string. (It is expected that these
topics will be, for example, "thing1/room1", "thing1/room2"...):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/
${iot:Connection.Thing.ThingName}/room*"
]
}
]
}
For devices not registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT using client ids "client1", "client2", "client3", and to subscribe to a topic
prefixed by the client id, followed by "room", followed by any string. (It is expected that these topics
will be, for example, "client1/room1", "client1/room2"...):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1",
"arn:aws:iot:us-east-1:123456789012:client/client2",
"arn:aws:iot:us-east-1:123456789012:client/client3"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/${iot:ClientId}/room*"
]
}
207
AWS IoT Developer Guide
AWS IoT Policies
]
}
For devices registered as things in the AWS IoT Registry, the following policy grants permission to
connect to AWS IoT using the device's thing name as the client id, and to subscribe to the topics
"my/topic" and "my/othertopic":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/my/topic",
"arn:aws:iot:us-east-1:123456789012:topicfilter/my/othertopic"
]
}
]
}
For devices not registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT using client id "client1", and to subscribe to the topics "my/topic" and "my/
othertopic":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/my/topic",
"arn:aws:iot:us-east-1:123456789012:topicfilter/my/othertopic"
208
AWS IoT Developer Guide
AWS IoT Policies
]
}
]
}
For devices registered as things in the AWS IoT Registry, the following policy grants permission to
connect to AWS IoT using the device's thing name as the client id and to subscribe to a topic unique
to that thing name/client id:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/my/topic/
${iot:Thing.ThingName}"
]
}
]
}
For devices not registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT using client id "client1", and to publish to a topic unique to that client id:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/my/topic/${iot:ClientId}"
]
209
AWS IoT Developer Guide
AWS IoT Policies
}
]
}
For devices registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT using the device's thing name as the client id and to publish to any topic
prefixed by that thing name/client except for one topic ending with "bar":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/${iot:Thing.ThingName}/*"
]
},
{
"Effect": "Deny",
"Action": [
"iot:Publish"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/${iot:Thing.ThingName}/bar"
]
}
]
}
For devices not registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT using client ids "client1" and "client2" and to publish to any topic prefixed by
the client id used to connect, except for one topic ending with "bar":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1",
"arn:aws:iot:us-east-1:123456789012:client/client2"
210
AWS IoT Developer Guide
AWS IoT Policies
]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/${iot:ClientId}/*"
]
},
{
"Effect": "Deny",
"Action": [
"iot:Publish"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/${iot:ClientId}/bar"
]
}
]
}
For devices registered as things in the AWS IoT Registry, the following policy grants permission to
connect to AWS IoT using the device's thing name as the client id and to subscribe to the topic "my/
topic":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/my/topic"
]
},
{
"Effect": "Deny",
"Action": [
"iot:Publish"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/${iot:Thing.ThingName}/bar"
]
}
]
}
211
AWS IoT Developer Guide
AWS IoT Policies
For devices not registered as things in the AWS IoT Registry, the following policy grants permission
to connect to AWS IoT using client id "client1" and to subscribe to the topic "my/topic":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/my/topic"
]
}
]
}
Thing policy variables are also replaced when a certificate or authenticated Amazon Cognito identity is
attached to a thing. The following policy grants permission to connect to AWS IoT with client id "client1"
and to publish and subscribe to topic "iotmonitor/provisioning/987654321098". It also allows the
certificate holder to subscribe to this same topic.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish",
"iot:Receive"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/iotmonitor/
provisioning/987654321098"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
212
AWS IoT Developer Guide
AWS IoT Policies
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/iotmonitor/
provisioning/987654321098"
]
}
]
}
For the following operations, AWS IoT uses AWS IoT policies attached to Amazon Cognito identities
(through the AttachPolicy API) to scope down the permissions attached to the Amazon Cognito
identity pool with authenticated identities. That means an Amazon Cognito identity needs permission
from the IAM role policy attached to the pool and the AWS IoT policy attached to the Amazon Cognito
identity through the AWS IoT AttachPolicy API.
• iot:Connect
• iot:Publish
• iot:Subscribe
• iot:Receive
• iot:GetThingShadow
• iot:UpdateThingShadow
• iot:DeleteThingShadow
Note
For other AWS IoT operations or for unauthenticated identities, AWS IoT does not scope down
the permissions attached to the Amazon Cognito identity pool role. For both authenticated and
unauthenticated identities, this is the most permissive policy that we recommend attaching to
the Amazon Cognito pool role.
HTTP
To allow unauthenticated Amazon Cognito identities to publish messages over HTTP on a topic specific
to the Cognito identity, attach the following policy to the Amazon Cognito identity pool role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Publish",
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${cognito-
identity.amazonaws.com:sub}"]
}
]
}
To allow authenticated users, attach the preceding policy to the Amazon Cognito identity pool role and
to the Cognito identity using the AWS IoT AttachPrincipalPolicy API.
Note
When authorizing Cognito identities, AWS IoT will consider both these policies and grant the
least privileges specified. An action is only allowed if both the policies allow the requested
action, and if either one of these policies disallow an action, that action will be unauthorized.
MQTT
213
AWS IoT Developer Guide
AWS IoT Policies
To allow unauthenticated Amazon Cognito identities to publish MQTT messages over WebSockets on a
topic specific to the Cognito identity in your account, attach the following policy to the Amazon Cognito
identity pool role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Publish",
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${cognito-
identity.amazonaws.com:sub}"]
},
{
"Effect": "Allow",
"Action": [
"iot:Connect",
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/${cognito-
identity.amazonaws.com:sub}"]
}
]
}
To allow authenticated users, attach the preceding policy to the Amazon Cognito identity pool role and
to the Cognito identity using the AWS IoT AttachPrincipalPolicy API.
Note
When authorizing Cognito identities, AWS IoT will consider both these policies and grant the
least privileges specified. An action is only allowed if both the policies allow the requested
action, and if either one of these policies disallow an action, that action will be unauthorized.
For devices registered in AWS IoT Registry, the following policy grants permission to connect to AWS
IoT with a client id that matches the thing name and to subscribe to and receive messages on one
topic:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/my/topic"
]
},
{
214
AWS IoT Developer Guide
AWS IoT Policies
"Effect": "Allow",
"Action": [
"iot:Receive"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/my/topic"
]
}
]
}
For devices not registered in AWS IoT Registry, the following policy grants permission to connect to
AWS IoT with client id "client1" and to subscribe to and receive messages on one topic:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:client/client1"]
},
{
"Effect": "Allow",
"Action": [
"iot:Subscribe"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topicfilter/my/topic"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Receive"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:topic/my/topic"
]
}
]
}
For devices registered in AWS IoT Registry, the following policy grants permission to connect to AWS
IoT with a client id that matches a thing name, and to publish to a topic whose name is equal to the
certificateId of the certificate the device used to authenticate itself:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Publish"
215
AWS IoT Developer Guide
AWS IoT Policies
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/
${iot:CertificateId}"]
},
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"]
}
]
}
For devices not registered in AWS IoT Registry, the following policy grants permission to connect
to AWS IoT with client ids "client1", "client2", and "client3" and to publish to a topic whose name is
equal to the certificateId of the certificate the device used to authenticate itself:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/
${iot:CertificateId}"]
},
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1",
"arn:aws:iot:us-east-1:123456789012:client/client2",
"arn:aws:iot:us-east-1:123456789012:client/client3"
]
}
]
}
For devices registered in AWS IoT Registry, the following policy grants permission to connect to AWS
IoT with a client id that matches a thing name, and to publish to a topic whose name is equal to the
subject's common name field of the certificate the device used to authenticate itself:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/
${iot:Certificate.Subject.CommonName}"]
216
AWS IoT Developer Guide
AWS IoT Policies
},
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"]
}
]
}
Note
In this example, the certificate's subject common name is used as the topic identifier, with
the assumption that the subject common name is unique for each registered certificate. If
the certificates are shared across multiple devices, the subject common name will be the
same for all the devices sharing this certificate, thereby allowing publish privileges to the
same topic from multiple devices (not recommended).
unregistered devices (13)
For devices not registered in AWS IoT Registry, the following policy grants permission to connect
to AWS IoT with client ids "client1", "client2", and "client3" and to publish to a topic whose name is
equal to the subject's common name field of the certificate the device used to authenticate itself:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/
${iot:Certificate.Subject.CommonName}"]
},
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1",
"arn:aws:iot:us-east-1:123456789012:client/client2",
"arn:aws:iot:us-east-1:123456789012:client/client3"
]
}
]
}
Note
In this example, the certificate's subject common name is used as the topic identifier, with
the assumption that the subject common name is unique for each registered certificate. If
the certificates are shared across multiple devices, the subject common name will be the
same for all the devices sharing this certificate, thereby allowing publish privileges to the
same topic from multiple devices (not recommended).
For devices registered in AWS IoT Registry, the following policy grants permission to connect to AWS
IoT with a client id that matches a thing name, and to publish to a topic whose name is prefixed with
217
AWS IoT Developer Guide
AWS IoT Policies
"admin/" when the certificate used to authenticate the device has its Subject.CommonName.2 field
set to "Administrator":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin/*"],
"Condition": {
"StringEquals": {
"iot:Certificate.Subject.CommonName.2": "Administrator"
}
}
}
]
}
For devices not registered in AWS IoT Registry, the following policy grants permission to connect
to AWS IoT with client ids "client1", "client2", and "client3" and to publish to a topic whose
name is prefixed with "admin/" when the certificate used to authenticate the device has its
Subject.CommonName.2 field set to "Administrator":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1",
"arn:aws:iot:us-east-1:123456789012:client/client2",
"arn:aws:iot:us-east-1:123456789012:client/client3"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin/*"],
"Condition": {
"StringEquals": {
"iot:Certificate.Subject.CommonName.2": "Administrator"
}
}
}
]
218
AWS IoT Developer Guide
AWS IoT Policies
For devices registered in AWS IoT Registry, the following policy allows a device to use a thing
name registered with AWS IoT to publish on a specific topic consisting of "admin/" followed
by the ThingName when the certificate used to authenticate the device has any one of its
Subject.CommonName fields set to "Administrator":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin/
${iot:Connection.Thing.ThingName}"],
"Condition": {
"ForAnyValue:StringEquals": {
"iot:Certificate.Subject.CommonName.List": "Administrator"
}
}
}
]
}
For devices not registered in AWS IoT Registry, the following policy grants permission to connect to
AWS IoT with client ids "client1", "client2", and "client3" and to publish to the topic "admin" when
the certificate used to authenticate the device has any one of its Subject.CommonName fields set to
"Administrator":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1",
"arn:aws:iot:us-east-1:123456789012:client/client2",
"arn:aws:iot:us-east-1:123456789012:client/client3"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish"
219
AWS IoT Developer Guide
IAM IoT Policies
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/admin"],
"Condition": {
"ForAnyValue:StringEquals": {
"iot:Certificate.Subject.CommonName.List": "Administrator"
}
}
}
]
}
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":["iot:Connect"],
"Resource":[ "*" ],
"Condition": {
"Bool": {
"iot:Connection.Thing.IsAttached": ["true"]
}
}
}
]
}
AcceptCertificateTransfer
iot:AcceptCertificateTransfer
arn:aws:iot:region:account-id:cert/cert-id
Note
The AWS account specified in the ARN must be the
account to which the certificate is being transferred.
AddThingToThingGroup
iot:AddThingToThingGroup
arn:aws:iot:region:account-id:thinggroup/thing-
group-name
arn:aws:iot:region:account-id:thing/thing-name
AssociateTargetsWithJob
iot:AssociateTargetsWithJob
none
220
AWS IoT Developer Guide
IAM IoT Policies
or
arn:aws:iot:region:account-id:cert/cert-id
AttachPrincipalPolicyiot:AttachPrincipalPolicy
arn:aws:iot:region:account-id:cert/cert-id
AttachThingPrincipaliot:AttachThingPrincipal
arn:aws:iot:region:account-id:cert/cert-id
CancelCertificateTransfer
iot:CancelCertificateTransfer
arn:aws:iot:region:account-id:cert/cert-id
Note
The AWS account specified in the ARN must be the
account to which the certificate is being transferred.
CancelJobExecution iot:CancelJobExecution
arn:aws:iot:region:account-id:job/job-id
arn:aws:iot:region:account-id:thing/thing-name
ClearDefaultAuthorizer
iot:ClearDefaultAuthorizer
none
CreateCertificateFromCsr
iot:CreateCertificateFromCsr
*
CreateKeysAndCertificate
iot:CreateKeysAndCertificate
*
CreatePolicy iot:CreatePolicy *
CreatePolicyVersion iot:CreatePolicyVersion
arn:aws:iot:region:account-id:policy/policy-name
Note
This must be an AWS IoT policy, not an IAM policy.
arn:aws:iot:region:account-id:rolealias/role-alias-
name
CreateThingGroup iot:CreateThingGrouparn:aws:iot:region:account-id:thinggroup/thing-
group-name
221
AWS IoT Developer Guide
IAM IoT Policies
DeleteCACertificate iot:DeleteCACertificate
arn:aws:iot:region:account-id:cacert/cert-id
DeleteJobExecution iot:DeleteJobExecution
arn:aws:iot:region:account-id:job/job-id
arn:aws:iot:region:account-id:thing/thing-name
DeletePolicyVersion iot:DeletePolicyVersion
arn:aws:iot:region:account-id:policy/policy-name
DeleteRegistrationCode
iot:DeleteRegistrationCode
*
DeleteThingGroup iot:DeleteThingGrouparn:aws:iot:region:account-id:thinggroup/thing-
group-name
DeleteV2LoggingLevel
iot:DeleteV2LoggingLevel
arn:aws:iot:region:account-id:thinggroup/thing-
group-name
DeprecateThingType iot:DeprecateThingType
arn:aws:iot:region:account-id:thingtype/thing-type-
name
DescribeAuthorizer iot:DescribeAuthorizer
arn:aws:iot:region:account-id:authorizer/authorizer-
function-name
(parameter: authorizerName)
none
DescribeCACertificateiot:DescribeCACertificate
arn:aws:iot:region:account-id:cacert/cert-id
DescribeCertificate iot:DescribeCertificate
arn:aws:iot:region:account-id:cert/cert-id
DescribeDefaultAuthorizer
iot:DescribeDefaultAuthorizer
none
DescribeEndpoint iot:DescribeEndpoint*
DescribeEventConfigurations
iot:DescribeEventConfigurations
none
222
AWS IoT Developer Guide
IAM IoT Policies
DescribeJobExecutioniot:DescribeJobExecution
none
DescribeRoleAlias iot:DescribeRoleAliasarn:aws:iot:region:account-id:rolealias/role-alias-
name
DescribeThingGroup iot:DescribeThingGroup
arn:aws:iot:region:account-id:thinggroup/thing-
group-name
DescribeThingRegistrationTask
iot:DescribeThingRegistrationTask
none
DescribeThingType iot:DescribeThingType
arn:aws:iot:region:account-id:thingtype/thing-type-
name
or
arn:aws:iot:region:account-id:thinggroup/thing-
group-name
DetachPrincipalPolicyiot:DetachPrincipalPolicy
arn:aws:iot:region:account-id:cert/cert-id
DetachThingPrincipaliot:DetachThingPrincipal
arn:aws:iot:region:account-id:cert/cert-id
GetEffectivePolicies iot:GetEffectivePolicies
arn:aws:iot:region:account-id:cert/cert-id
GetIndexingConfiguration
iot:GetIndexingConfiguration
none
GetLoggingOptions iot:GetLoggingOptions
*
GetRegistrationCode iot:GetRegistrationCode
*
ListAttachedPolicies iot:ListAttachedPolicies
arn:aws:iot:region:account-id:thinggroup/thing-
group-name
or
arn:aws:iot:region:account-id:cert/cert-id
ListCACertificates iot:ListCACertificates *
ListCertificates iot:ListCertificates *
223
AWS IoT Developer Guide
IAM IoT Policies
ListCertificatesByCA iot:ListCertificatesByCA
*
ListJobExecutionsForJob
iot:ListJobExecutionsForJob
none
ListJobExecutionsForThing
iot:ListJobExecutionsForThing
none
ListOutgoingCertificates
iot:ListOutgoingCertificates
*
ListPolicies iot:ListPolicies *
ListPolicyPrincipals iot:ListPolicyPrincipals
arn:aws:iot:region:account-id:policy/policy-name
ListPolicyVersions iot:ListPolicyVersionsarn:aws:iot:region:account-id:policy/policy-name
ListPrincipalPolicies iot:ListPrincipalPolicies
arn:aws:iot:region:account-id:cert/cert-id
ListPrincipalThings iot:ListPrincipalThingsarn:aws:iot:region:account-id:cert/cert-id
ListTargetsForPolicy iot:ListTargetsForPolicy
arn:aws:iot:region:account-id:policy/policy-name
ListThingGroupsForThing
iot:ListThingGroupsForThing
arn:aws:iot:region:account-id:thing/thing-name
ListThingPrincipals iot:ListThingPrincipalsarn:aws:iot:region:account-id:thing/thing-name
ListThingRegistrationTaskReports
iot:ListThingRegistrationTaskReports
none
ListThingRegistrationTasks
iot:ListThingRegistrationTasks
none
ListThingTypes iot:ListThingTypes *
ListThings iot:ListThings *
ListThingsInThingGroup
iot:ListThingsInThingGroup
arn:aws:iot:region:account-id:thinggroup/thing-
group-name
ListTopicRules iot:ListTopicRules *
ListV2LoggingLevels iot:ListV2LoggingLevels
none
RegisterCACertificateiot:RegisterCACertificate
*
RegisterCertificate iot:RegisterCertificate*
RejectCertificateTransfer
iot:RejectCertificateTransfer
arn:aws:iot:region:account-id:cert/cert-id
224
AWS IoT Developer Guide
IAM IoT Policies
RemoveThingFromThingGroup
iot:RemoveThingFromThingGroup
arn:aws:iot:region:account-id:thinggroup/thing-
group-name
arn:aws:iot:region:account-id:thing/thing-name
SetDefaultAuthorizeriot:SetDefaultAuthorizer
arn:aws:iot:region:account-id:authorizer/authorizer-
function-name
SetDefaultPolicyVersion
iot:SetDefaultPolicyVersion
arn:aws:iot:region:account-id:policy/policy-name
SetLoggingOptions iot:SetLoggingOptions
arn:aws:iot:region:account-id:role/role-name
SetV2LoggingLevel iot:SetV2LoggingLevel
arn:aws:iot:region:account-id:thinggroup/thing-
group-name
SetV2LoggingOptionsiot:SetV2LoggingOptions
arn:aws:iot:region:account-id:role/role-name
StartThingRegistrationTask
iot:StartThingRegistrationTask
none
StopThingRegistrationTask
iot:StopThingRegistrationTask
none
TestAuthorization iot:TestAuthorizationarn:aws:iot:region:account-id:cert/cert-id
TestInvokeAuthorizeriot:TestInvokeAuthorizer
none
TransferCertificate iot:TransferCertificatearn:aws:iot:region:account-id:cert/cert-id
UpdateAuthorizer iot:UpdateAuthorizerarn:aws:iot:region:account-
id:authorizerfunction/authorizer-function-name
UpdateCACertificate iot:UpdateCACertificate
arn:aws:iot:region:account-id:cacert/cert-id
UpdateCertificate iot:UpdateCertificatearn:aws:iot:region:account-id:cert/cert-id
UpdateEventConfigurations
iot:UpdateEventConfigurations
none
UpdateIndexingConfiguration
iot:UpdateIndexingConfiguration
none
UpdateThingGroup iot:UpdateThingGroup
arn:aws:iot:region:account-id:thinggroup/thing-
group-name
UpdateThingGroupsForThing
iot:UpdateThingGroupsForThing
arn:aws:iot:region:account-id:thing/thing-name
225
AWS IoT Developer Guide
Authorizing Direct Calls to AWS Services
operations allow you to create things, certificates, policies, and rules. Data operations send data over
MQTT or HTTP protocols. The following table describes these templates.
The credentials provider authenticates a caller using an X.509 certificate and issues a temporary, limited-
privilege security token. The token can be used to sign and authenticate any AWS request. This way
of authenticating your AWS requests requires you to create and configure an AWS Identity and Access
Management (IAM) role and attach appropriate IAM policies to the role so that the credentials provider
can assume the role on your behalf.
226
AWS IoT Developer Guide
How to Use a Certificate to Get a Security Token
1. The AWS IoT device makes an HTTPS request to the credentials provider for a security token. The
request includes the device X.509 certificate for authentication.
2. The credentials provider forwards the request to the AWS IoT authentication and authorization
module to validate the certificate and verify that it has permission to request the security token.
3. If the certificate is valid and has permission to request a security token, the AWS IoT authentication
and authorization module returns success. Otherwise, it sends an exception to the device.
4. After successfully validating the certificate, the credentials provider invokes the AWS Security Token
Service (AWS STS) to assume the IAM role that you created for it.
5. AWS STS returns a temporary, limited-privilege security token to the credentials provider.
6. The credentials provider returns the security token to the device.
7. The device uses the security token to sign an AWS request with AWS Signature Version 4.
8. The requested service invokes IAM to validate the signature and authorize the request against access
policies attached to the IAM role that you created for the credentials provider.
9. If IAM validates the signature successfully and authorizes the request, the request succeeds.
Otherwise, IAM sends an exception.
The following section describes how to use a certificate to get a security token. It assumes that you have
already registered a device and created and activated your own certificate for it.
227
AWS IoT Developer Guide
How to Use a Certificate to Get a Security Token
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Principal": {"Service": "credentials.iot.amazonaws.com"},
"Action": "sts:AssumeRole"
}
}
For each AWS service that you want to call, attach an access policy to the role. The credentials
provider supports the following policy variables:
• credentials-iot:ThingName
• credentials-iot:ThingTypeName
• credentials-iot:AwsCertificateId
When the device provides the thing name in its request to an AWS service, the credentials
provider adds credentials-iot:ThingName and credentials-iot:ThingTypeName
as context variables to the security token. The credentials provider provides credentials-
iot:AwsCertificateId as a context variable even if the device doesn't provide the thing name
in the request. You pass the thing name as the value of the x-amzn-iot-thingname HTTP request
header.
These three variables work for IAM policies only, not AWS IoT policies.
2. Make sure that the user who performs the next step (creating a role alias) has permission to pass this
newly created role to AWS IoT. The following policy gives both iam:GetRole and iam:PassRole
permissions to an AWS user. The iam:GetRole permission enables the user to get information
about the role that you've just created. The iam:PassRole permission enables the user to pass the
role to another AWS service.
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": [
"iam:GetRole",
"iam:PassRole"
],
"Resource": "arn:aws:iam::your aws account id:role/your role name"
}
}
3. Create an AWS IoT role alias. The device that is going to make direct calls to AWS services must
know which role ARN to use when connecting to AWS IoT. Hard-coding the role ARN is not a good
solution because it requires you to update the device whenever the role ARN changes. A better
solution is to use the CreateRoleAlias API to create a role alias that points to the role ARN. If the
role ARN changes, you simply update the role alias. No change is required on the device. This API
takes the following parameters:
roleAlias
Mandatory. An arbitrary string identifying the role alias. It serves as the primary key in the role
alias data model. It contains 1-128 characters and must include only alphanumeric characters
and the =,@, and - symbols. Uppercase and lowercase alphabetic characters are allowed.
roleArn
Mandatory. The ARN of the role to which the role alias refers.
228
AWS IoT Developer Guide
How to Use a Certificate to Get a Security Token
credentialDurationInSeconds
Optional. How long (in seconds) the credential is valid. The minimum value is 900 seconds (15
minutes). The maximum value is 3,600 seconds (60 minutes). The default value is 3,600 seconds.
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": "iot:AssumeRoleWithCertificate",
"Resource": "arn:aws:iot:your region:your_aws_account_id:rolealias/your role
alias"
}
}
5. Make an HTTPS request to the credentials provider to get a security token. Supply the following
information.
• Certificate: Because this is an HTTP request over TLS mutual authentication, you have to provide
the certificate and the corresponding private key to your client while making the request. Use the
same certificate and private key that you used when you registered your certificate with AWS IoT.
To make sure your device is communicating with AWS IoT (and not a service impersonating
it), refer to the documentation on Server Authentication in AWS IoT Core, follow the links to
download the appropriate CA certificates, and then copy them to your device.
• RoleAlias: The name of the role alias that you created for the credentials provider.
• ThingName: The thing name that you created when you registered your AWS IoT thing. This is
passed as the value of the x-amzn-iot-thingname HTTP header. This value is required only if
you are using thing attributes as policy variables in AWS IoT or IAM policies.
Run the following command in the AWS CLI to obtain the credentials provider endpoint for your
AWS account. For more information about this API, see DescribeEndpoint.
The following JSON object is sample output of the describe-endpoint command. It contains the
endpointAddress that you use to request a security token.
{
"endpointAddress": "your_aws_account_specific_prefix.credentials.iot.your
region.amazonaws.com"
}
Use the endpoint to make an HTTPS request to the credentials provider to return a security token.
The following sample uses curl but you can use any HTTP client.
curl --cert your certficate --key your device certificate key pair -H "x-amzn-iot-
thingname: your thing name" --cacert AmazonRootCA1.pem https://your endpoint/role-
aliases/your role alias/credentials
229
AWS IoT Developer Guide
Cross Account Access
This command returns a security token object that contains an accessKeyId, a secretAccessKey,
a sessionToken, and an expiration. The following JSON object is sample output of the
curlcommand.
You can then use the accessKeyId, secretAccessKey, and sessionToken values to sign
requests to AWS services. For an end-to-end demonstration of a specific use case, see How to
Eliminate the Need for Hard-Coded AWS Credentials in Devices by Using the AWS IoT Credential
Provider.
First, create a customer managed IAM policy as described in Creating IAM Policies, just like you would for
other users and certificates in your AWS account.
For devices registered in AWS IoT Registry, the following policy grants permission to devices to use
thing names registered in your account's (123456789012) AWS IoT Registry to connect to AWS IoT
and to publish to a thingName specific topic whose name is prefixed with "my/topic/":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:client/
${iot:Connection.Thing.ThingName}"]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/my/topic/
${iot:Connection.Thing.ThingName}"],
}
]
}
For devices not registered in AWS IoT Registry, the following policy grants permission to a device
to use the thing name "client1" registered in your account's (123456789012) AWS IoT Registry to
230
AWS IoT Developer Guide
Transport Security
connect to AWS IoT and to publish to a client id specific topic whose name is prefixed with "my/
topic/":
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": [
"arn:aws:iot:us-east-1:123456789012:client/client1"
]
},
{
"Effect": "Allow",
"Action": [
"iot:Publish"
],
"Resource": ["arn:aws:iot:us-east-1:123456789012:topic/my/topic/
${iot:ClientId}"]
}
]
}
Next, follow the steps in Creating a Role to Delegate Permissions to an IAM User. Enter the account id of
the AWS account with which you want to share access. Then, in the final step, attach the policy you just
created to the role. If, at a later time, you need to modify the AWS account ID to which you are granting
access, you can use the following trust policy format to do so:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam:us-east-1:567890123456:user:MyUser" },
"Action": "sts:AssumeRole",
}
]
}
Transport Security
The AWS IoT message broker and Device Shadow service encrypt all communication with TLS version 1.2.
TLS is used to ensure the confidentiality of the application protocols (MQTT, HTTP) supported by AWS
IoT. TLS is available in a number of programming languages and operating systems.
For MQTT, TLS encrypts the connection between the device and the broker. TLS client authentication is
used by AWS IoT to identify devices. For HTTP, TLS encrypts the connection between the device and the
broker. Authentication is delegated to AWS Signature Version 4.
• ECDHE-ECDSA-AES128-GCM-SHA256 (recommended)
231
AWS IoT Developer Guide
TLS Cipher Suite Support
• ECDHE-RSA-AES128-GCM-SHA256 (recommended)
• ECDHE-ECDSA-AES128-SHA256
• ECDHE-RSA-AES128-SHA256
• ECDHE-ECDSA-AES128-SHA
• ECDHE-RSA-AES128-SHA
• ECDHE-ECDSA-AES256-GCM-SHA384
• ECDHE-RSA-AES256-GCM-SHA384
• ECDHE-ECDSA-AES256-SHA384
• ECDHE-RSA-AES256-SHA384
• ECDHE-RSA-AES256-SHA
• ECDHE-ECDSA-AES256-SHA
• AES128-GCM-SHA256
• AES128-SHA256
• AES128-SHA
• AES256-GCM-SHA384
• AES256-SHA256
• AES256-SHA
232
AWS IoT Developer Guide
Protocols
The message broker, in turn, sends the message to all clients that have registered to receive messages for
that topic. The act of sending the message is referred to as publishing. The act of registering to receive
messages for a topic filter is referred to as subscribing.
The topic namespace is isolated for each AWS account and region pair. For example, the Sensor/temp/
room1 topic for an AWS account is independent from the Sensor/temp/room1 topic for another AWS
account. This is true of regions, too. The Sensor/temp/room1 topic in the same AWS account in us-
east-1 is independent from the same topic in us-east-2. AWS IoT does not support sending and receiving
messages across AWS accounts and regions.
The message broker maintains a list of all client sessions and the subscriptions for each session. When a
message is published on a topic, the broker checks for sessions with subscriptions that map to the topic.
The broker then forwards the publish message to all sessions that have a currently connected client.
If your use case does not require IoT, see AWS Messaging for information about other AWS messaging
services that better fit your requirements.
Protocols
The message broker supports the use of the MQTT protocol to publish and subscribe and the HTTPS
protocol to publish. Both protocols are supported through IP version 4 and IP version 6. The message
broker also supports MQTT over the WebSocket protocol.
Protocol/Port Mappings
The following table shows each protocol supported by AWS IoT, the authentication method, and port
used for each protocol.
†
Clients that connect on port 443 with X.509 client certificate authentication must implement the
Application Layer Protocol Negotiation (ALPN) TLS extension and use the ALPN ProtocolName listed
above in the ALPN ProtocolNameList sent by the client as part of the ClientHello message.
233
AWS IoT Developer Guide
MQTT
MQTT
MQTT is a widely adopted, lightweight messaging protocol designed for constrained devices. For more
information, see MQTT.
Although the AWS IoT message broker implementation is based on MQTT version 3.1.1, it deviates from
the specification as follows:
• In AWS IoT, subscribing to a topic with Quality of Service (QoS) 0 means a message is delivered zero or
more times. A message might be delivered more than once. Messages delivered more than once might
be sent with a different packet ID. In these cases, the DUP flag is not set.
• AWS IoT does not support publishing and subscribing with QoS 2. The AWS IoT message broker does
not send a PUBACK or SUBACK when QoS 2 is requested.
• When responding to a connection request, the message broker sends a CONNACK message. This
message contains a flag to indicate if the connection is resuming a previous session. The value of this
flag might be incorrect if two MQTT clients connect with the same client ID simultaneously.
• When a client subscribes to a topic, there might be a delay between the time the message broker
sends a SUBACK and the time the client starts receiving new matching messages.
• The MQTT specification provides a provision for the publisher to request that the broker retain the last
message sent to a topic and send it to all future topic subscribers. AWS IoT does not support retained
messages. If a request is made to retain messages, the connection is disconnected.
• The message broker uses the client ID to identify each client. The client ID is passed in from the client
to the message broker as part of the MQTT payload. Two clients with the same client ID are not
allowed to be connected concurrently to the message broker. When a client connects to the message
broker using a client ID that another client is using, a CONNACK message is sent to both clients and the
currently connected client is disconnected.
• On rare occasions, the message broker might resend the same logical PUBLISH message with a
different packet ID.
• The message broker does not guarantee the order in which messages and ACK are received.
Topics
The message broker uses topics to route messages from publishing clients to subscribing clients. The
forward slash (/) is used to separate topic hierarchy.
Note
We do not recommend using personally identifiable information in your topics.
The following table lists the wildcards that can be used in the topic filter when you subscribe.
Topic Wildcards
Wildcard Description
234
AWS IoT Developer Guide
MQTT
Reserved Topics
Except for those topics listed here, any topics beginning with $ are considered reserved and are not
supported for publishing and subscribing. Any attempts to publish or subscribe to topics beginning with
$ result in a terminated connection.
235
AWS IoT Developer Guide
MQTT
236
AWS IoT Developer Guide
MQTT
237
AWS IoT Developer Guide
HTTP
You create an MQTT persistent session by sending a CONNECT message setting the cleanSession
flag to 0. If no session exists for the client sending the CONNECT message, a new persistent session is
created. If a session already exists for the client, it is resumed.
Devices need to look at the sessionPresent attribute in the CONNACK (Connection Acknowledged)
message to determine if a persistent session is present. If sessionPresent is set to 1, a persistent
session is present and stored messages are delivered to the client. If sessionPresent is set to 0, no
persistent session is present and the client must re-subscribe to its topic filters.
Persistent sessions have a default expiry period of 1 hour. The expiry period begins when the message
broker detects that a client disconnects (MQTT disconnect or timeout). The persistent session expiry
period can be increased through the standard limit increase process. If a client has not resumed its
session within the expiry period, the session is terminated and any associated stored messages are
discarded. The expiry period is approximate, sessions might be persisted for up to 30 minutes longer (but
not less) than the configured duration. For more information, see AWS Service Limits. Any messages
stored for persistent sessions will be billed at the standard messaging rate. For more information see,
AWS IoT Pricing.
HTTP
The message broker supports clients connecting with the HTTP protocol using a REST
API. Clients can publish by sending a POST message to <AWS IoT Endpoint>/
topics/<url_encoded_topic_name>?qos=1".
For example, you can use curl to emulate sending a message. For example:
--tlsv1.2
Use TLSv1.2 (SSL). curl must be installed with OpenSSL and you must use version 1.2 of TLS.
238
AWS IoT Developer Guide
MQTT over the WebSocket Protocol
--cacert <filename>
The URL. In this case, the REST API endpoint for the thing.
To find the endpoint for a thing, in the AWS IoT console, choose Registry to expand your choices.
Choose Things, choose the thing, and then choose Interact.) After the endpoint add the port (:8443)
followed by the keyword "topics", the topic and, finally, specify the quality of service in a query
string (?qos=1).
A WebSocket connection is initiated on a client by sending an HTTP GET request. The URL you use is of
the following form:
wss://<endpoint>.iot.<region>.amazonaws.com/mqtt
wss
Your AWS account-specific AWS IoT endpoint. You can use the AWS IoT CLI describe-endpoint
command to find this endpoint.
region
Specifies you are sending MQTT messages over the WebSocket protocol.
When the server responds, the client sends an upgrade request to indicate to the server it will
communicate using the WebSocket protocol. After the server acknowledges the upgrade request, all
239
AWS IoT Developer Guide
MQTT over the WebSocket Protocol
communication is performed using the WebSocket protocol. The WebSocket implementation you use
acts as a transport protocol. The data you send over the WebSocket protocol are MQTT messages.
The following JavaScript defines some utility functions used in generating a Signature Version 4 request.
/**
* utilities to do sigv4
* @class SigV4Utils
*/
function SigV4Utils() {}
240
AWS IoT Developer Guide
MQTT over the WebSocket Protocol
2. Create a string to sign, generate a signing key, and sign the string.
Take the canonical URL you created in the previous step and assemble it into a string to sign. You
do this by creating a string composed of the hashing algorithm, the date, the credential scope, and
the SHA of the canonical request. Next, generate the signing key and sign the string, as shown in the
following JavaScript code.
The following JavaScript code shows how to add the signing information to the query string.
4. If you have session credentials (from an STS server, AssumeRole, or Amazon Cognito), append the
session token to the end of the URL string after signing:
canonicalQuerystring += '&X-Amz-Security-Token=' +
encodeURIComponent(credentials.sessionToken);
241
AWS IoT Developer Guide
MQTT over the WebSocket Protocol
The following JavaScript code shows how to create a Paho MQTT client and call CONNECT to
AWS IoT. The endpoint argument is your AWS account-specific endpoint. The clientId is a text
identifier that is unique among all clients simultaneously connected in your AWS account.
• Node.js
• iOS
• Android
For a reference implementation for connecting a web application to AWS IoT using MQTT over the
WebSocket protocol, see AWS Labs WebSocket sample.
If you are using a programming or scripting language that is not currently supported, any existing
WebSocket library can be used as long as the initial WebSocket upgrade request (HTTP POST) is
signed using Signature Version 4. Some MQTT clients, such as Eclipse Paho for JavaScript, support the
WebSocket protocol natively.
242
AWS IoT Developer Guide
Granting AWS IoT the Required Access
Your rules can use MQTT messages that pass through the publish/subscribe Message Broker for AWS
IoT (p. 233) or, using the Basic Ingest (p. 319) feature, you can securely send device data to the AWS
services listed above without incurring messaging costs. (The Basic Ingest (p. 319) feature optimizes
data flow by removing the publish/subscribe message broker from the ingestion path, so it is more cost
effective while keeping the security and data processing features of AWS IoT.)
Before AWS IoT can perform these actions, you must grant it permission to access your AWS resources on
your behalf. When the actions are performed, you incur the standard charges for the AWS services you
use.
1. Save the following trust policy document, which grants AWS IoT permission to assume the role, to a
file called iot-role-trust.json:
{
"Version":"2012-10-17",
"Statement":[{
"Effect": "Allow",
"Principal": {
243
AWS IoT Developer Guide
Granting AWS IoT the Required Access
"Service": "iot.amazonaws.com"
},
"Action": "sts:AssumeRole"
}]
}
Use the create-role command to create an IAM role specifying the iot-role-trust.json file:
{
"Role": {
"AssumeRolePolicyDocument": "url-encoded-json",
"RoleId": "AKIAIOSFODNN7EXAMPLE",
"CreateDate": "2015-09-30T18:43:32.821Z",
"RoleName": "my-iot-role",
"Path": "/",
"Arn": "arn:aws:iam::123456789012:role/my-iot-role"
}
}
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "dynamodb:*",
"Resource": "*"
}]
}
This JSON is an example policy document that grants AWS IoT administrator access to DynamoDB.
Use the create-policy command to grant AWS IoT access to your AWS resources upon assuming the
role, passing in the iot-policy.json file:
For more information about how to grant access to AWS services in policies for AWS IoT, see
Creating an AWS IoT Rule (p. 245).
The output of the create-policy command contains the ARN of the policy. You need to attach the
policy to a role.
{
"Policy": {
"PolicyName": "my-iot-policy",
"CreateDate": "2015-09-30T19:31:18.620Z",
"AttachmentCount": 0,
"IsAttachable": true,
"PolicyId": "ZXR6A36LTYANPAI7NJ5UV",
"DefaultVersionId": "v1",
"Path": "/",
"Arn": "arn:aws:iam::123456789012:policy/my-iot-policy",
244
AWS IoT Developer Guide
Pass Role Permissions
"UpdateDate": "2015-09-30T19:31:18.620Z"
}
}
When creating or replacing a rule you are, in effect, passing a role to the rules engine. The user
performing this operation requires the iam:PassRole permission. To ensure you have this permission,
create a policy that grants the iam:PassRole permission and attach it to your IAM user. The following
policy shows how to allow iam:PassRole permission for a role.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1",
"Effect": "Allow",
"Action": [
"iam:PassRole"
],
"Resource": [
"arn:aws:iam::123456789012:role/myRole"
]
}
]
}
In this policy example, the iam:PassRole permission is granted for the role myRole. The role is
specified using the role's ARN. You must attach this policy to your IAM user or role to which your user
belongs. For more information, see Working with Managed Policies.
Note
Lambda functions use resource-based policy, where the policy is attached directly to the
Lambda function itself. When creating a rule that invokes a Lambda function, you do not pass
a role, so the user creating the rule does not need the iam:PassRole permission. For more
information about Lambda function authorization, see Granting Permissions Using a Resource
Policy.
Rule name
245
AWS IoT Developer Guide
Creating an AWS IoT Rule
Optional description
A simplified SQL syntax to filter messages received on an MQTT topic and push the data elsewhere.
For more information, see AWS IoT SQL Reference (p. 267).
SQL version
The version of the SQL rules engine to use when evaluating the rule. Although this property is
optional, we strongly recommend that you specify the SQL version. If this property is not set, the
default, 2015-10-08, is used. For more information, see SQL Versions (p. 316).
One or more actions
The actions AWS IoT performs when executing the rule. For example, you can insert data into a
DynamoDB table, write data to an Amazon S3 bucket, publish to an Amazon SNS topic, or invoke a
Lambda function.
An error action
The action AWS IoT performs when it is unable to perform a rule's action.
When you create a rule, be aware of how much data you are publishing on topics. If you create rules
that include a wildcard topic pattern, they might match a large percentage of your messages, and you
might need to increase the capacity of the AWS resources used by the target actions. Also, if you create
a republish rule that includes a wildcard topic pattern, you can end up with a circular rule that causes an
infinite loop.
Note
Creating and updating rules are administrator-level actions. Any user who has permission to
create or update rules is able to access data processed by the rules.
The following is an example payload file with a rule that inserts all messages sent to the iot/test topic
into the specified DynamoDB table. The SQL statement filters the messages and the role ARN grants
AWS IoT permission to write to the DynamoDB table.
{
"sql": "SELECT * FROM 'iot/test'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"dynamoDB": {
"tableName": "my-dynamodb-table",
"roleArn": "arn:aws:iam::123456789012:role/my-iot-role",
"hashKeyField": "topic",
"hashKeyValue": "${topic(2)}",
"rangeKeyField": "timestamp",
"rangeKeyValue": "${timestamp()}"
}
}]
}
246
AWS IoT Developer Guide
Creating an AWS IoT Rule
The following is an example payload file with a rule that inserts all messages sent to the iot/test topic
into the specified S3 bucket. The SQL statement filters the messages, and the role ARN grants AWS IoT
permission to write to the Amazon S3 bucket.
{
"awsIotSqlVersion": "2016-03-23",
"sql": "SELECT * FROM 'iot/test'",
"ruleDisabled": false,
"actions": [
{
"s3": {
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_s3",
"bucketName": "my-bucket",
"key": "myS3Key"
}
}
]
}
The following is an example payload file with a rule that pushes data to Amazon Elasticsearch Service:
{
"sql":"SELECT *, timestamp() as timestamp FROM 'iot/test'",
"ruleDisabled":false,
"awsIotSqlVersion": "2016-03-23",
"actions":[
{
"elasticsearch":{
"roleArn":"arn:aws:iam::123456789012:role/aws_iot_es",
"endpoint":"https://my-endpoint",
"index":"my-index",
"type":"my-type",
"id":"${newuuid()}"
}
}
]
}
The following is an example payload file with a rule that invokes a Lambda function:
{
"sql": "expression",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"lambda": {
"functionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-lambda-
function"
}
}]
}
The following is an example payload file with a rule that publishes to an Amazon SNS topic:
{
"sql": "expression",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"sns": {
"targetArn": "arn:aws:sns:us-west-2:123456789012:my-sns-topic",
247
AWS IoT Developer Guide
Creating an AWS IoT Rule
"roleArn": "arn:aws:iam::123456789012:role/my-iot-role"
}
}]
}
The following is an example payload file with a rule that republishes on a different MQTT topic:
{
"sql": "expression",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"republish": {
"topic": "my-mqtt-topic",
"roleArn": "arn:aws:iam::123456789012:role/my-iot-role"
}
}]
}
The following is an example payload file with a rule that pushes data to an Amazon Kinesis Data Firehose
stream:
{
"sql": "SELECT * FROM 'my-topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"firehose": {
"roleArn": ""arn:aws:iam::123456789012:role/my-iot-role",
"deliveryStreamName": "my-stream-name"
}
}]
}
The following is an example payload file with a rule that uses the Amazon Machine Learning
machinelearning_predict function to republish to a topic if the data in the MQTT payload is
classified as a 1.
{
"sql": "SELECT * FROM 'iot/test' where machinelearning_predict('my-model',
'arn:aws:iam::123456789012:role/my-iot-aml-role', *).predictedLabel=1",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"republish": {
"roleArn": "arn:aws:iam::123456789012:role/my-iot-role",
"topic": "my-mqtt-topic"
}
}]
}
The following is an example payload file with a rule that publishes messages to a Salesforce IoT Cloud
input stream.
{
"sql": "expression",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"salesforce": {
248
AWS IoT Developer Guide
Viewing Your Rules
"token": "ABCDEFGHI123456789abcdefghi123456789",
"url": "https://ingestion-cluster-id.my-env.sfdcnow.com/streams/stream-id/
connection-id/my-event"
}
}]
}
The following is an example payload file with a rule that starts an execution of a Step Functions state
machine.
{
"sql": "expression",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"stepFunctions": {
"stateMachineName": "myCoolStateMachine",
"executionNamePrefix": "coolRunning",
"roleArn": "arn:aws:iam::123456789012:role/my-iot-role"
}
}]
}
Deleting a Rule
When you are finished with a rule, you can delete it.
249
AWS IoT Developer Guide
CloudWatch Alarm Action
Note
The AWS IoT rules engine might make multiple attempts to perform an action in case of
intermittent errors. If all attempts fail, the message is discarded and the error is available in
your CloudWatch logs. You can specify an error action for each rule that is invoked after a failure
occurs. For more information, see Error Handling (Error Action) (p. 265).
The CloudWatch alarm action allows you to change CloudWatch alarm state. You can specify the
state change reason and value in this call.
more info (1)
When creating an AWS IoT rule with a CloudWatch alarm action, you must specify the following
information:
roleArn
The value of the alarm state. Acceptable values are OK, ALARM, INSUFFICIENT_DATA.
Note
Make sure the role associated with the rule has a policy that grants the
cloudwatch:SetAlarmState permission.
250
AWS IoT Developer Guide
CloudWatch Metric Action
The following JSON example shows how to define a CloudWatch alarm action in an AWS IoT rule:
{
"topicRulePayload": {
"sql": "SELECT * FROM 'some/topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"cloudwatchAlarm": {
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_cw",
"alarmName": "IotAlarm",
"stateReason": "Temperature stabilized.",
"stateValue": "OK"
}
}]
}
}
The CloudWatch metric action allows you to capture a CloudWatch metric. You can specify the
metric namespace, name, value, unit, and timestamp.
more info (2)
When creating an AWS IoT rule with a CloudWatch metric action, you must specify the following
information:
roleArn
Note
Make sure that the role associated with the rule has a policy granting the
cloudwatch:PutMetricData permission.
The following JSON example shows how to define a CloudWatch metric action in an AWS IoT rule:
251
AWS IoT Developer Guide
DynamoDB Action
"topicRulePayload": {
"sql": "SELECT * FROM 'some/topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"cloudwatchMetric": {
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_cw",
"metricNamespace": "IotNamespace",
"metricName": "IotMetric",
"metricValue": "1",
"metricUnit": "Count",
"metricTimestamp": "1456821314"
}
}]
}
}
DynamoDB Action
DynamoDB Action
The dynamoDB action allows you to write all or part of an MQTT message to a DynamoDB table.
more info (3)
When creating a DynamoDB rule, you must specify the following information:
hashKeyType
The data type of the hash key (also called the partition key). Valid values are: "STRING" or
"NUMBER".
hashKeyField
The name of the hash key (also called the partition key).
hashKeyValue
Optional. The data type of the range key (also called the sort key). Valid values are: "STRING"
or "NUMBER".
rangeKeyField
Optional. The name of the range key (also called the sort key).
rangeKeyValue
Optional. The type of operation to be performed. This follows the substitution template, so
it can be ${operation}, but the substitution must result in one of the following: INSERT,
UPDATE, or DELETE.
payloadField
Optional. The name of the field where the payload is written. If this value is omitted, the
payload is written to the payload field.
252
AWS IoT Developer Guide
DynamoDBv2 Action
table
The IAM role that allows access to the DynamoDB table. At a minimum, the role must allow the
dynamoDB:PutItem IAM action.
The data written to the DynamoDB table is the result from the SQL statement of the rule. The
hashKeyValue and rangeKeyValue fields are usually composed of expressions (for example,
"${topic()}" or "${timestamp()}").
Note
Non-JSON data is written to DynamoDB as binary data. The DynamoDB console displays the
data as Base64-encoded text.
Make sure that the role associated with the rule has a policy granting the
dynamodb:PutItem permission.
The following JSON example shows how to define a dynamoDB action in an AWS IoT rule:
{
"topicRulePayload": {
"ruleDisabled": false,
"sql": "SELECT * AS message FROM 'some/topic'",
"description": "A test Dynamo DB rule",
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"dynamoDB": {
"hashKeyField": "key",
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_dynamoDB",
"tableName": "my_ddb_table",
"hashKeyValue": "${topic()}",
"rangeKeyValue": "${timestamp()}",
"rangeKeyField": "timestamp"
}
}]
}
}
For more information, see the Amazon DynamoDB Getting Started Guide.
DynamoDBv2 Action
DynamoDBv2 Action
The dynamoDBv2 action allows you to write all or part of an MQTT message to a DynamoDB table.
Each attribute in the payload is written to a separate column in the DynamoDB database.
more info (4)
When creating a DynamoDB rule, you must specify the following information:
roleARN
The IAM role that allows access to the DynamoDB table. At a minimum, the role must allow the
dynamoDB:PutItem IAM action.
tableName
253
AWS IoT Developer Guide
Elasticsearch Action
Note
The MQTT message payload must contain a root-level key that matches the table's primary
partition key and a root-level key that matches the table's primary sort key, if one is
defined.
The data written to the DynamoDB table is the result from the SQL statement of the rule.
Note
Make sure that the role associated with the rule has a policy granting the
dynamodb:PutItem permission.
The following JSON example shows how to define a dynamoDB action in an AWS IoT rule:
{
"topicRulePayload": {
"sql": "SELECT * AS message FROM 'some/topic'",
"ruleDisabled": false,
"description": "A test DynamoDBv2 rule",
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"dynamoDBv2": {
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_dynamoDBv2",
"putItem": {
"tableName": "my_ddb_table"
}
}
}]
}
}
For more information, see the Amazon DynamoDB Getting Started Guide.
Elasticsearch Action
Elasticsearch Action
The elasticsearch action allows you to write data from MQTT messages to an Amazon
Elasticsearch Service domain. Data in Elasticsearch can then be queried and visualized by using tools
like Kibana.
more info (5)
When you create an AWS IoT rule with an elasticsearch action, you must specify the following
information:
endpoint
254
AWS IoT Developer Guide
Firehose Action
Note
Make sure that the role associated with the rule has a policy granting the es:ESHttpPut
permission.
The following JSON example shows how to define an elasticsearch action in an AWS IoT rule:
{
"topicRulePayload":{
"sql":"SELECT *, timestamp() as timestamp FROM 'iot/test'",
"ruleDisabled":false,
"awsIotSqlVersion": "2016-03-23",
"actions":[{
"elasticsearch":{
"roleArn":"arn:aws:iam::123456789012:role/aws_iot_es",
"endpoint":"https://my-endpoint",
"index":"my-index",
"type":"my-type",
"id":"${newuuid()}"
}
}]
}
}
For more information, see the Amazon Elasticsearch Service Developer Guide.
Firehose Action
Firehose Action
A firehose action sends data from an MQTT message that triggered the rule to a Kinesis Data
Firehose stream.
more info (6)
When creating a rule with a firehose action, you must specify the following information:
deliveryStreamName
The Kinesis Data Firehose stream to which to write the message data.
roleArn
A character separator that is used to separate records written to the Kinesis Data Firehose
stream. Valid values are: '\n' (newline), '\t' (tab), '\r\n' (Windows newline), ',' (comma).
Note
Make sure that the role associated with the rule has a policy that grants the
firehose:PutRecord permission.
The following JSON example shows how to create an AWS IoT rule with a firehose action:
{
"topicRulePayload": {
"sql": "SELECT * FROM 'some/topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
255
AWS IoT Developer Guide
IoT Analytics Action
"actions": [{
"firehose": {
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_firehose",
"deliveryStreamName": "my_firehose_stream"
}
}]
}
}
For more information, see the Kinesis Data Firehose Developer Guide.
An iotAnalytics action sends data from the MQTT message that triggered the rule to an AWS IoT
Analytics channel.
more info (7)
When creating a rule with an iotAnalytics action, you must specify the following information:
channelName
The name of the AWS IoT Analytics channel to which to write the data.
roleArn
The IAM role that allows access to the AWS IoT Analytics channel.
The policy attached to the role you specify should look like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iotanalytics:BatchPutMessage",
"Resource": [
"arn:aws:iotanalytics:us-west-2:<your-account-number>:channel/
mychannel"
]
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "iot.amazonaws.com"
},
"Action": "sts:AssumeRole",
}
]
}
256
AWS IoT Developer Guide
IoT Events Action
The following JSON example shows how to create an AWS IoT rule with an iotAnalytics action:
{
"topicRulePayload": {
"sql": "SELECT * FROM 'some/topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"iotAnalytics": {
"channelName": "mychannel",
"roleArn": "arn:aws:iam::123456789012:role/analyticsRole",
}
}]
}
}
For more information, see the AWS IoT Analytics User Guide.
The AWS IoT Analytics console also has a Quick start feature that allows you to create a channel,
data store, pipeline, and data store with one click. Look for this page when you enter the AWS IoT
Analytics console:
An iotEvents action sends data from the MQTT message that triggered the rule to an AWS IoT
Events input.
more info (8)
When creating a rule with a iotEvents action, you must specify the following information:
inputName
Optional. Use this to ensure that only one input (message) with a given messageId is processed
by an AWS IoT Events detector.
257
AWS IoT Developer Guide
Kinesis Action
roleArn
The ARN of the role that grants AWS IoT permission to send an input to an AWS IoT Events
detector. ("Action":"iotevents:BatchPutMessage").
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": "iotevents:BatchPutMessage",
"Resource": [ * ]
}
}
The following JSON example shows how to create an AWS IoT rule with an iotEvents action:
{
"topicRulePayload": {
"sql": "expression",
"ruleDisabled": false,
"description": "An AWS IoT Events test rule",
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"iotEvents": {
"inputName": "MyIoTEventsInput",
"messageId": "1234567890",
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_events"
},
}]
}
}
For more information, see the AWS IoT Events Developer Guide.
Kinesis Action
Kinesis Action
The kinesis action allows you to write data from MQTT messages into a Kinesis stream.
more info (9)
When creating an AWS IoT rule with a kinesis action, you must specify the following information:
stream
The partition key used to determine to which shard the data is written. The partition key is
usually composed of an expression (for example, "${topic()}" or "${timestamp()}").
Note
Ensure that the policy associated with the rule has the kinesis:PutRecord permission.
The following JSON example shows how to define a kinesis action in an AWS IoT rule:
258
AWS IoT Developer Guide
Lambda Action
{
"topicRulePayload": {
"sql": "SELECT * FROM 'some/topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"kinesis": {
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_kinesis",
"streamName": "my_kinesis_stream",
"partitionKey": "${topic()}"
}
}],
}
}
Lambda Action
Lambda Action
A lambda action calls a Lambda function, passing in the MQTT message that triggered the rule.
more info (10)
In order for AWS IoT to call a Lambda function, you must configure a policy granting the
lambda:InvokeFunction permission to AWS IoT. Lambda functions use resource-based policies,
so you must attach the policy to the Lambda function itself. Use the following CLI command to
attach a policy granting lambda:InvokeFunction permission:
--function-name
Name of the Lambda function whose resource policy you are updating by adding a new
permission.
--region
The principal who is getting the permission. This should be iot.amazonaws.com to allow AWS
IoT permission to call a Lambda function.
--source-arn
The ARN of the rule. You can use the get-topic-rule CLI command to get the ARN of a rule.
--source-account
259
AWS IoT Developer Guide
Republish Action
--action
The Lambda action you want to allow in this statement. To allow AWS IoT to invoke a Lambda
function, specify lambda:InvokeFunction.
Note
If you add a permission for an AWS IoT principal without providing the source ARN, any
AWS account that creates a rule with your Lambda action can trigger rules to invoke your
Lambda function from AWS IoT.
When creating a rule with a lambda action, you must specify the Lambda function to invoke when
the rule is triggered.
The following JSON example shows a rule that calls a Lambda function:
{
"topicRulePayload": {
"sql": "SELECT * FROM 'some/topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"lambda": {
"functionArn": "arn:aws:lambda:us-
east-2:123456789012:function:myLambdaFunction"
}
}]
}
}
If you do not specify a version or alias for your Lambda function, the most recent version of the
function is executed. You can specify a version or alias if you want to execute a specific version of
your Lambda function. To specify a version or alias, append the version or alias to the ARN of the
Lambda function. For example:
"arn:aws:lambda:us-east-2:123456789012:function:myLambdaFunction:someAlias"
For more information about versioning and aliases see AWS Lambda Function Versioning and
Aliases. For more information about AWS Lambda, see the AWS Lambda Developer Guide.
Republish Action
Republish Action
The republish action allows you to republish the message that triggered the role to another MQTT
topic.
more info (11)
When creating a rule with a republish action, you must specify the following information:
topic
The MQTT topic to which to republish the message. If you are republishing to a reserved topic,
one that begins with $ use $$ instead. For example, if you are republishing to a device shadow
260
AWS IoT Developer Guide
S3 Action
Note
Make sure that the role associated with the rule has a policy granting the iot:Publish
permission.
{
"topicRulePayload": {
"sql": "SELECT * FROM 'some/topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"republish": {
"topic": "another/topic",
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_republish"
}
}]
}
}
S3 Action
S3 Action
An s3 action writes the data from the MQTT message that triggered the rule to an Amazon S3
bucket.
more info (12)
When creating an AWS IoT rule with an s3 action, you must specify the following information,
except cannedacl, which is optional:
bucket
Optional. The Amazon S3 canned ACL that controls access to the object identified by the object
key. For more information, including allowed values, see S3 Canned ACLs.
key
The path to the file where the data is written. For example, if the value of this argument is
"${topic()}/${timestamp()}", the topic the message was sent to is "this/is/my/topic,". If the
current timestamp is 1460685389, the data is written to a file called "1460685389" in the "this/
is/my/topic" folder on Amazon S3.
Note
Using a static key results in a single file in Amazon S3 being overwritten for each
invocation of the rule. More common use cases are to use the message timestamp or
another unique message identifier so that a new file is saved in Amazon S3 for each
message received.
roleArn
261
AWS IoT Developer Guide
Salesforce Action
Note
Make sure that the role associated with the rule has a policy granting the s3:PutObject
permission.
The following JSON example shows how to define an s3 action in an AWS IoT rule:
{
"topicRulePayload": {
"sql": "SELECT * FROM 'some/topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"s3": {
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_s3",
"bucketName": "my-bucket",
"key": "${topic()}/${timestamp()}"
"cannedacl": "public-read"
}
}]
}
}
Salesforce Action
Salesforce Action
A salesforce action sends data from the MQTT message that triggered the rule to a Salesforce IoT
input stream.
more info (13)
When creating a rule with a salesforce action, you must specify the following information:
url
The URL exposed by the Salesforce IoT input stream. The URL is available from the Salesforce
IoT platform when you create an input stream. For more information, see the Salesforce IoT
documentation.
token
The token used to authenticate access to the specified Salesforce IoT input stream. The token
is available from the Salesforce IoT platform when you create an input stream. For more
information, see the Salesforce IoT documentation.
Note
These parameters do not support substitution.
The following JSON example shows how to create an AWS IoT rule with a salesforce action:
{
"topicRulePayload": {
"sql": "expression",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"salesforce": {
"token": "ABCDEFGHI123456789abcdefghi123456789",
262
AWS IoT Developer Guide
SNS Action
"url": "https://ingestion-cluster-id.my-env.sfdcnow.com/streams/stream-
id/connection-id/my-event"
}
}]
}
}
SNS Action
SNS Action
A sns action sends the data from the MQTT message that triggered the rule as an SNS push
notification.
more info (14)
When creating a rule with an sns action, you must specify the following information:
messageFormat
The message format. Accepted values are "JSON" and "RAW." The default value of the attribute
is "RAW." SNS uses this setting to determine if the payload should be parsed and relevant
platform-specific parts of the payload should be extracted.
roleArn
The SNS topic or individual device to which the push notification is sent.
Note
Make sure that the policy associated with the rule has the sns:Publish permission.
The following JSON example shows how to define an sns action in an AWS IoT rule:
{
"topicRulePayload": {
"sql": "SELECT * FROM 'some/topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"sns": {
"targetArn": "arn:aws:sns:us-east-2:123456789012:my_sns_topic",
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_sns"
}
}]
}
}
SQS Action
SQS Action
An sqs action sends data from the MQTT message that triggered the rule to an SQS queue.
263
AWS IoT Developer Guide
Step Functions Action
When creating a rule with an sqs action, you must specify the following information:
queueUrl
Set to true if you want the MQTT message data to be Base64-encoded before writing to the
SQS queue. Otherwise, set to false.
roleArn
Note
Make sure that the role associated with the rule has a policy granting the
sqs:SendMessage permission.
The following JSON example shows how to create an AWS IoT rule with an sqs action:
{
"topicRulePayload": {
"sql": "SELECT * FROM 'some/topic'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"sqs": {
"queueUrl": "https://sqs.us-east-2.amazonaws.com/123456789012/
my_sqs_queue",
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_sqs",
"useBase64": false
}
}]
}
}
SQS action does not support SQS FIFO Queues. Because the Rules Engine is a fully distributed
service, there is no guarantee of message order when the SQS action is triggered.
When creating a rule with a stepFunctions action, you must specify the following information:
executionNamePrefix
Optional. The name given to the state machine execution consists of this prefix followed by
a UUID. Step Functions creates a unique name for each state machine execution if one is not
provided.
264
AWS IoT Developer Guide
Troubleshooting a Rule
stateMachineName
The name of the Step Functions state machine whose execution will be started.
roleArn
The ARN of the role that grants AWS IoT permission to start execution of a state machine
("Action":"states:StartExecution").
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": "states:StartExecution",
"Resource": [ * ]
}
}
The following JSON example shows how to create an AWS IoT rule with a stepFunctions action:
{
"topicRulePayload": {
"sql": "expression",
"ruleDisabled": false,
"description": "A step functions test rule",
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"stepFunctions": {
"executionNamePrefix": "myExecution",
"stateMachineName": "myStateMachine",
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_step_functions"
}
}]
}
}
Troubleshooting a Rule
If you are having an issue with your rules, you should enable CloudWatch Logs. By analyzing your logs,
you can determine whether the issue is authorization or whether, for example, a WHERE clause condition
did not match. For more information, see Setting Up CloudWatchLogs.
If a problem occurs when triggering an action, the rules engine triggers an error action, if one is specified
for the rule. This might happen when:
265
AWS IoT Developer Guide
Error Action Message Format
{
"ruleName": "TestAction",
"topic": "testme/action",
"cloudwatchTraceId": "7e146a2c-95b5-6caf-98b9-50e3969734c7",
"clientId": "iotconsole-1511213971966-0",
"base64OriginalPayload": "ewogICJtZXNzYWdlIjogIkhlbGxvIHZyb20gQVdTIElvVCBjb25zb2xlIgp9",
"failures": [
{
"failedAction": "S3Action",
"failedResource": "us-east-1-s3-verify-user",
"errorMessage": "Failed to put S3 object. The error received was The
specified bucket does not exist (Service: Amazon S3; Status Code: 404; Error
Code: NoSuchBucket; Request ID: 9DF5416B9B47B9AF; S3 Extended Request ID:
yMah1cwPhqTH267QLPhTKeVPKJB8BO5ndBHzOmWtxLTM6uAvwYYuqieAKyb6qRPTxP1tHXCoR4Y=).
Message arrived on: error/action, Action: s3, Bucket: us-
east-1-s3-verify-user, Key: \"aaa\". Value of x-amz-id-2:
yMah1cwPhqTH267QLPhTKeVPKJB8BO5ndBHzOmWtxLTM6uAvwYYuqieAKyb6qRPTxP1tHXCoR4Y="
}
]
}
ruleName
The name of the action that failed to complete (for example, "S3Action").
failedResource
266
AWS IoT Developer Guide
AWS IoT SQL Reference
{
"sql" : "SELECT * FROM ..."
"actions" : [{
"dynamoDB" : {
"table" : "PoorlyConfiguredTable",
"hashKeyField" : "AConstantString",
"hashKeyValue" : "AHashKey"}}
],
"errorAction" : {
"s3" : {
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_s3",
"bucket" : "message-processing-errors",
"key" : "${replace(topic(), '/', '-') + '-' + timestamp() + '-' + newuuid()}"
}
}
}
You can use any function or substitution in an error action's SQL statement, except for external functions
(for example, get_thing_shadow, aws_lambda, and machinelearning_predict.)
For more information about rules and how to specify an error action, see Creating an AWS IoT Rule.
For more information about using CloudWatch to monitor the success or failure of rules, see AWS IoT
Metrics and Dimensions (p. 620).
SELECT
Required. Extracts information from the incoming message payload and performs transformations.
FROM
The MQTT message topic filter. The rule is triggered for each message sent to an MQTT topic
that matches the filter specified here. Required for rules that are triggered by messages that
pass through the message broker. Optional for rules that are only triggered using the Basic
Ingest (p. 319) feature.
WHERE
Optional. Adds conditional logic that determines if the actions specified by a rule are carried out.
An example MQTT message (also called an incoming payload) looks like this:
{
"color":"red",
"temperature":100
}
267
AWS IoT Developer Guide
Data Types
If this message is published on the 'a/b' topic, the rule is triggered and the SQL statement is evaluated.
The SQL statement extracts the value of the color property if the "temperature" property is greater
than 50. The WHERE clause specifies the condition temperature > 50. The AS keyword renames the
"color" property to "rgb". The result (also called an outgoing payload) looks like this:
{
"rgb":"red"
}
This data is then forwarded to the rule's action, which sends the data for more processing. For more
information about rule actions, see AWS IoT Rule Actions (p. 249).
Data Types
The AWS IoT rules engine supports all JSON data types.
Type Meaning
{"foo":null, "bar":undefined}
268
AWS IoT Developer Guide
Data Types
Type Meaning
{"foo":null}
Conversions
The following table lists the results when a value of one type is converted to another type (when a value
of the incorrect type is given to a function). For example, if the absolute value function "abs" (which
expects an Int or Decimal) is given a String, it attempts to convert the String to a Decimal,
following these rules. In this case, 'abs("-5.123")' is treated as 'abs(-5.123)'.
Note
There are no attempted conversions to Array, Object, Null, or Undefined.
To Decimal
Array Undefined.
Object Undefined.
Null Null.
Undefined Undefined.
To Int
269
AWS IoT Developer Guide
Data Types
Array Undefined.
Object Undefined.
Null Null.
Undefined Undefined.
To Boolean
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
To String
270
AWS IoT Developer Guide
Operators
Null Undefined.
Undefined Undefined.
Operators
The following operators can be used in SELECT, FROM, and WHERE clauses.
AND operator
Returns a Boolean result. Performs a logical AND operation. Returns true if left and right operands are
true. Otherwise, returns false. Boolean operands or case insensitive "true" or "false" string operands are
required.
AND Operator
Boolean Boolean Boolean. True if both operands are true. Otherwise, false.
String/Boolean String/Boolean If all strings are "true" or "false" (case insensitive), they are
converted to Boolean and processed normally as boolean
AND boolean.
OR operator
Returns a Boolean result. Performs a logical OR operation. Returns true if either the left or the right
operands are true. Otherwise, returns false. Boolean operands or case insensitive "true" or "false" string
operands are required.
OR Operator
271
AWS IoT Developer Guide
Operators
String/Boolean String/Boolean If all strings are "true" or "false" (case insensitive), they are
converted to Booleans and processed normally as boolean
OR boolean.
NOT operator
Returns a Boolean result. Performs a logical NOT operation. Returns true if the operand is false.
Otherwise, returns true. A Boolean operand or case insensitive "true" or "false" string operand is
required.
NOT Operator
Operand Output
> operator
Returns a Boolean result. Returns true if the left operand is greater than the right operand. Both
operands are converted to a Decimal, and then compared.
> Operator
Int/Decimal Int/Decimal Boolean. True if the left operand is greater than the right
operand. Otherwise, false.
>= operator
Returns a Boolean result. Returns true if the left operand is greater than or equal to the right operand.
Both operands are converted to a Decimal, and then compared.
272
AWS IoT Developer Guide
Operators
>= Operator
Left Operand Right Operand Output
Int/Decimal Int/Decimal Boolean. True if the left operand is greater than or equal to
the right operand. Otherwise, false.
< operator
Returns a Boolean result. Returns true if the left operand is less than the right operand. Both operands
are converted to a Decimal, and then compared.
< Operator
Left Operand Right Operand Output
Int/Decimal Int/Decimal Boolean. True if the left operand is less than the right
operand. Otherwise, false.
<= operator
Returns a Boolean result. Returns true if the left operand is less than or equal to the right operand. Both
operands are converted to a Decimal, and then compared.
>= Operator
Left Operand Right Operand Output
Int/Decimal Int/Decimal Boolean. True if the left operand is less than or equal to the
right operand. Otherwise, false.
<> operator
Returns a Boolean result. Returns true if both left and right operands are not equal. Otherwise, returns
false.
273
AWS IoT Developer Guide
Operators
<> Operator
Int Int True if left operand is not equal to right operand. Otherwise,
false.
Decimal Decimal True if left operand is not equal to right operand. Otherwise,
false.Int is converted to Decimal before being compared.
String String True if left operand is not equal to right operand. Otherwise,
false.
Array Array True if the items in each operand are not equal and not in
the same order. Otherwise, false
Object Object True if the keys and values of each operand are not equal.
Otherwise, false. The order of keys/values is unimportant.
= operator
Returns a Boolean result. Returns true if both left and right operands are equal. Otherwise, returns
false.
= Operator
Array Array True if the items in each operand are equal and in the same
order. Otherwise, false.
Object Object True if the keys and values of each operand are equal.
Otherwise, false. The order of keys/values is unimportant.
274
AWS IoT Developer Guide
Operators
+ operator
The "+" is an overloaded operator. It can be used for string concatenation or addition.
+ Operator
String Any Value Converts the right operand to a string and concatenates it to
the end of the left operand.
Any Value String Converts the left operand to a string and concatenates the
right operand to the end of the converted left operand.
- operator
Subtracts the right operand from the left operand.
- Operator
Int Int Int value. Subtracts right operand from left operand.
Int/Decimal Int/Decimal Decimal value. Subtracts right operand from left operand.
* operator
Multiplies the left operand by the right operand.
* Operator
Int Int Int value. Multiplies the left operand by the right operand.
275
AWS IoT Developer Guide
Functions
Int/Decimal Int/Decimal Decimal value. Multiplies the left operand by the right
operand.
/ operator
Divides the left operand by the right operand.
/ Operator
Int Int Int value. Divides the left operand by the right operand.
Int/Decimal Int/Decimal Decimal value. Divides the left operand by the right
operand.
% operator
Returns the remainder from dividing the left operand by the right operand.
% Operator
Int Int Int value. Returns the remainder from dividing the left
operand by the right operand.
Functions
You can use the following built-in functions in the SELECT or WHERE clauses of your SQL expressions.
276
AWS IoT Developer Guide
Functions
abs(Decimal)
Returns the absolute value of a number. Supported by SQL version 2015-10-8 and later.
Boolean Undefined.
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
accountid()
Returns the ID of the account that owns this rule as a String. Supported by SQL version 2015-10-8 and
later.
Example:
accountid() = "123456789012"
acos(Decimal)
Returns the inverse cosine of a number in radians. Decimal arguments are rounded to double precision
before function application. Supported by SQL version 2015-10-8 and later.
Boolean Undefined.
277
AWS IoT Developer Guide
Functions
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
asin(Decimal)
Returns the inverse sine of a number in radians. Decimal arguments are rounded to double precision
before function application. Supported by SQL version 2015-10-8 and later.
Boolean Undefined.
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
atan(Decimal)
Returns the inverse tangent of a number in radians. Decimal arguments are rounded to double precision
before function application. Supported by SQL version 2015-10-8 and later.
278
AWS IoT Developer Guide
Functions
Boolean Undefined.
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
atan2(Decimal, Decimal)
Returns the angle, in radians, between the positive x-axis and the (x, y) point defined in the two
arguments. The angle is positive for counter-clockwise angles (upper half-plane, y > 0), and negative for
clockwise angles (lower half-plane, y < 0). Decimal arguments are rounded to double precision before
function application. Supported by SQL version 2015-10-8 and later.
aws_lambda(functionArn, inputJson)
Calls the specified Lambda function passing inputJson to the Lambda function and returns the JSON
generated by the Lambda function.
Arguments
Argument Description
functionArn The ARN of the Lambda function to call. The Lambda function
must return JSON data.
You must grant AWS IoT lambda:InvokeFunction permissions to invoke the specified Lambda
function. The following example shows how to grant the lambda:InvokeFunction permission using
the AWS CLI:
279
AWS IoT Developer Guide
Functions
--principal iot.amazonaws.com
--source-arn arn:aws:iot:us-east-1:account_id:rule/rule_name
--source-account "account_id"
--statement-id "unique_id"
--action "lambda:InvokeFunction"
--function-name
Name of the Lambda function whose resource policy you are updating by adding a new permission.
--region
The principal who is getting the permission. This should be iot.amazonaws.com to allow AWS IoT
permission to call a Lambda function.
--source-arn
The ARN of the rule. You can use the get-topic-rule CLI command to get the ARN of a rule.
--source-account
The Lambda action you want to allow in this statement. To allow AWS IoT to invoke a Lambda
function, specify lambda:InvokeFunction.
Note
If you add a permission for an AWS IoT principal without providing the source ARN, any AWS
account that creates a rule with your Lambda action can trigger rules to invoke your Lambda
function from AWS IoT. For more information, see Lambda Permission Model.
{
"attribute1": 21,
"attribute2": "value"
}
SELECT
aws_lambda("arn:aws:lambda:us-east-1:account_id:function:lambda_function",
{"payload":attribute1) as output FROM 'a/b'
If you want to pass the full MQTT message payload, you can specify the JSON payload using '*'. For
example:
SELECT
aws_lambda("arn:aws:lambda:us-east-1:account_id:function:lambda_function", *) as output
FROM 'a/b'
280
AWS IoT Developer Guide
Functions
some.value selects data from the output that is generated by the Lambda function.
Note
The rules engine limits the execution duration of Lambda functions. Lambda function calls from
rules should be completed within 2000 milliseconds.
bitand(Int, Int)
Performs a bitwise AND on the bit representations of the two Int(-converted) arguments. Supported by
SQL version 2015-10-8 and later.
Example: bitand(13, 5) = 5
bitor(Int, Int)
Performs a bitwise OR of the bit representations of the two arguments. Supported by SQL version
2015-10-8 and later.
Example: bitor(8, 5) = 13
bitxor(Int, Int)
Performs a bitwise XOR on the bit representations of the two Int(-converted) arguments. Supported by
SQL version 2015-10-8 and later.
281
AWS IoT Developer Guide
Functions
Example:bitor(13, 5) = 8
bitnot(Int)
Performs a bitwise NOT on the bit representations of the Int(-converted) argument. Supported by SQL
version 2015-10-8 and later.
Example: bitnot(13) = 2
cast()
Converts a value from one data type to another. Cast behaves mostly like the standard conversions, with
the addition of the ability to cast numbers to or from Booleans. If AWS IoT cannot determine how to cast
one type to another, the result is Undefined. Supported by SQL version 2015-10-8 and later. Format:
cast(value as type).
Example:
The following keywords might appear after "as" when calling cast:
Keyword Result
282
AWS IoT Developer Guide
Functions
Keyword Result
Keyword Result
Casting rules:
Cast to Decimal
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
Cast to Int
283
AWS IoT Developer Guide
Functions
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
Cast to Boolean
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
Cast to String
284
AWS IoT Developer Guide
Functions
Null Undefined.
Undefined Undefined.
ceil(Decimal)
Rounds the given Decimal up to the nearest Int. Supported by SQL version 2015-10-8 and later.
Examples:
ceil(1.2) = 2
ceil(11.2) = -1
chr(String)
Returns the ASCII character that corresponds to the given Int argument. Supported by SQL version
2015-10-8 and later.
Examples:
chr(65) = "A".
chr(49) = "1".
Boolean Undefined.
285
AWS IoT Developer Guide
Functions
Array Undefined.
Object Undefined.
Null Undefined.
clientid()
Returns the ID of the MQTT client sending the message, or n/a if the message wasn't sent over MQTT.
Supported by SQL version 2015-10-8 and later.
Example:
clientid() = "123456789012"
concat()
Concatenates arrays or strings. This function accepts any number of arguments and returns a String or
an Array. Supported by SQL version 2015-10-8 and later.
Examples:
concat() = Undefined.
concat(1) = "1".
concat("he","is","man") = "heisman"
0 Undefined.
286
AWS IoT Developer Guide
Functions
cos(Decimal)
Returns the cosine of a number in radians. Decimal arguments are rounded to double precision before
function application. Supported by SQL version 2015-10-8 and later.
Example:
cos(0) = 1.
Boolean Undefined.
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
cosh(Decimal)
Returns the hyperbolic cosine of a number in radians. Decimal arguments are rounded to double
precision before function application. Supported by SQL version 2015-10-8 and later.
Boolean Undefined.
Array Undefined.
287
AWS IoT Developer Guide
Functions
Object Undefined.
Null Undefined.
Undefined Undefined.
encode(value, encodingScheme)
Use the encode function to encode the payload, which potentially might be non-JSON data, into its
string representation based on the encoding scheme. Supported by SQL version 2016-03-23 and later.
value
Any of the valid expressions, as defined in AWS IoT SQL Reference (p. 267). You can specify * to
encode the entire payload, regardless of whether it's in JSON format. If you supply an expression,
the result of the evaluation is converted to a string before it is encoded.
encodingScheme
A literal string representing the encoding scheme you want to use. Currently, only 'base64' is
supported.
endswith(String, String)
Returns a Boolean indicating whether the first String argument ends with the second String
argument. If either argument is Null or Undefined, the result is Undefined. Supported by SQL version
2015-10-8 and later.
exp(Decimal)
Returns e raised to the Decimal argument. Decimal arguments are rounded to double precision before
function application. Supported by SQL version 2015-10-8 and later.
Example: exp(1) = e.
288
AWS IoT Developer Guide
Functions
get
Extracts a value from a collection-like type (Array, String, Object). No conversion is applied to the first
argument. Conversion applies as documented in the table to the second argument. Supported by SQL
version 2015-10-8 and later.
Examples:
get("abc", 1) = "b"
get_thing_shadow(thingName, roleARN)
Returns the shadow of the specified thing. Supported by SQL version 2016-03-23 and later.
thingName
String: The name of the thing whose shadow you want to retrieve.
roleArn
Example:
289
AWS IoT Developer Guide
Functions
WHERE get_thing_shadow("MyThing","arn:aws:iam::123456789012:role/
AllowsThingShadowAccess") .state.reported.alarm = 'ON'
Hashing Functions
AWS IoT provides the following hashing functions:
• md2
• md5
• sha1
• sha224
• sha256
• sha384
• sha512
All hash functions expect one string argument. The result is the hashed value of that string. Standard
string conversions apply to non-string arguments. All hash functions are supported by SQL version
2015-10-8 and later.
Examples:
md2("hello") = "a9046c73e00331af68917d3804f70655"
md5("hello") = "5d41402abc4b2a76b9719d911017c592"
indexof(String, String)
Returns the first index (0-based) of the second argument as a substring in the first argument. Both
arguments are expected as strings. Arguments that are not strings are subjected to standard string
conversion rules. This function does not apply to arrays, only to strings. Supported by SQL version
2015-10-8 and later.
Examples:
indexof("abcd", "bc") = 1
isNull()
Returns true if the argument is the Null value. Supported by SQL version 2015-10-8 and later.
Examples:
isNull(5) = false.
isNull(Null) = true.
Int false
Decimal false
Boolean false
290
AWS IoT Developer Guide
Functions
String false
Array false
Object false
Null true
Undefined false
isUndefined()
Returns true if the argument is Undefined. Supported by SQL version 2016-03-23 and later.
Examples:
isUndefined(5) = false.
isNull(floor([1,2,3]))) = true.
Int false
Decimal false
Boolean false
String false
Array false
Object false
Null false
Undefined true
length(String)
Returns the number of characters in the provided string. Standard conversion rules apply to non-String
arguments. Supported by SQL version 2015-10-8 and later.
Examples:
length("hi") = 2
length(false) = 5
ln(Decimal)
Returns the natural logarithm of the argument. Decimal arguments are rounded to double precision
before function application. Supported by SQL version 2015-10-8 and later.
Example: ln(e) = 1.
291
AWS IoT Developer Guide
Functions
Boolean Undefined.
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
log(Decimal)
Returns the base 10 logarithm of the argument. Decimal arguments are rounded to double precision
before function application. Supported by SQL version 2015-10-8 and later.
Boolean Undefined.
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
lower(String)
Returns the lowercase version of the given String. Non-string arguments are converted to strings using
the standard conversion rules. Supported by SQL version 2015-10-8 and later.
Examples:
292
AWS IoT Developer Guide
Functions
lower("HELLO") = "hello".
lower(["HELLO"]) = "[\"hello\"]".
lpad(String, Int)
Returns the String argument, padded on the left side with the number of spaces specified by the
second argument. The Int argument must be between 0 and 1000. If the provided value is outside of
this valid range, the argument is set to the nearest valid value (0 or 1000). Supported by SQL version
2015-10-8 and later.
Examples:
ltrim(String)
Removes all leading whitespace (tabs and spaces) from the provided String. Supported by SQL version
2015-10-8 and later.
Example:
293
AWS IoT Developer Guide
Functions
Null Undefined.
Undefined Undefined.
machinelearning_predict(modelId)
Use the machinelearning_predict function to make predictions using the data from an MQTT
message based on an Amazon Machine Learning (Amazon ML) model. Supported by SQL version
2015-10-8 and later. The arguments for the machinelearning_predict function are:
modelId
The ID of the model against which to run the prediction. The real-time endpoint of the model must
be enabled.
roleArn
The data to be passed into the Amazon ML Predict API. This should be represented as a single layer
JSON object. If the record is a multi-level JSON object, the record is flattened by serializing its
values. For example, the following JSON:
would become:
predictedLabel
294
AWS IoT Developer Guide
Functions
Algorithm
The algorithm used by Amazon ML to make predictions. The value must be SGD.
predictedScores
mod(Decimal, Decimal)
Returns the remainder of the division of the first argument by the second argument. Supported by SQL
version 2015-10-8 and later. You can also use "%" as an infix operator for the same modulo functionality.
Supported by SQL version 2015-10-8 and later.
Example: mod(8, 3) = 2.
nanvl(AnyValue, AnyValue)
Returns the first argument if it is a valid Decimal. Otherwise, the second argument is returned.
Supported by SQL version 2015-10-8 and later.
Example: Nanvl(8, 3) = 8.
newuuid()
Returns a random 16-byte UUID. Supported by SQL version 2015-10-8 and later.
295
AWS IoT Developer Guide
Functions
numbytes(String)
Returns the number of bytes in the UTF-8 encoding of the provided string. Standard conversion rules
apply to non-String arguments. Supported by SQL version 2015-10-8 and later.
Examples:
numbytes("hi") = 2
numbytes("€") = 3
principal()
Returns the X.509 certificate fingerprint or thing name, depending on which endpoint, MQTT or HTTP,
received the request. Supported by SQL version 2015-10-8 and later.
Example:
principal() = "ba67293af50bf2506f5f93469686da660c7c844e7b3950bfb16813e0d31e9373"
pattern
(String) A date/time pattern that conforms to the ISO 8601 standard format. (Specifically, the
function supports Joda-Time formats.)
timestamp
(Long) The time to be formatted in milliseconds since Unix epoch. See function
timestamp() (p. 308).
timezone
(String) [Optional] The time zone of the formatted date/time. The default is "UTC". The function
supports Joda-Time time zones.
Examples:
When this message is published to the topic 'A/B', the payload {"ts": "1970.01.01 AD at
21:46:40 CST"} is sent to the S3 bucket:
{
"ruleArn": "arn:aws:iot:us-east-2:ACCOUNT_ID:rule/RULE_NAME",
"topicRulePayload": {
"sql": "SELECT parse_time("yyyy.MM.dd G 'at' HH:mm:ss z", 100000000, "America/
Belize" ) as ts FROM 'A/B'",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [
{
"s3": {
"roleArn": "arn:aws:iam::ACCOUNT_ID:rule:role/ROLE_NAME",
"bucketName": "BUCKET_NAME",
"key": "KEY_NAME"
}
}
],
"ruleName": "RULE_NAME"
296
AWS IoT Developer Guide
Functions
}
}
When this message is published to the topic 'A/B', a payload similar to {"ts": "2017.06.09 AD at
17:19:46 UTC"} (but with the current date/time) is sent to the S3 bucket:
{
"ruleArn": "arn:aws:iot:us-east-2:ACCOUNT_ID:rule/RULE_NAME",
"topicRulePayload": {
"sql": "SELECT parse_time("yyyy.MM.dd G 'at' HH:mm:ss z", timestamp() ) as ts FROM
'A/B'",
"awsIotSqlVersion": "2016-03-23",
"ruleDisabled": false,
"actions": [
{
"s3": {
"roleArn": "arn:aws:iam::ACCOUNT_ID:rule:role/ROLE_NAME",
"bucketName": "BUCKET_NAME",
"key": "KEY_NAME"
}
}
],
"ruleName": "RULE_NAME"
}
}
parse_time() can also be used as a substitution template. For example, when this message is
published to the topic 'A/B', the payload is sent to the S3 bucket with key = "2017":
{
"ruleArn": "arn:aws:iot:us-east-2:ACCOUNT_ID:rule/RULE_NAME",
"topicRulePayload": {
"sql": "SELECT * FROM 'A/B'",
"awsIotSqlVersion": "2016-03-23",
"ruleDisabled": false,
"actions": [
{
"s3": {
"roleArn": "arn:aws:iam::ACCOUNT_ID:rule:role/ROLE_NAME",
"bucketName": BUCKET_NAME,
"key": "${parse_time("yyyy", timestamp(), "UTC")}"
}
}
],
"ruleName": "RULE_NAME"
}
}
power(Decimal, Decimal)
Returns the first argument raised to the second argument. Decimal arguments are rounded to double
precision before function application. Supported by SQL version 2015-10-8 and later. Supported by SQL
version 2015-10-8 and later.
297
AWS IoT Developer Guide
Functions
rand()
Returns a pseudorandom, uniformly distributed double between 0.0 and 1.0. Supported by SQL version
2015-10-8 and later.
Example:
rand() = 0.8231909191640703
regexp_matches(String, String)
Returns true if the string (first argument) contains a match for the regular expression (second argument).
Example:
First argument:
Null Undefined.
Undefined Undefined.
Second argument:
Must be a valid regex expression. Non-string types are converted to String using the standard
conversion rules. Depending on the type, the resultant string might not be a valid regular expression. If
the (converted) argument is not valid regex, the result is Undefined.
Third argument:
298
AWS IoT Developer Guide
Functions
Must be a valid regex replacement string. (Can reference capture groups.) Non-string types are converted
to String using the standard conversion rules. If the (converted) argument is not a valid regex
replacement string, the result is Undefined.
Example:
First argument:
Null Undefined.
Undefined Undefined.
Second argument:
Must be a valid regex expression. Non-string types are converted to Strings using the standard
conversion rules. Depending on the type, the resultant string might not be a valid regular expression. If
the (converted) argument is not a valid regex expression, the result is Undefined.
Third argument:
Must be a valid regex replacement string. (Can reference capture groups.) Non-string types will be
converted to Strings using the standard conversion rules. If the (converted) argument is not a valid
regex replacement string, the result is Undefined.
regexp_substr(String, String)
Finds the first match of the 2nd parameter (regex) in the first parameter. Reference capture groups with
"$". Supported by SQL version 2015-10-8 and later.
Example:
299
AWS IoT Developer Guide
Functions
First argument:
Null Undefined.
Undefined Undefined.
Second argument:
Must be a valid regex expression. Non-string types are converted to Strings using the standard
conversion rules. Depending on the type, the resultant string might not be a valid regular expression. If
the (converted) argument is not a valid regex expression, the result is Undefined.
Third argument:
Must be a valid regex replacement string. (Can reference capture groups.) Non-string types are converted
to String using the standard conversion rules. If the argument is not a valid regex replacement string,
the result is Undefined.
rpad(String, Int)
Returns the string argument, padded on the right side with the number of spaces specified in the second
argument. The Int argument must be between 0 and 1000. If the provided value is outside of this valid
range, the argument is set to the nearest valid value (0 or 1000). Supported by SQL version 2015-10-8
and later.
Examples:
300
AWS IoT Developer Guide
Functions
301
AWS IoT Developer Guide
Functions
302
AWS IoT Developer Guide
Functions
round(Decimal)
Rounds the given Decimal to the nearest Int. If the Decimal is equidistant from two Int values (for
example, 0.5), the Decimal is rounded up. Supported by SQL version 2015-10-8 and later.
Example: Round(1.2) = 1.
Round(1.5) = 2.
Round(1.7) = 2.
Round(-1.1) = -1.
Round(-1.5) = -2.
303
AWS IoT Developer Guide
Functions
rtrim(String)
Removes all trailing whitespace (tabs and spaces) from the provided String. Supported by SQL version
2015-10-8 and later.
Examples:
Null Undefined.
Undefined Undefined
sign(Decimal)
Returns the sign of the given number. When the sign of the argument is positive, 1 is returned. When the
sign of the argument is negative, -1 is returned. If the argument is 0, 0 is returned. Supported by SQL
version 2015-10-8 and later.
Examples:
sign(-7) = -1.
sign(0) = 0.
sign(13) = 1.
304
AWS IoT Developer Guide
Functions
sin(Decimal)
Returns the sine of a number in radians. Decimal arguments are rounded to double precision before
function application. Supported by SQL version 2015-10-8 and later.
Boolean Undefined.
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
sinh(Decimal)
Returns the hyperbolic sine of a number. Decimal values are rounded to double precision before
function application. The result is a Decimal value of double precision. Supported by SQL version
2015-10-8 and later.
Boolean Undefined.
Array Undefined.
305
AWS IoT Developer Guide
Functions
Object Undefined.
Null Undefined.
Undefined Undefined.
If the arguments provided are not (String, Int), or (String, Int, Int), the standard conversions
are applied to the arguments to attempt to convert them into the correct types. If the types cannot be
converted, the result of the function is Undefined. Supported by SQL version 2015-10-8 and later.
Examples:
substring("012345", 0) = "012345".
substring("012345", 2) = "2345".
substring(123, 2) = "3".
substring("012345", 1, 3) = "12".
substring("012345", 3, 1) = "".
sqrt(Decimal)
Returns the square root of a number. Decimal arguments are rounded to double precision before
function application. Supported by SQL version 2015-10-8 and later.
306
AWS IoT Developer Guide
Functions
Boolean Undefined.
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
startswith(String, String)
Returns Boolean, whether the first string argument starts with the second string argument. If either
argument is Null or Undefined, the result is Undefined. Supported by SQL version 2015-10-8 and
later.
Example:
startswith("ranger","ran") = true
tan(Decimal)
Returns the tangent of a number in radians. Decimal values are rounded to double precision before
function application. Supported by SQL version 2015-10-8 and later.
Boolean Undefined.
Array Undefined.
307
AWS IoT Developer Guide
Functions
Object Undefined.
Null Undefined.
Undefined Undefined.
tanh(Decimal)
Returns the hyperbolic tangent of a number in radians. Decimal values are rounded to double precision
before function application. Supported by SQL version 2015-10-8 and later.
Boolean Undefined.
Array Undefined.
Object Undefined.
Null Undefined.
Undefined Undefined.
timestamp()
Returns the current timestamp in milliseconds from 00:00:00 Coordinated Universal Time (UTC),
Thursday, 1 January 1970, as observed by the AWS IoT rules engine. Supported by SQL version
2015-10-8 and later.
topic(Decimal)
Returns the topic to which the message that triggered the rule was sent. If no parameter is specified,
the entire topic is returned. The Decimal parameter is used to specify a specific topic segment, with 1
designating the first segment. For the topic foo/bar/baz, topic(1) returns foo, topic(2) returns bar,
and so on. Supported by SQL version 2015-10-8 and later.
Examples:
topic() = "things/myThings/thingOne"
topic(1) = "things"
308
AWS IoT Developer Guide
Functions
When Basic Ingest (p. 319) is used, the initial prefix of the topic ($aws/rules/rule-name) is not
available to the topic() function. For example, given the topic:
$aws/rules/BuildingManager/Buildings/Building5/Floor2/Room201/Lights
topic() = "Buildings/Building5/Floor2/Room201/Lights"
topic(3) = "Floor2"
traceid()
Returns the trace ID (UUID) of the MQTT message, or Undefined if the message wasn't sent over MQTT.
Supported by SQL version 2015-10-8 and later.
Example:
traceid() = "12345678-1234-1234-1234-123456789012"
trunc(Decimal, Int)
Truncates the first argument to the number of Decimal places specified by the second argument. If the
second argument is less than zero, it is set to zero. If the second argument is greater than 34, it is set to
34. Trailing zeroes are stripped from the result. Supported by SQL version 2015-10-8 and later.
Examples:
trunc(2.3, 0) = 2.
trunc(2.3123, 2) = 2.31.
trunc(2.888, 2) = 2.88.
trunc(2.00, 5) = 2.
trim(String)
Removes all leading and trailing whitespace from the provided String. Supported by SQL version
2015-10-8 and later.
Example:
309
AWS IoT Developer Guide
SELECT Clause
Null Undefined.
Undefined Undefined.
upper(String)
Returns the uppercase version of the given String. Non-String arguments are converted to String
using the standard conversion rules. Supported by SQL version 2015-10-8 and later.
Examples:
upper("hello") = "HELLO"
upper(["hello"]) = "[\"HELLO\"]"
SELECT Clause
The AWS IoT SELECT clause is essentially the same as the ANSI SQL SELECT clause, with some minor
differences.
You can use the SELECT clause to extract information from incoming MQTT messages. SELECT * can be
used to retrieve the entire incoming message payload. For example:
If the payload is a JSON object, you can reference keys in the object. Your outgoing payload contains the
key-value pair. For example:
310
AWS IoT Developer Guide
SELECT Clause
You can select multiple items by separating them with a comma. For example:
You can select multiple items including '*' to add items to the incoming payload. For example:
You can use the "VALUE" keyword to produce outgoing payloads that are not JSON objects. You may
only select one item. For example:
You can use '.' syntax to drill into nested JSON objects in the incoming payload. For example:
You can use functions (see Functions (p. 276)) to transform the incoming payload. Parentheses can be
used for grouping. For example:
These rules must be followed to use * to refer to the message payload as raw binary data:
1. The SQL statement and templates must not refer to JSON names other than *.
2. The SELECT statement must have * as the only item, or must have only functions, for example:
311
AWS IoT Developer Guide
FROM Clause
The following SELECT cannot be used with binary payloads because it refers to device_type in the
WHERE clause.
The following SELECT cannot be used with binary payloads because it violates rule #2.
The following SELECT can be used with binary payloads because it doesn't violate rule #1 or rule #2.
The following AWS IoT rule cannot be used with payloads because it violates rule #1.
{
"sql": "SELECT * FROM 'a/b'"
"actions": [{
"republish": {
"topic":"device/${device_id}"
}
}]
}
FROM Clause
The FROM clause subscribes your rule to a topic or topic filter. The rule is triggered for each message
sent to an MQTT topic that matches the topic filter specified here. A topic filter allows you to subscribe
to a group of similar topics.
Example:
The rule is subscribed to 'a/b', so the incoming payload is passed to the rule, and the outgoing payload
(passed to the rule actions) is: {t: 50}. The rule is not subscribed to 'a/c', so the rule is not triggered
for the message published on 'a/c'.
# Wildcard Example:
You can use the '#' (multi-level) wildcard character to match one or more particular path elements:
312
AWS IoT Developer Guide
WHERE Clause
The rule is subscribed to any topic beginning with 'a', so it is executed three times, sending outgoing
payloads of {t: 50} (for a/b), {t: 60} (for a/c), and {t: 70} (for a/e/f) to its actions. It is not
subscribed to 'b/x', so the rule is not triggered for the {temperature: 80} message.
+ Wildcard Example:
You can use the '+' (single-level) wildcard character to match any one particular path element:
The rule is subscribed to all topics with two path elements where the first element is 'a'. The rule is
executed for the messages sent to 'a/b' and 'a/c', but not 'a/e/f' or 'b/x'.
WHERE Clause
The WHERE clause determines if the actions specified by a rule are carried out. If the WHERE clause
evaluates to true, the rule actions are performed. Otherwise, the rule actions are not performed.
Example:
SQL: SELECT color AS my_color FROM 'a/b' WHERE temperature > 50 AND color <>
'red'.
In this case, the rule would be triggered, but the actions specified by the rule would not be performed.
There would be no outgoing payload.
You can use functions and operators in the WHERE clause. However, you cannot reference any aliases
created with the AS keyword in the SELECT. (The WHERE clause is evaluated first, to determine if SELECT
is evaluated.)
Literals
You can directly specify literal objects in the SELECT and WHERE clauses of your rule SQL, which can be
useful for passing information.
Note
Literals are available only when using SQL version 2016-03-23 or later.
JSON object syntax is used (key-value pairs, comma-separated, where keys are strings and values are
JSON values, wrapped in curly brackets {}). For example:
313
AWS IoT Developer Guide
Case Statements
You can also directly specify arrays in the SELECT and WHERE clauses of your rule SQL, which allows you
to group information. JSON syntax is used (wrap comma-separated items in square brackets [] to create
an array literal). For example:
Case Statements
Case statements can be used for branching execution, like a switch statement, or if/else statements.
Syntax:
The expression v is evaluated and matched for equality against each t[i] expression. If a match is
found, the corresponding r[i] expression becomes the result of the case statement. If there is more
than one possible match, the first match is selected. If there are no matches, the else statement's re
is used as the result. If there is no match and no else statement, the result of the case statement is
Undefined. For example:
SQL statement: SELECT CASE color WHEN 'green' THEN 'go' WHEN 'yellow' THEN
'caution' WHEN 'red' THEN 'stop' ELSE 'you are not at a stop light' END as
instructions FROM 'a/b'
Case statements require at least one WHEN clause. An ELSE clause is not required.
Note
If v is Undefined, the result of the case statement is Undefined.
JSON Extensions
You can use the following extensions to ANSI SQL syntax to make it easier to work with nested JSON
objects.
"." Operator
This operator accesses members in embedded JSON objects and functions identically to ANSI SQL and
JavaScript. For example:
* Operator
This functions in the same way as the * wildcard in ANSI SQL. It's used in the SELECT clause only and
creates a new JSON object containing the message data. If the message payload is not in JSON format, *
returns the entire message payload as raw bytes. For example:
314
AWS IoT Developer Guide
Substitution Templates
{
"deviceid" : "iot123",
"temp" : 54.98,
"humidity" : 32.43,
"coords" : {
"latitude" : 47.615694,
"longitude" : -122.3359976
}
}
{
"temp": 54.98,
"hashed_id": "e37f81fb397e595c4aeb5645b8cbbbd1"
}
Substitution Templates
You can use a substitution template to augment the JSON data returned when a rule is triggered and
AWS IoT performs an action. The syntax for a substitution template is ${expression}, where expression
can be any expression supported by AWS IoT in a SELECT or WHERE clause. This includes functions,
operators, and information present in the original message payload. Because an expression in a
substitution template is evaluated separately from the "SELECT ..." statement, you cannot reference an
alias created using the AS clause. For more information about supported expressions, see AWS IoT SQL
Reference (p. 267).
{
"sql": "SELECT *, topic() AS topic FROM 'my/iot/topic'",
"ruleDisabled": false,
"actions": [{
"republish": {
"topic": "${topic()}/republish",
"roleArn": "arn:aws:iam::123456789012:role/my-iot-role"
}
}]
}
{
"deviceid" : "iot123",
"temp" : 54.98,
"humidity" : 32.43,
"coords" : {
315
AWS IoT Developer Guide
SQL Versions
"latitude" : 47.615694,
"longitude" : -122.3359976
}
}
{
"coords":{
"longitude":-122.3359976,
"latitude":47.615694
},
"humidity":32.43,
"temp":54.98,
"deviceid":"iot123",
"topic":"my/iot/topic"
}
SQL Versions
The AWS IoT rules engine uses an SQL-like syntax to select data from MQTT messages. The SQL
statements are interpreted based on an SQL version specified with the awsIotSqlVersion property
in a JSON document that describes the rule. For more information about the structure of JSON rule
documents, see Creating a Rule (p. 245). The awsIotSqlVersion property allows you to specify
which version of the AWS IoT SQL rules engine you want to use. When a new version is deployed, you can
continue to use an older version or change your rule to use the new version. Your current rules continue
to use the version with which they were created.
The following JSON example shows how to specify the SQL version using the awsIotSqlVersion
property:
{
"sql": "expression",
"ruleDisabled": false,
"awsIotSqlVersion": "2016-03-23",
"actions": [{
"republish": {
"topic": "my-mqtt-topic",
"roleArn": "arn:aws:iam::123456789012:role/my-iot-role"
}
}]
}
316
AWS IoT Developer Guide
What's New in the 2016-03-23 SQL Rules Engine Version
Inter-Object Queries
This feature allows you to query for an attribute in a JSON object. For example, given the following
MQTT message:
{
"e": [
{ "n": "temperature", "u": "Cel", "t": 1234, "v":22.5 },
{ "n": "light", "u": "lm", "t": 1235, "v":135 },
{ "n": "acidity", "u": "pH", "t": 1235, "v":7 }
]
}
{"temperature": [{"v":22.5}]}
Using the same MQTT message, given a slightly more complicated rule such as:
{"temperature":22.5}
{
"a": {"b":"c"},
"arr":[1,2,3,4]
}
[1,2,3,4]
317
AWS IoT Developer Guide
What's New in the 2016-03-23 SQL Rules Engine Version
Encode Function
Encodes the payload, which potentially might be non-JSON data, into its string representation based on
the specified encoding scheme.
318
AWS IoT Developer Guide
To use Basic Ingest
Basic Ingest
Basic Ingest enables you to securely send device data to the AWS services supported by AWS IoT Rule
Actions (p. 249) without incurring messaging costs. Basic Ingest optimizes data flow by removing the
publish/subscribe message broker from the ingestion path, so it's more cost effective while keeping the
security and data processing features of AWS IoT.
To use Basic Ingest, you send messages from your devices or applications with topic names that start
with $aws/rules/rule-name as their first three levels, where rule-name is the name of your AWS IoT
Rule to trigger.
You can continue to use an existing rule with Basic Ingest by just adding the Basic Ingest prefix ($aws/
rules/rule-name) to the message topic by which you normally trigger the rule. For example, if
you have a rule named "BuildingManager" that is triggered by messages with topics like "Buildings/
Building5/Floor2/Room201/Lights" ("sql": "SELECT * FROM 'Buildings/#'"), you can trigger
the same rule with Basic Ingest by sending a message with topic $aws/rules/BuildingManager/
Buildings/Building5/Floor2/Room201/Lights.
Be aware that:
• Your devices and rules cannot subscribe to Basic Ingest reserved topics. (See Reserved Topics (p. 235)
for details.)
• If you need a publish/subscribe broker to distribute messages to multiple subscribers (for example, to
deliver messages to other devices as well as the Rules Engine), you should continue to use the AWS IoT
message broker to handle the message distribution. Just publish your messages on topics other than
Basic Ingest topics.
When the message reaches the Rules Engine, there is no difference in execution or error handling
between rules triggered from Basic Ingest and those triggered through message broker subscriptions.
You can, of course, create rules for use with Basic Ingest. Keep in mind the following:
• The initial prefix of a Basic Ingest topic ($aws/rules/rule-name) isn't available to the
topic(Decimal) (p. 308) function.
• If you define a rule that is triggered only with Basic Ingest, the FROM clause is optional in the sql field
of the rule definition. It's still required if the rule will also be triggered by other messages that must
be sent through the message broker (for example, because those other messages must be distributed
to multiple subscribers). See AWS IoT SQL Reference (p. 267).
• The first three levels of the Basic Ingest topic ($aws/rules/rule-name) are not counted toward the
eight segment length limit or toward the 256 total character limit for a topic. Otherwise, the same
restrictions apply as documented in AWS IoT Limits.
• If a message is received with a Basic Ingest topic that specifies an inactive rule or a rule that doesn't
exist, an error log is created in a CloudWatch log to help you with debugging (See Rules Engine
Logs (p. 640)). A "RuleNotFound" metric is indicated and you can create alarms on this metric. See
Rule Metrics in AWS IoT Metrics (p. 620).
319
AWS IoT Developer Guide
To use Basic Ingest
• You can still publish with QoS 1 on Basic Ingest topics. You will receive a PUBACK once the message is
successfully delivered to the Rules Engine. Receiving a PUBACK does not mean that your rule actions
completed successfully. You can configure an error action to handle errors during action execution. See
Error Handling (Error Action) (p. 265).
320
AWS IoT Developer Guide
Device Shadow Service Data Flow
Contents
• Device Shadow Service Data Flow (p. 321)
• Device Shadow Service Documents (p. 328)
• Using Shadows (p. 332)
• Device Shadow RESTful API (p. 340)
• Shadow MQTT Topics (p. 343)
• Shadow Document Syntax (p. 350)
• Shadow Error Messages (p. 352)
To illustrate how devices and applications communicate with the Device Shadow service, this section
walks you through the use of the AWS IoT MQTT client and the AWS CLI to simulate communication
between an internet-connected light bulb, an application, and the Device Shadow service.
The Device Shadow service uses MQTT topics to facilitate communication between applications and
devices. To see how this works, use the AWS IoT MQTT client to subscribe to the following MQTT topics
with QoS 1:
$aws/things/myLightBulb/shadow/update/accepted
The Device Shadow service sends messages to this topic when an update is successfully made to the
device's shadow.
$aws/things/myLightBulb/shadow/update/rejected
The Device Shadow service sends messages to this topic when an update to the device's shadow is
rejected.
$aws/things/myLightBulb/shadow/update/delta
The Device Shadow service sends messages to this topic when a difference is detected between
the reported and desired sections of the device's shadow. For more information, see /update/
delta (p. 346).
$aws/things/myLightBulb/shadow/get/accepted
The Device Shadow service sends messages to this topic when a request for the device's shadow is
made successfully.
$aws/things/myLightBulb/shadow/get/rejected
The Device Shadow service sends messages to this topic when a request for the device's shadow is
rejected.
321
AWS IoT Developer Guide
Device Shadow Service Data Flow
$aws/things/myLightBulb/shadow/delete/accepted
The Device Shadow service sends messages to this topic when the device's shadow is deleted.
$aws/things/myLightBulb/shadow/delete/rejected
The Device Shadow service sends messages to this topic when a request to delete the device's
shadow is rejected.
$aws/things/myLightBulb/shadow/update/documents
The Device Shadow service publishes a state document to this topic whenever an update to the
device's shadow is successfully performed.
To learn more about all of the MQTT topics used by the Device Shadow service, see Shadow MQTT
Topics (p. 343).
Note
We recommend that you subscribe to the .../rejected topics to see any errors sent by the
Device Shadow service.
When the light bulb comes online, it sends its current state to the Device Shadow service by sending an
MQTT message to the $aws/things/myLightBulb/shadow/update topic.
Note
Device Shadows are created the first time an attempt is made to update it. The Device Shadow
service will detect that a shadow doesn't exist and will create one. If the shadow exists, it will be
updated.
To simulate this, use the AWS IoT MQTT client to publish the following message to the $aws/things/
myLightBulb/shadow/update topic:
{
"state": {
"reported": {
"color": "red"
}
}
}
The Device Shadow service responds by sending the following message to the $aws/things/
myLightBulb/shadow/update/accepted topic:
{
"messageNumber": 4,
"payload": {
"state": {
"reported": {
"color": "red"
}
},
"metadata": {
"reported": {
"color": {
"timestamp": 1469564492
}
}
},
"version": 1,
"timestamp": 1469564492
},
322
AWS IoT Developer Guide
Device Shadow Service Data Flow
"qos": 0,
"timestamp": 1469564492848,
"topic": "$aws/things/myLightBulb/shadow/update/accepted"
}
This message indicates the Device Shadow service received the UPDATE request and updated the device's
shadow. If the shadow doesn't exist, it is created. Otherwise, the shadow is updated with the data in the
message. If you don't see a message published to $aws/things/myLightBulb/shadow/update/
accepted, check the subscription to $aws/things/myLightBulb/shadow/update/rejected to see
any error messages.
In addition, the Device Shadow service publishes the following message to the $aws/things/
myLightBulb/shadow/update/documents topic.
{
"previous":null,
"current":{
"state":{
"reported":{
"color":"red"
}
},
"metadata":{
"reported":{
"color":{
"timestamp":1483467764
}
}
},
"version":1
},
"timestamp":1483467764
}
Messages are published to the /update/documents topic whenever an update to the device's shadow
is successfully performed. For more information of the contents of messages published to this topic, see
Shadow MQTT Topics (p. 343).
An application that interacts with the light bulb comes online and requests the light bulb's current state.
The application sends an empty message to the $aws/things/myLightBulb/shadow/get topic. To
simulate this, use the AWS IoT MQTT client to publish an empty message ("") to the $aws/things/
myLightBulb/shadow/get topic.
The Device Shadow service responds by publishing the requested shadow to the $aws/things/
myLightBulb/shadow/get/accepted topic:
{
"messageNumber": 1,
"payload": {
"state": {
"reported": {
"color": "red"
}
},
"metadata": {
"reported": {
"color": {
"timestamp": 1469564492
}
}
},
"version": 1,
323
AWS IoT Developer Guide
Device Shadow Service Data Flow
"timestamp": 1469564571
},
"qos": 0,
"timestamp": 1469564571533,
"topic": "$aws/things/myLightBulb/shadow/get/accepted"
}
The application displays this information to the user, and the user requests a change to the light bulb's
color (from red to green). To do this, the application publishes a message on the $aws/things/
myLightBulb/shadow/update topic:
{
"state": {
"desired": {
"color": "green"
}
}
}
To simulate this, use the AWS IoT MQTT client to publish the preceding message to the $aws/things/
myLightBulb/shadow/update topic.
{
"messageNumber": 5,
"payload": {
"state": {
"desired": {
"color": "green"
}
},
"metadata": {
"desired": {
"color": {
"timestamp": 1469564658
}
}
},
"version": 2,
"timestamp": 1469564658
},
"qos": 0,
"timestamp": 1469564658286,
"topic": "$aws/things/myLightBulb/shadow/update/accepted"
}
{
"messageNumber": 1,
"payload": {
"version": 2,
"timestamp": 1469564658,
"state": {
"color": "green"
},
324
AWS IoT Developer Guide
Device Shadow Service Data Flow
"metadata": {
"color": {
"timestamp": 1469564658
}
}
},
"qos": 0,
"timestamp": 1469564658309,
"topic": "$aws/things/myLightBulb/shadow/update/delta"
}
The Device Shadow service publishes a message to this topic when it accepts a shadow update and the
resulting shadow contains different values for desired and reported states.
{
"previous":{
"state":{
"reported":{
"color":"red"
}
},
"metadata":{
"reported":{
"color":{
"timestamp":1483467764
}
}
},
"version":1
},
"current":{
"state":{
"desired":{
"color":"green"
},
"reported":{
"color":"red"
}
},
"metadata":{
"desired":{
"color":{
"timestamp":1483468612
}
},
"reported":{
"color":{
"timestamp":1483467764
}
}
},
"version":2
},
"timestamp":1483468612
}
325
AWS IoT Developer Guide
Device Shadow Service Data Flow
{
"state":{
"reported":{
"color":"green"
},
"desired":null}
}
}
{
"messageNumber": 6,
"payload": {
"state": {
"reported": {
"color": "green"
},
"desired": null
},
"metadata": {
"reported": {
"color": {
"timestamp": 1469564801
}
},
"desired": {
"timestamp": 1469564801
}
},
"version": 3,
"timestamp": 1469564801
},
"qos": 0,
"timestamp": 1469564801673,
"topic": "$aws/things/myLightBulb/shadow/update/accepted"
}
{
"previous":{
"state":{
"reported":{
"color":"red"
}
},
"metadata":{
"reported":{
"color":{
"timestamp":1483470355
}
}
},
"version":3
},
"current":{
"state":{
"reported":{
"color":"green"
}
},
326
AWS IoT Developer Guide
Detecting a Thing Is Connected
"metadata":{
"reported":{
"color":{
"timestamp":1483470364
}
}
},
"version":4
},
"timestamp":1483470364
}
The app requests the current state from the Device Shadow service and displays the most recent state
data. To simulate this, run the following command:
Note
On Windows, omit the && cat "output.txt", which displays the contents of output.txt
to the console. You can open the file in Notepad or any text editor to see the contents of the
shadow.
{
"state":{
"reported":{
"color":"green"
}
},
"metadata":{
"reported":{
"color":{
"timestamp":1469564801
}
}
},
"version":3,
"timestamp":1469564864}
{
"version" : 1,
"timestamp" : 1488565234
}
327
AWS IoT Developer Guide
Device Shadow Service Documents
an LWT message to a non-reserved topic and create a rule that republishes the message on
the reserved topic. The following example shows how to create a republish rule that listens for
a messages from the my/things/myLightBulb/update topic and republishes it to $aws/
things/myLightBulb/shadow/update.
{
"rule": {
"ruleDisabled": false,
"sql": "SELECT * FROM 'my/things/myLightBulb/update'",
"description": "Turn my/things/ into $aws/things/",
"actions": [{
"republish": {
"topic": "$$aws/things/myLightBulb/shadow/update",
"roleArn": "arn:aws:iam::123456789012:role/aws_iot_republish"
}
}]
}
}
When a device connects, it registers an LWT that sets the connected setting to false:
{
"state": {
"reported": {
"connected":"false"
}
}
}
{
"state": {
"reported": {
"connected":"true"
}
}
}
When the device disconnects gracefully, it publishes a message on its update topic and sets its connected
state to false:
{
"state": {
"reported": {
"connected":"false"
}
}
}
If the device disconnects due to an error, its LWT message is posted automatically to the update topic.
328
AWS IoT Developer Guide
Document Properties
Contents
• Document Properties (p. 329)
• Versioning of a Device Shadow (p. 329)
• Client Token (p. 330)
• Example Document (p. 330)
• Empty Sections (p. 330)
• Arrays (p. 331)
Document Properties
A device's shadow document has the following properties:
state
desired
The desired state of the thing. Applications can write to this portion of the document to update
the state of a thing without having to directly connect to a thing.
reported
The reported state of the thing. Things write to this portion of the document to report their new
state. Applications read this portion of the document to determine the state of a thing.
metadata
Information about the data stored in the state section of the document. This includes timestamps,
in Epoch time, for each attribute in the state section, which enables you to determine when they
were updated.
Note
Metadata do not contribute to the document size for service limits or pricing. For more
information, see AWS IoT Service Limits.
timestamp
Indicates when the message was transmitted by AWS IoT. By using the timestamp in the message
and the timestamps for individual attributes in the desired or reported section, a thing can
determine how old an updated item is, even if it doesn't feature an internal clock.
clientToken
A string unique to the device that enables you to associate responses with requests in an MQTT
environment.
version
The document version. Every time the document is updated, this version number is incremented.
Used to ensure the version of the document being updated is the most recent.
329
AWS IoT Developer Guide
Client Token
• A client can receive an error if it attempts to overwrite a shadow using an older version number. The
client is informed it must resync before it can update a device's shadow.
• A client can decide not to act on a received message if the message has a lower version than the
version stored by the client.
In some cases, a client might bypass version matching by not submitting a version.
Client Token
You can use a client token with MQTT-based messaging to verify the same client token is contained in a
request and request response. This ensures the response and request are associated.
Note
The client token can be no longer than 64 bytes. A client token that is longer than 64 bytes will
cause a 400 (Bad Request) response and an Invalid clientToken error message.
Example Document
Here is an example shadow document:
{
"state" : {
"desired" : {
"color" : "RED",
"sequence" : [ "RED", "GREEN", "BLUE" ]
},
"reported" : {
"color" : "GREEN"
}
},
"metadata" : {
"desired" : {
"color" : {
"timestamp" : 12345
},
"sequence" : {
"timestamp" : 12345
}
},
"reported" : {
"color" : {
"timestamp" : 12345
}
}
},
"version" : 10,
"clientToken" : "UniqueClientToken",
"timestamp": 123456789
}
Empty Sections
A shadow document contains a desired section only if it has a desired state. For example, the following
is a valid state document with no desired section:
{
"reported" : { "temp": 55 }
330
AWS IoT Developer Guide
Arrays
{
"desired" : { "color" : "RED" }
}
If an update causes the desired or reported sections to become null, the section is removed from
the document. To remove the desired section from a document (in response, for example, to a device
updating its state), set the desired section to null:
{
"state": {
"reported": {
"color": "red"
},
"desired": null
}
}
It is also possible a shadow document will not contain desired or reported sections. In that case, the
shadow document is empty. For example, this is a valid document:
{
}
Arrays
Shadows support arrays, but treat them as normal values in that an update to an array replaces the
whole array. It is not possible to update part of an array.
Initial state:
{
"desired" : { "colors" : ["RED", "GREEN", "BLUE" ] }
}
Update:
{
"desired" : { "colors" : ["RED"] }
}
Final state:
{
"desired" : { "colors" : ["RED"] }
}
Arrays can't have null values. For example, the following array is not valid and will be rejected.
{
"desired" : {
"colors" : [ null, "RED", "GREEN" ]
331
AWS IoT Developer Guide
Using Shadows
}
}
Using Shadows
AWS IoT provides three methods for working with a device's shadow:
UPDATE
Creates a device's shadow if it doesn't exist, or updates the contents of a device's shadow with the
data provided in the request. The data is stored with timestamp information to indicate when it
was last updated. Messages are sent to all subscribers with the difference between desired or
reported state (delta). Things or apps that receive a message can perform an action based on the
difference between desired or reported states. For example, a device can update its state to the
desired state, or an app can update its UI to show the change in the device's state.
GET
Retrieves the latest state stored in the device's shadow (for example, during start-up of a device to
retrieve configuration and the last state of operation). This method returns the full JSON document,
including metadata.
DELETE
Deletes a device's shadow, including all of its content. This removes the JSON document from the
data store. You can't restore a device's shadow you deleted, but you can create a new shadow with
the same name.
Protocol Support
These methods are supported through both MQTT and a RESTful API over HTTPS. Because MQTT is
a publish/subscribe communication model, AWS IoT implements a set of reserved topics. Things or
applications subscribe to these topics before publishing on a request topic in order to implement a
request–response behavior. For more information, see Shadow MQTT Topics (p. 343) and Device
Shadow RESTful API (p. 340).
Updating a Shadow
You can update a device's shadow by using the UpdateThingShadow (p. 341) RESTful API or by
publishing to the /update (p. 343) topic. Updates affect only the fields specified in the request.
Initial state:
{
"state": {
"reported" : {
"color" : { "r" :255, "g": 255, "b": 0 }
}
}
}
{
"state": {
332
AWS IoT Developer Guide
Retrieving a Shadow Document
"desired" : {
"color" : { "r" : 10 },
"engine" : "ON"
}
}
}
The device receives the desired state on the /update/delta topic that is triggered by the previous /
update message and then executes the desired changes. When finished, the device should confirm its
updated state through the reported section in the shadow JSON document.
Final state:
{
"state": {
"reported" : {
"color" : { "r" : 10, "g" : 255, "b": 0 },
"engine" : "ON"
}
}
}
Example document:
{
"state": {
"desired": {
"lights": {
"color": "RED"
},
"engine": "ON"
},
"reported": {
"lights": {
"color": "GREEN"
},
"engine": "ON"
}
},
"metadata": {
"desired": {
"lights": {
"color": {
"timestamp": 123456
},
"engine": {
"timestamp": 123456
}
}
},
"reported": {
"lights": {
"color": {
"timestamp": 789012
}
333
AWS IoT Developer Guide
Retrieving a Shadow Document
},
"engine": {
"timestamp": 789012
}
},
"version": 10,
"timestamp": 123456789
}
}
Response:
{
"state": {
"desired": {
"lights": {
"color": "RED"
},
"engine": "ON"
},
"reported": {
"lights": {
"color": "GREEN"
},
"engine": "ON"
},
"delta": {
"lights": {
"color": "RED"
}
}
},
"metadata": {
"desired": {
"lights": {
"color": {
"timestamp": 123456
},
},
"engine": {
"timestamp": 123456
}
},
"reported": {
"lights": {
"color": {
"timestamp": 789012
}
},
"engine": {
"timestamp": 789012
}
},
"delta": {
"lights": {
"color": {
"timestamp": 123456
}
}
}
},
"version": 10,
"timestamp": 123456789
}
334
AWS IoT Developer Guide
Retrieving a Shadow Document
Optimistic Locking
You can use the state document version to ensure you are updating the most recent version of a device's
shadow document. When you supply a version with an update request, the service rejects the request
with an HTTP 409 conflict response code if the current version of the state document does not match
the version supplied.
For example:
Initial document:
{
"state" : {
"desired" : { "colors" : ["RED", "GREEN", "BLUE" ] }
},
"version" : 10
}
{
"state": {
"desired": {
"colors": [
"BLUE"
]
}
},
"version": 9
}
Result:
409 Conflict
{
"state": {
"desired": {
"colors": [
"BLUE"
]
}
},
"version": 10
}
Final state:
{
"state": {
"desired": {
"colors": [
"BLUE"
]
}
},
"version": 11
335
AWS IoT Developer Guide
Deleting Data
Deleting Data
You can delete data from a device's shadow by publishing to the /update (p. 343) topic, setting the
fields to be deleted to null. Any field with a value of null is removed from the document.
Initial state:
{
"state": {
"desired" : {
"lights": { "color": "RED" },
"engine" : "ON"
},
"reported" : {
"lights" : { "color": "GREEN" },
"engine" : "OFF"
}
}
}
{
"state": {
"desired": null,
"reported": {
"engine": null
}
}
}
Final state:
{
"state": {
"reported" : {
"lights" : { "color" : "GREEN" }
}
}
}
You can delete all data from a device's shadow by setting its state to null. For example, sending the
following message deletes all of the state data, but the device's shadow remains.
{
"state": null
}
The device's shadow still exists even if its state is null. The version of the shadow is incremented when
the next update occurs.
Deleting a Shadow
You can delete a device's shadow document by using the DeleteThingShadow (p. 342) RESTful API or
by publishing to the /delete (p. 348) topic.
336
AWS IoT Developer Guide
Delta State
Note
Deleting a device's shadow does not delete the thing. Deleting a thing does not delete the
corresponding device's shadow.
Initial state:
{
"state": {
"desired" : {
"lights": { "color": "RED" },
"engine" : "ON"
},
"reported" : {
"lights" : { "color": "GREEN" },
"engine" : "OFF"
}
}
}
Final state:
Delta State
Delta state is a virtual type of state that contains the difference between the desired and reported
states. Fields in the desired section that are not in the reported section are included in the delta.
Fields that are in the reported section and not in the desired section are not included in the delta.
The delta contains metadata, and its values are equal to the metadata in the desired field. For example:
{
"state": {
"desired": {
"color": "RED",
"state": "STOP"
},
"reported": {
"color": "GREEN",
"engine": "ON"
},
"delta": {
"color": "RED",
"state": "STOP"
}
},
"metadata": {
"desired": {
"color": {
"timestamp": 12345
},
"state": {
"timestamp": 12345
},
"reported": {
"color": {
"timestamp": 12345
},
"engine": {
337
AWS IoT Developer Guide
Observing State Changes
"timestamp": 12345
}
},
"delta": {
"color": {
"timestamp": 12345
},
"state": {
"timestamp": 12345
}
}
},
"version": 17,
"timestamp": 123456789
}
}
When nested objects differ, the delta contains the path all the way to the root.
{
"state": {
"desired": {
"lights": {
"color": {
"r": 255,
"g": 255,
"b": 255
}
}
},
"reported": {
"lights": {
"color": {
"r": 255,
"g": 0,
"b": 255
}
}
},
"delta": {
"lights": {
"color": {
"g": 255
}
}
}
},
"version": 18,
"timestamp": 123456789
}
The Device Shadow service calculates the delta by iterating through each field in the desired state and
comparing it to the reported state.
Arrays are treated like values. If an array in the desired section doesn't match the array in the
reported section, then the entire desired array is copied into the delta.
• $aws/things/thing-name/shadow/update/accepted
338
AWS IoT Developer Guide
Message Order
• $aws/things/thing-name/shadow/update/delta
The message sent to the update/delta topic is intended for the thing whose state is being updated.
This message contains only the difference between the desired and reported sections of the
device's shadow document. Upon receiving this message, the device should decide whether to make the
requested change. If the device's state is changed, it should publish its new current state to the $aws/
things/thing-name/shadow/update topic.
Devices and applications can subscribe to either of these topics to be notified when the state of the
document has changed.
Message Order
There is no guarantee that messages from the AWS IoT service will arrive at the device in any specific
order.
{
"state" : {
"reported" : { "color" : "blue" }
},
"version" : 10,
"timestamp": 123456777
}
Update 1:
{
"state": { "desired" : { "color" : "RED" } },
"version": 10,
"timestamp": 123456777
}
Update 2:
{
"state": { "desired" : { "color" : "GREEN" } },
"version": 11,
"timestamp": 123456778
}
{
"state": {
"reported": { "color" : "GREEN" }
339
AWS IoT Developer Guide
Trim Shadow Messages
},
"version": 12,
"timestamp": 123456779
}
{
"state": {
"color": "RED"
},
"version": 11,
"timestamp": 123456778
}
{
"state": { "color" : "GREEN" },
"version": 12,
"timestamp": 123456779
}
The device might receive these messages out of order. Because the state in these messages is cumulative,
a device can safely discard any messages that contain a version number older than the one it is tracking.
If the device receives the delta for version 12 before version 11, it can safely discard the version 11
message.
The rule is specified in JSON and should look like the following:
{
"sql": "SELECT state, version FROM '$aws/things/+/shadow/update/delta'",
"ruleDisabled": false,
"actions": [{
"republish": {
"topic": "${topic(2)}/delta",
"roleArn": "arn:aws:iam::123456789012:role/my-iot-role"
}
}]
}
The SELECT statement determines which fields from the message will be republished to the specified
topic. A "+" wild card is used to match all shadow names. The rule specifies that all matching messages
should be republished to the specified topic. In this case, the "topic()" function is used to specify
the topic on which to republish. topic(2) evaluates to the thing name in the original topic. For more
information about creating rules, see Rules.
https://endpoint/things/thingName/shadow
340
AWS IoT Developer Guide
GetThingShadow
The endpoint is specific to your AWS account. To retrieve your endpoint, use the describe-endpoint
command. The format of the endpoint is as follows:
identifier.iot.region.amazonaws.com
The shadow RESTful API follows the same HTTPS protocols/port mappings as described in AWS IoT
Protocols.
API Actions
• GetThingShadow (p. 341)
• UpdateThingShadow (p. 341)
• DeleteThingShadow (p. 342)
GetThingShadow
Gets the shadow for the specified thing.
The response state document includes the delta between the desired and reported states.
Request
The request includes the standard HTTP headers plus the following URI:
Response
Upon success, the response includes the standard HTTP headers plus the following code and body:
HTTP 200
BODY: response state document
For more information, see Example Response State Document (p. 350).
Authorization
Retrieving a shadow requires a policy that allows the caller to perform the iot:GetThingShadow
action. The Device Shadow service accepts two forms of authentication: Signature Version 4 with IAM
credentials or TLS mutual authentication with a client certificate.
The following is an example policy that allows a caller to retrieve a device's shadow:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "iot:GetThingShadow",
"Resource": ["arn:aws:iot:region:account:thing/thing"]
}]
}
UpdateThingShadow
Updates the shadow for the specified thing.
341
AWS IoT Developer Guide
DeleteThingShadow
Updates affect only the fields specified in the request state document. Any field with a value of null is
removed from the device's shadow.
Request
The request includes the standard HTTP headers plus the following URI and body:
For more information, see Example Request State Document (p. 350).
Response
Upon success, the response includes the standard HTTP headers plus the following code and body:
HTTP 200
BODY: response state document
For more information, see Example Response State Document (p. 350).
Authorization
Updating a shadow requires a policy that allows the caller to perform the iot:UpdateThingShadow
action. The Device Shadow service accepts two forms of authentication: Signature Version 4 with IAM
credentials or TLS mutual authentication with a client certificate.
The following is an example policy that allows a caller to update a device's shadow:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "iot:UpdateThingShadow",
"Resource": ["arn:aws:iot:region:account:thing/thing"]
}]
}
DeleteThingShadow
Deletes the shadow for the specified thing.
Request
The request includes the standard HTTP headers plus the following URI:
Response
Upon success, the response includes the standard HTTP headers plus the following code and body:
HTTP 200
BODY: Empty response state document
Authorization
342
AWS IoT Developer Guide
MQTT Pub/Sub Topics
Deleting a device's shadow requires a policy that allows the caller to perform the
iot:DeleteThingShadow action. The Device Shadow service accepts two forms of authentication:
Signature Version 4 with IAM credentials or TLS mutual authentication with a client certificate.
The following is an example policy that allows a caller to delete a device's shadow:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "iot:DeleteThingShadow",
"Resource": ["arn:aws:iot:region:account:thing/thing"]
}]
}
The following are the MQTT topics used for interacting with shadows.
Topics
• /update (p. 343)
• /update/accepted (p. 344)
• /update/documents (p. 345)
• /update/rejected (p. 345)
• /update/delta (p. 346)
• /get (p. 347)
• /get/accepted (p. 347)
• /get/rejected (p. 348)
• /delete (p. 348)
• /delete/accepted (p. 349)
• /delete/rejected (p. 349)
/update
Publish a request state document to this topic to update the device's shadow:
$aws/things/thingName/shadow/update
A client attempting to update the state of a thing would send a JSON request state document like this:
{
"state" : {
343
AWS IoT Developer Guide
/update/accepted
"desired" : {
"color" : "red",
"power" : "on"
}
}
}
A device updating its shadow would send a JSON request state document like this:
{
"state" : {
"reported" : {
"color" : "red",
"power" : "on"
}
}
}
AWS IoT responds by publishing to either /update/accepted (p. 344) or /update/rejected (p. 345).
Example Policy
The following is an example of the required policy:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["iot:Publish"],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/
update"]
}]
}
/update/accepted
AWS IoT publishes a response state document to this topic when it accepts a change for the device's
shadow:
$aws/things/thingName/shadow/update/accepted
Example Policy
The following is an example of the required policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": ["arn:aws:iot:region:account:topicfilter/$aws/things/thingName/shadow/
update/accepted"]
344
AWS IoT Developer Guide
/update/documents
},
{
"Effect": "Allow",
"Action": ["iot:Receive"],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/update/
accepted"]
}
]
}
/update/documents
AWS IoT publishes a state document to this topic whenever an update to the shadow is successfully
performed:
$aws/things/thingName/shadow/update/documents
The JSON document will contain two primary nodes: previous and current. The previous node will
contain the contents of the full shadow document before the update was performed while current will
contain the full shadow document after the update is successfully applied. When the shadow is updated
(created) for the first time, the previous node will contain null.
Example Policy
The following is an example of the required policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": ["arn:aws:iot:region:account:topicfilter/$aws/things/thingName/shadow/
update/documents"]
},
{
"Effect": "Allow",
"Action": ["iot:Receive"],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/update/
accepted"]
}
]
}
/update/rejected
AWS IoT publishes an error response document to this topic when it rejects a change for the device's
shadow:
$aws/things/thingName/shadow/update/rejected
Example Policy
The following is an example of the required policy:
345
AWS IoT Developer Guide
/update/delta
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": ["arn:aws:iot:region:account:topicfilter/$aws/things/thingName/shadow/
update/rejected"]
},
{
"Effect": "Allow",
"Action": ["iot:Receive"],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/update/
rejected"]
}
]
}
/update/delta
AWS IoT publishes a response state document to this topic when it accepts a change for the device's
shadow and the request state document contains different values for desired and reported states:
$aws/things/thingName/shadow/update/delta
Publishing Details
• A message published on update/delta includes only the desired attributes that differ between
the desired and reported sections. It contains all of these attributes, regardless of whether these
attributes were contained in the current update message or were already stored in AWS IoT. Attributes
that do not differ between the desired and reported sections are not included.
• If an attribute is in the reported section but has no equivalent in the desired section, it is not
included.
• If an attribute is in the desired section but has no equivalent in the reported section, it is included.
• If an attribute is deleted from the reported section but still exists in the desired section, it is
included.
Example Policy
The following is an example of the required policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": ["arn:aws:iot:region:account:topicfilter/$aws/things/thingName/shadow/
update/delta"]
},
{
"Effect": "Allow",
"Action": ["iot:Receive"],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/update/
delta"]
346
AWS IoT Developer Guide
/get
}
]
}
/get
Publish an empty message to this topic to get the device's shadow:
$aws/things/thingName/shadow/get
AWS IoT responds by publishing to either /get/accepted (p. 347) or /get/rejected (p. 348).
Example Policy
The following is an example of the required policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "iot:Publish" ],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/get"]
}
]
}
/get/accepted
AWS IoT publishes a response state document to this topic when returning the device's shadow:
$aws/things/thingName/shadow/get/accepted
Example Policy
The following is an example of the required policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": ["arn:aws:iot:region:account:topicfilter/$aws/things/thingName/shadow/
get/accepted"]
},
{
"Effect": "Allow",
"Action": ["iot:Receive"],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/get/
accepted"]
}
]
}
347
AWS IoT Developer Guide
/get/rejected
/get/rejected
AWS IoT publishes an error response document to this topic when it can't return the device's shadow:
$aws/things/thingName/shadow/get/rejected
Example Policy
The following is an example of the required policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": ["arn:aws:iot:region:account:topicfilter/$aws/things/thingName/shadow/
get/rejected"]
},
{
"Action": ["iot:Receive"],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/get/
rejected"]
}
]
}
/delete
To delete a device's shadow, publish an empty message to the delete topic:
$aws/things/thingName/shadow/delete
AWS IoT responds by publishing to either /delete/accepted (p. 349) or /delete/rejected (p. 349).
Example Policy
The following is an example of the required policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": ["arn:aws:iot:region:account:topicfilter/$aws/things/thingName/shadow/
delete"]
},
{
"Effect": "Allow",
"Action": ["iot:Receive"],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/
delete"]
}
348
AWS IoT Developer Guide
/delete/accepted
]
}
/delete/accepted
AWS IoT publishes a message to this topic when a device's shadow is deleted:
$aws/things/thingName/shadow/delete/accepted
Example Policy
The following is an example of the required policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": ["arn:aws:iot:region:account:topicfilter/$aws/things/thingName/shadow/
delete/accepted"]
},
{
"Effect": "Allow",
"Action": ["iot:Receive"],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/delete/
accepted"]
}
]
}
/delete/rejected
AWS IoT publishes an error response document to this topic when it can't delete the device's shadow:
$aws/things/thingName/shadow/delete/rejected
Example Policy
The following is an example of the required policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iot:Subscribe"],
"Resource": ["arn:aws:iot:region:account:topicfilter/$aws/things/thingName/shadow/
delete/rejected"]
},
{
"Effect": "Allow",
"Action": ["iot:Receive"],
"Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/delete/
rejected"]
349
AWS IoT Developer Guide
Document Syntax
}
]
}
Examples
• Request State Documents (p. 350)
• Response State Documents (p. 350)
• Error Response Documents (p. 351)
{
"state": {
"desired": {
"attribute1": integer2,
"attribute2": "string2",
...
"attributeN": boolean2
},
"reported": {
"attribute1": integer1,
"attribute2": "string1",
...
"attributeN": boolean1
}
},
"clientToken": "token",
"version": version
}
{
"state": {
"desired": {
"attribute1": integer2,
"attribute2": "string2",
...
"attributeN": boolean2
350
AWS IoT Developer Guide
Error Response Documents
},
"reported": {
"attribute1": integer1,
"attribute2": "string1",
...
"attributeN": boolean1
},
"delta": {
"attribute3": integerX,
"attribute5": "stringY"
}
},
"metadata": {
"desired": {
"attribute1": {
"timestamp": timestamp
},
"attribute2": {
"timestamp": timestamp
},
...
"attributeN": {
"timestamp": timestamp
}
},
"reported": {
"attribute1": {
"timestamp": timestamp
},
"attribute2": {
"timestamp": timestamp
},
...
"attributeN": {
"timestamp": timestamp
}
}
},
"timestamp": timestamp,
"clientToken": "token",
"version": version
}
• state
• reported — Only present if a thing reported any data in the reported section and contains only
fields that were in the request state document.
• desired — Only present if a thing reported any data in the desired section and contains only
fields that were in the request state document.
• metadata — Contains the timestamps for each attribute in the desired and reported sections so
that you can determine when the state was updated.
• timestamp — The Epoch date and time the response was generated by AWS IoT.
• clientToken — Present only if a client token was used when publishing valid JSON to the /update
topic.
• version — The current version of the document for the device's shadow shared in AWS IoT. It is
increased by one over the previous version of the document.
351
AWS IoT Developer Guide
Error Messages
{
"code": error-code,
"message": "error-message",
"timestamp": timestamp,
"clientToken": "token"
}
413 (Payload Too Large) • The payload exceeds the maximum size allowed
429 (Too Many Requests) • The Device Shadow service will generate this error
message when there are more than 10 in-flight requests.
352
AWS IoT Developer Guide
Error Messages
353
AWS IoT Developer Guide
Jobs Key Concepts
Jobs
AWS IoT jobs can be used to define a set of remote operations that are sent to and executed on one or
more devices connected to AWS IoT.
A job is a remote operation that is sent to and executed on one or more devices connected to
AWS IoT. For example, you can define a job that instructs a set of devices to download and install
application or firmware updates, reboot, rotate certificates, or perform remote troubleshooting
operations.
job document
To create a job, you must first create a job document that is a description of the remote operations
to be performed by the devices.
Job documents are UTF-8 encoded JSON documents and should contain any information your
devices need to perform a job. A job document will most likely contain one or more URLs where the
device can download an update or some other data. The job document itself can be stored in an
Amazon S3 bucket, or be included inline with the command that creates the job.
target
When you create a job, you specify a list of targets that are the devices that should perform the
operations. The targets can be things or thing groups (p. 160) or both. AWS IoT Jobs sends a
message to each target to inform it that a job is available.
job execution
A job execution is an instance of a job on a target device. The target starts an execution of a job by
downloading the job document. It then performs the operations the document specifies, and reports
its progress to AWS IoT. An execution number is a unique identifier of a specific job execution on a
specific target. The Jobs service provides commands to track the progress of a job execution on a
specific target and the progress of a job generally across all the targets of the job.
snapshot job
By default, a job is sent to all targets that you specify when you create the job. After those targets
complete the job (or report that they are unable to do so), the job is complete.
continuous job
A continuous job is sent to all targets that you specify when you create the job, but continues to
run and will be sent to any new devices (things) that are added to the target group. For example, a
continuous job can be used to onboard or upgrade devices as they are added to a group. You can
make a job continuous by setting an optional parameter when you create the job.
rollouts
You can specify how quickly targets are notified of a pending job execution. This allows you to create
a staged rollout to better manage updates, reboots, and other operations.
354
AWS IoT Developer Guide
Jobs Key Concepts
The following field can be added to the CreateJob request to specify the maximum number of
targets that will be informed of the job per minute. This example sets a static rollout rate.
"jobExecutionRolloutConfig": {
"maximumPerMinute": "integer"
}
You can also set a variable rollout rate with the exponentialRate field. The following example
creates a rollout that has an exponential rate.
"jobExecutionsRolloutConfig": {
"exponentialRate": {
"baseRatePerMinute": integer,
"incrementFactor": integer,
"rateIncreaseCriteria": {
"numberOfNotifiedThings": integer, // Set one or the other
"numberOfSucceededThings": integer // of these two values.
},
"maximumPerMinute": integer
}
}
For more information about configuring job rollouts, see Job Rollout and Abort Configuration.
abort
You can create a set of conditions to abort rollouts once certain criteria that you specify have been
met. For more information about configuring job abort conditions, see Job Rollout and Abort
Configuration.
presigned URLs
To allow a device secure, time-limited access to data beyond that included in the job document itself,
you can use presigned Amazon S3 URLs. You can place your data in an Amazon S3 bucket and add
a placeholder link to the data in the job document. When the Jobs service receives a request for the
job document, it parses the job document looking for placeholder links and it replaces them with
presigned Amazon S3 URLs.
${aws:iot:s3-presigned-url:https://s3.amazonaws.com/bucket/key}
where bucket is your bucket name and key is the object in the bucket to which you are linking.
timeouts
Note
The job timeout feature isn't currently available in the PDT (us-gov-west-1) Region.
Job timeouts enable you to be notified whenever a job execution gets stuck in the IN_PROGRESS
state for an unexpectedly long period of time. There are two types of timers: in progress timers and
step timers.
When you create a job, you can set a value for the inProgressTimeoutInMinutes property of
the optional TimeoutConfig object. The in progress timer can't be updated and will apply to all job
executions for the job. Whenever a job execution remains in the IN_PROGRESS status for longer
355
AWS IoT Developer Guide
Managing Jobs
than this interval, the job execution will fail and switch to the terminal TIMED_OUT status. AWS IoT
will also publish an MQTT notification.
You can also set a step timer for a specific job execution by setting a value for
stepTimeoutInMinutes when you call UpdateJobExecution. The step timer applies only to the job
execution that you update, and you can set a new value for this timer each time you update a job
execution. You can also create a step timer when you call StartNextPendingJobExecution. If the job
execution remains in the IN_PROGRESS status for longer than the step timer interval, it will fail and
switch to the terminal TIMED_OUT status. The step timer has no effect on the in progress timer that
you set when you create a job.
The following diagram and description illustrate the ways in which in progress timeouts and step
timeouts interact with each other.
Job Creation: CreateJob sets an in progress timer that expires in twenty minutes. This timer
applies to all job executions and can't be updated.
12:00 PM: The job execution starts and switches to IN_PROGRESS status. The in progress timer
starts to run.
12:05 PM: UpdateJobExecution creates a step timer with a value of 7 minutes. If a new step timer
isn't created, the job execution will time out at 12:12 PM.
12:10 PM: UpdateJobExecution creates a new step timer with a value of 5 minutes. The previous
step timer is discarded. If a new step timer isn't created, the job execution will time out at 12:15 PM.
12:13 PM: UpdateJobExecution creates a new step timer with a value of 9 minutes. The job
execution times out at 12:20 because the in progress timer expires at 12:20. The step timer can't
exceed the absolute bound created by the in progress timer.
UpdateJobExecution can also discard a step timer that has already been created by creating a
new step timer with a value of -1.
Managing Jobs
You can use the AWS IoT console, the Jobs HTTPS API, the AWS Command Line Interface, or the AWS
SDKs to create and manage jobs. For more information, see Job Management and Control API (p. 378),
AWS CLI Command Reference: iot or AWS SDKs and Tools.
The primary purpose of jobs is to notify devices of a software or firmware update. When sending code
to devices, the best practice is to sign the code file. This allows devices to detect if the code has been
modified in transit. The instructions in the following section are written with the assumption that you
want to code-sign the software update you are sending to your devices.
For more information about code-signing, see What Is Code Signing for AWS IoT?
Before you create a job, you must create a job document. If you are using Code-signing for AWS IoT, you
must upload your job document to a versioned Amazon S3 bucket. For more information about creating
an Amazon S3 bucket and uploading files to it, see Getting Started with Amazon Simple Storage Service
in the Amazon S3 Getting Started Guide.
Your job document can contain a presigned Amazon S3 URL that points to your code file (or other
file). Presigned Amazon S3 URLs are valid for a limited amount of time and so are not generated
until a device requests a job document. Because the presigned URL has not been created when
you are creating the job document, you put a placeholder URL in your job document instead.
356
AWS IoT Developer Guide
Creating and Managing Jobs (Console)
When a device requests the job document, AWS IoT generates the presigned URL and replaces the
placeholder URL with the presigned URL. Your job document is then sent to the device.
When you create a job that uses presigned Amazon S3 URLs, you must provide an IAM role that grants
permission to download files from the Amazon S3 bucket where the data or updates are stored. The role
must also grant permission for AWS IoT to assume the role.
You can specify an optional timeout for the presigned URL. For more information, see
CreateJob (p. 393).
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the navigation pane, choose Roles.
3. Search for your role and choose it.
4. Choose the Trust Relationships tab, and then choose Edit Trust Relationship.
5. On the Edit Trust Relationship page, replace the policy document with the following JSON:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": [
"iot.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::your_S3_bucket/*"
}
]
}
357
AWS IoT Developer Guide
Creating and Managing Jobs (CLI)
A placeholder for the code file should look like this: ${aws:iot:s3-presigned-url:https://
s3.amazonaws.com/<my-s3-bucket>/<my-code-file>}.
Note
Currently, versions are not supported for presigned URL placeholders for jobs. If you update
your code file and copy it to the same Amazon S3 location, you must create a new signature and
then reference the new signature version in your job document.
To create a job
After you create the job, the console generates a JSON signature and places it in your job document.
You can use the AWS IoT console to view the status, cancel, or delete a job.
Create Jobs
You use the CreateJob command to create an AWS IoT job. The job is queued for execution on the
targets (things or thing groups) that you specify. To create an AWS IoT job, you need a job document that
can be included in the body of the request or as a link to an Amazon S3 document. If the job includes
downloading files using presigned Amazon S3 URLs, you need an IAM role ARN that has permission to
download the file and grants permission to AWS IoT Jobs to assume the role.
358
AWS IoT Developer Guide
Creating and Managing Jobs (CLI)
Your job document must contain a pre-signed URL placeholder for your code file and the JSON
signature output placed in an Amazon S3 bucket using the start-signing-job command, enclosed in a
codesignelement:
{
"presign": "${aws:iot:s3-presigned-url:https://s3.region.amazonaws.com/bucket/image}",
"codesign": {
"rawPayloadSize": <image-file-size>,
"signature": <signature>,
"signatureAlgorithm": <signature-algorithm>,
"payloadLocation": {
"s3": {
"bucketName": <my-s3-bucket>,
"key": <my-code-file>,
"version": <code-file-version-id>
}
}
}
}
The optional timeout-config parameter specifies the amount of time each device has to finish its
execution of the job. The timer starts when the job execution status is set to IN_PROGRESS. If the job
execution status is not set to another terminal state before the time expires, it is set to TIMED_OUT.
Note
The job timeout feature isn't currently available in the PDT (us-gov-west-1) Region.
The in-progress timer can't be updated and applies to all job executions for the job. Whenever a job
execution remains in the IN_PROGRESS status for longer than this interval, the job execution fails and
switches to the terminal TIMED_OUT status. AWS IoT also publishes an MQTT notification.
359
AWS IoT Developer Guide
Creating and Managing Jobs (CLI)
For more information about creating configurations about job rollouts and aborts, see Job Rollout and
Abort Configuration.
Note
Job documents that are specified as Amazon S3 files are retrieved at the time you create the job.
Changing the contents of the Amazon S3 file you used as the source of your job document after
you have created the job does not change what is sent to the targets of the job.
Update a Job
You use the UpdateJob command to update a job. You can update the description,
presignedUrlConfig, jobExecutionsRolloutConfig, abortConfig, and timeoutConfig fields
of a job.
For more information about configuring job rollouts and aborts, see Job Rollout and Abort
Configuration.
Cancel a Job
You use the CancelJob command to cancel a job. Canceling a job stops AWS IoT from rolling out any new
job executions for the job. It also cancels any job executions that are in a QUEUED state. AWS IoT leaves
any job executions in a terminal state untouched because the device has already completed the job. If
the status of a job execution is IN_PROGRESS, it also remains untouched unless you use the optional --
force parameter.
{
"jobArn": "string",
"jobId": "string",
"description": "string"
}
When you cancel a job, job executions that are in a QUEUED state are canceled. Job executions that are in
an IN_PROGRESS state are canceled if you specify the optional --force parameter. Job executions in a
terminal state are not canceled.
Warning
Canceling a job that is in the IN_PROGRESS state (by setting the --force parameter) cancels
any job executions that are in progress and causes the device that is executing the job to
360
AWS IoT Developer Guide
Creating and Managing Jobs (CLI)
be unable to update the job execution status. Use caution and make sure that each device
executing a canceled job is able to recover to a valid state.
The status of a canceled job or of one of its job executions is eventually consistent. AWS IoT stops
scheduling new job executions and QUEUED job executions for that job to devices as soon as possible.
Changing the status of a job execution to CANCELED might take some time, depending on the number of
devices and other factors.
If a job is cancelled because it has met the criteria defined by an AbortConfig object, the service will
add auto-populated values for the comment and reasonCode fields. Customers can create their own
values for reasonCode when the job cancellation is user-driven.
The following command shows how to cancel the job execution from job 010 running on myThing.
A job execution that is in a QUEUED state is canceled. A job execution that is in an IN_PROGRESS state
is canceled if you specify the optional --force parameter. Job executions in a terminal state cannot be
canceled.
Warning
When you cancel a job execution that is in the IN_PROGRESS state, the device is unable to
update the job execution status. Use caution and ensure that the device is able to recover to a
valid state.
If the job execution is in a terminal state or if the job execution is in an IN_PROGRESS state and the --
force parameter is not set to true, this command causes an InvalidStateTransitionException.
The status of a canceled job execution is eventually consistent. Changing the status of a job execution to
CANCELED might take some time, depending various factors.
Delete a Job
You use the DeleteJob command to delete a job and its job executions. By default, you can only delete a
job that is in a terminal state (SUCCEEDED or CANCELED). Otherwise, an exception occurs. You can delete
a job in the IN_PROGRESS state if the force parameter is set to true.
It can take some time to delete a job, depending on the number of job executions created for the
job and various other factors. While the job is being deleted, DELETION_IN_PROGRESS appears as
361
AWS IoT Developer Guide
Creating and Managing Jobs (CLI)
the status of the job. An error results if you attempt to delete or cancel a job whose status is already
DELETION_IN_PROGRESS.
Only 10 jobs can have a status of DELETION_IN_PROGRESS at the same time. Otherwise, a
LimitExceededException occurs.
The command returns the job document for the specified job:
{
"document": "{\n\t\"operation\":\"install\",\n\t\"url\":\"http://amazon.com/
firmWareUpate-01\",\n\t\"data\":\"${aws:iot:s3-presigned-url:https://s3.amazonaws.com/job-
test-bucket/datafile}\"\n}"
}
Note
When you use this command to retrieve a job document, placeholder URLs are not replaced by
presigned Amazon S3 URLs. When a device calls the GetPendingJobExecutions (p. 437) MQTT
API, the placeholder URLs are replaced by presigned Amazon S3 URLs in the job document.
List Jobs
You use the ListJobs command to get a list of all jobs in your AWS account. Job data and job execution
data are purged after 90 days. Run the following command to list all jobs in your AWS account:
The command returns all jobs in your account, sorted by the job status:
{
"jobs": [
{
"status": "IN_PROGRESS",
"lastUpdatedAt": 1486687079.743,
"jobArn": "arn:aws:iot:us-east-1:123456789012:job/013",
"createdAt": 1486687079.743,
"targetSelection": "SNAPSHOT",
"jobId": "013"
},
{
"status": "SUCCEEDED",
"lastUpdatedAt": 1486685868.444,
"jobArn": "arn:aws:iot:us-east-1:123456789012:job/012",
"createdAt": 1486685868.444,
"completedAt": 148668789.690,
"targetSelection": "SNAPSHOT",
"jobId": "012"
},
{
362
AWS IoT Developer Guide
Creating and Managing Jobs (CLI)
"status": "CANCELED",
"lastUpdatedAt": 1486678850.575,
"jobArn": "arn:aws:iot:us-east-1:123456789012:job/011",
"createdAt": 1486678850.575,
"targetSelection": "SNAPSHOT",
"jobId": "011"
}
]
}
Describe a Job
Run the DescribeJob command to get the status of a specific job. The following command shows how to
describe a job:
The command returns the status of the specified job. For example:
{
"documentSource": "https://s3.amazonaws.com/job-test-bucket/job-document.json",
"job": {
"status": "IN_PROGRESS",
"jobArn": "arn:aws:iot:us-east-1:123456789012:job/010",
"targets": [
"arn:aws:iot:us-east-1:123456789012:thing/myThing"
],
"jobProcessDetails": {
"numberOfCanceledThings": 0,
"numberOfFailedThings": 0,
"numberOfInProgressThings": 0,
"numberOfQueuedThings": 0,
"numberOfRejectedThings": 0,
"numberOfRemovedThings": 0,
"numberOfSucceededThings": 0,
"numberOfTimedOutThings": 0,
"processingTargets": [
arn:aws:iot:us-east-1:123456789012:thing/thingOne,
arn:aws:iot:us-east-1:123456789012:thinggroup/thinggroupOne,
arn:aws:iot:us-east-1:123456789012:thing/thingTwo,
arn:aws:iot:us-east-1:123456789012:thinggroup/thinggroupTwo
]
},
"presignedUrlConfig": {
"expiresInSec": 60,
"roleArn": "arn:aws:iam::123456789012:role/S3DownloadRole"
},
"jobId": "010",
"lastUpdatedAt": 1486593195.006,
"createdAt": 1486593195.006,
"targetSelection": "SNAPSHOT",
"jobExecutionsRolloutConfig": {
"exponentialRate": {
"baseRatePerMinute": integer,
"incrementFactor": integer,
"rateIncreaseCriteria": {
"numberOfNotifiedThings": integer, // Set one or the other
"numberOfSucceededThings": integer // of these two values.
},
"maximumPerMinute": integer
}
},
363
AWS IoT Developer Guide
Creating and Managing Jobs (CLI)
"abortConfig": {
"criteriaList": [
{
"action": "string",
"failureType": "string",
"minNumberOfExecutedThings": integer,
"thresholdPercentage": integer
}
]
},
"timeoutConfig": {
"inProgressTimeoutInMinutes": number
}
}
}
{
"executionSummaries": [
{
"thingArn": "arn:aws:iot:us-east-1:123456789012:thing/thingOne",
"jobExecutionSummary": {
"status": "QUEUED",
"lastUpdatedAt": 1486593196.378,
"queuedAt": 1486593196.378,
"executionNumber": 1234567890
}
},
{
"thingArn": "arn:aws:iot:us-east-1:123456789012:thing/thingTwo",
"jobExecutionSummary": {
"status": "IN_PROGRESS",
"lastUpdatedAt": 1486593345.659,
"queuedAt": 1486593196.378,
"startedAt": 1486593345.659,
"executionNumber": 4567890123
}
}
]
}
The command returns a list of job executions that are running or have run on the specified thing:
364
AWS IoT Developer Guide
Creating and Managing Jobs (CLI)
{
"executionSummaries": [
{
"jobExecutionSummary": {
"status": "QUEUED",
"lastUpdatedAt": 1486687082.071,
"queuedAt": 1486687082.071,
"executionNumber": 9876543210
},
"jobId": "013"
},
{
"jobExecutionSummary": {
"status": "IN_PROGRESS",
"startAt": 1486685870.729,
"lastUpdatedAt": 1486685870.729,
"queuedAt": 1486685870.729,
"executionNumber": 1357924680
},
"jobId": "012"
},
{
"jobExecutionSummary": {
"status": "SUCCEEDED",
"startAt": 1486678853.415,
"lastUpdatedAt": 1486678853.415,
"queuedAt": 1486678853.415,
"executionNumber": 4357680912
},
"jobId": "011"
},
{
"jobExecutionSummary": {
"status": "CANCELED",
"startAt": 1486593196.378,
"lastUpdatedAt": 1486593196.378,
"queuedAt": 1486593196.378,
"executionNumber": 2143174250
},
"jobId": "010"
}
]
}
{
"execution": {
"jobId": "017",
"executionNumber": 4516820379,
"thingArn": "arn:aws:iot:us-east-1:123456789012:thing/thingOne",
"versionNumber": 123,
"createdAt": 1489084805.285,
365
AWS IoT Developer Guide
Devices and Jobs
"lastUpdatedAt": 1489086279.937,
"startedAt": 1489086279.937,
"status": "IN_PROGRESS",
"approximateSecondsBeforeTimedOut": 100,
"statusDetails": {
"status": "IN_PROGRESS",
"detailsMap": {
"percentComplete": "10"
}
}
}
}
By default, the status of the job execution must be QUEUED or in a terminal state (SUCCEEDED, FAILED,
REJECTED, TIMED_OUT, REMOVED or CANCELED). Otherwise, an error occurs. To delete a job execution
with a status of IN_PROGRESS, you can set the force parameter to true.
Warning
When you delete a job execution with a status of IN_PROGRESS, the device that is executing the
job cannot access job information or update the job execution status. Use caution and make sure
that the device is able to recover to a valid state.
Devices can communicate with the AWS IoT Jobs service through these methods:
• MQTT
• HTTP Signature Version 4
• HTTP TLS
Communication between the AWS IoT Jobs service and your devices can occur over the MQTT
protocol. Devices subscribe to MQTT topics to be notified of new jobs and to receive responses from
the AWS IoT Jobs service. Devices publish on MQTT topics to query or update the state of a job
execution. Each device has its own general MQTT topic. For more information about publishing and
subscribing to MQTT topics, see Message Broker for AWS IoT (p. 233).
Note
You must use the correct endpoint when you communicate with the AWS IoT Jobs service
through MQTT. Use the DescribeEndpoint command to find it. For example, if you run this
command:
366
AWS IoT Developer Guide
Devices and Jobs
{
"endpointAddress": "a1b2c3d4e5f6g7.iot.us-west-2.amazonaws.com"
}
With this method, your device uses its device-specific certificate and private key to
authenticate with the AWS IoT Jobs service.
Devices can:
• Be notified when a job execution is added or removed from the list of pending job executions by
subscribing to the $aws/things/thing-name/jobs/notify MQTT topic, where thing-name
is the name of the thing associated with the device.
• Be notified when the next pending job execution has changed by subscribing to the $aws/
things/thing-name/jobs/notify-next MQTT topic, where thing-name is the name of the
thing associated with the device.
• Update the status of a job execution by calling the UpdateJobExecution (p. 451) API.
• Query the status of a job execution by calling the DescribeJobExecution (p. 446) API.
• Retrieve a list of pending job executions by calling the GetPendingJobExecutions (p. 437) API.
• Retrieve the next pending job execution by calling the DescribeJobExecution (p. 446) API with
jobId $next.
• Get and start the next pending job execution by calling the
StartNextPendingJobExecution (p. 441) API.
The AWS IoT Jobs service publishes success and failure messages on an MQTT topic. The topic is
formed by appending accepted or rejected to the topic used to make the request. For example, if
a request message is published on the $aws/things/myThing/jobs/get topic, the AWS IoT Jobs
service publishes success messages on the $aws/things/myThing/jobs/get/accepted topic
and publishes rejected messages on the $aws/things/myThing/jobs/get/rejected topic.
using HTTP Signature Version 4
Communication between the AWS IoT Jobs service and your devices can occur over HTTP Signature
Version 4 on port 443. This is the method used by the AWS SDKs and CLI. For more information
about those tools, see AWS CLI Command Reference: iot-jobs-data or AWS SDKs and Tools and refer
to the IotJobsDataPlane section for your preferred language.
Note
You must use the correct endpoint when you communicate with the AWS IoT Jobs service
through HTTP Signature Version 4 or using an AWS SDK or CLI IotJobsDataPlane command.
Use the DescribeEndpoint command to find it. For example, if you run this command:
{
"endpointAddress": "a1b2c3d4e5f6g7.jobs.iot.us-west-2.amazonaws.com"
}
With this method of communication, your device uses IAM credentials to authenticate with
the AWS IoT Jobs service.
367
AWS IoT Developer Guide
Programming Devices to Work with Jobs
• DescribeJobExecution
Communication between the AWS IoT Jobs service and your devices can occur over HTTP TLS on
port 8443 using a third-party software client that supports this protocol.
Note
You must use the correct endpoint when you communicate with the AWS IoT Jobs service
through HTTP TLS. Use the DescribeEndpoint command to find it. For example, if you run
this command:
{
"endpointAddress": "a1b2c3d4e5f6g7.jobs.iot.us-west-2.amazonaws.com"
}
With this method, your device uses X.509 certificate-based authentication (for example, its
device-specific certificate and private key).
• DescribeJobExecution
• GetPendingJobExecutions
• StartNextPendingJobExecution
• UpdateJobExecution
368
AWS IoT Developer Guide
Programming Devices to Work with Jobs
• $aws/things/MyThing/jobs/jobId/get/rejected
If you are using Code-signing for AWS IoT your device code must verify the signature of your code file.
The signature will be in the job document within the codesign property. For more information about
verifying a code file signature, see Device Agent Sample.
Device Workflow
There are two ways a device can handle the jobs it is given to execute.
1. When a device first comes online, it should subscribe to the device's notify-next topic.
2. Call the DescribeJobExecution (p. 446) MQTT API with jobId $next to get the next job, its job
document, and other details, including any state saved in statusDetails. If the job document
has a code file signature, you must verify the signature before proceeding with processing the
job request.
3. Call the UpdateJobExecution (p. 451) MQTT API to update the job status. Or, to combine this
and the previous step in one call, the device can call StartNextPendingJobExecution (p. 441).
4. Optionally, you can add a step timer by setting a value for stepTimeoutInMinutes when you
call either UpdateJobExecution (p. 451) or StartNextPendingJobExecution (p. 441).
5. Perform the actions specified by the job document using the UpdateJobExecution (p. 451)
MQTT API to report on the progress of the job.
6. Continue to monitor the job execution by calling the DescribeJobExecution (p. 446) MQTT API
with this jobId. If the job execution is canceled or deleted while the device is running the job, the
device should be capable of recovering to a valid state.
7. Call the UpdateJobExecution (p. 451) MQTT API when finished with the job to update the job
status and report success or failure.
8. Because this job's execution status has been changed to a terminal state, the next job available
for execution (if any) changes. The device is notified that the next pending job execution has
changed. At this point, the device should continue as described in step 2.
If the device remains online, it continues to receive a notifications of the next pending job execution,
including its job execution data, when it completes a job or a new pending job execution is added.
When this occurs, the device continues as described in step 2.
Option B: Pick from available jobs
1. When a device first comes online, it should subscribe to the thing's notify topic.
2. Call the GetPendingJobExecutions (p. 437) MQTT API to get a list of pending job executions.
3. If the list contains one or more job executions, pick one.
4. Call the DescribeJobExecution (p. 446) MQTT API to get the job document and other details,
including any state saved in statusDetails.
5. Call the UpdateJobExecution (p. 451) MQTT API to update the job status. If the
includeJobDocument field is set to true in this command, the device can skip the previous
step and retrieve the job document at this point.
6. Optionally, you can add a step timer by setting a value for stepTimeoutInMinutes when you
call UpdateJobExecution (p. 451).
7. Perform the actions specified by the job document using the UpdateJobExecution (p. 451)
MQTT API to report on the progress of the job.
8. Continue to monitor the job execution by calling the DescribeJobExecution (p. 446) MQTT API
with this jobId. If the job execution is canceled or deleted while the device is running the job, the
device should be capable of recovering to a valid state.
369
AWS IoT Developer Guide
Programming Devices to Work with Jobs
9. Call the UpdateJobExecution (p. 451) MQTT API when finished with the job to update the job
status and to report success or failure.
If the device remains online, it is notified of all pending job executions when a new pending job
execution becomes available. When this occurs, the device can continue as described in step 2.
If the device is unable to execute the job, it should call the UpdateJobExecution (p. 451) MQTT API to
update the job status to REJECTED.
When a new job is created, the AWS IoT Jobs service publishes a message on the $aws/
things/thing-name/jobs/notify topic for each target device.
more info (1)
{
"timestamp":1476214217017,
"jobs":{
"QUEUED":[{
"jobId":"0001",
"queuedAt":1476214216981,
"lastUpdatedAt":1476214216981,
"versionNumber" : 1
}]
}
}
To get more information about a job execution, the device calls the DescribeJobExecution (p. 446)
MQTT API with the includeJobDocument field set to true (the default).
more info (2)
If the request is successful, the AWS IoT Jobs service publishes a message on the $aws/things/
MyThing/jobs/0023/get/accepted topic:
{
"clientToken" : "client-001",
"timestamp" : 1489097434407,
"execution" : {
"approximateSecondsBeforeTimedOut": number,
"jobId" : "023",
"status" : "QUEUED",
"queuedAt" : 1489097374841,
"lastUpdatedAt" : 1489097374841,
"versionNumber" : 1,
"jobDocument" : {
< contents of job document >
}
}
370
AWS IoT Developer Guide
Programming Devices to Work with Jobs
Note
If the request fails, the AWS IoT Jobs service publishes a message on the $aws/things/
MyThing/jobs/0023/get/rejected topic.
The device now has the job document that it can use to perform the remote operations for the job. If
the job document contains an Amazon S3 presigned URL, the device can use that URL to download any
required files for the job.
As the device is executing the job, it can call the UpdateJobExecution (p. 451) MQTT API to update
the status of the job execution.
more info (3)
For example, a device can update the job execution status to IN_PROGRESS by publishing the
following message on the $aws/things/MyThing/jobs/0023/update topic:
{
"status":"IN_PROGRESS",
"statusDetails": {
"progress":"50%"
},
"expectedVersion":"1",
"clientToken":"client001"
}
{
"clientToken":"client001",
"timestamp":1476289222841
}
If the job contains a TimeoutConfig, the in-progress timer starts running. You can also set a
step timer for a job execution by setting a value for stepTimeoutInMinutes when you call
UpdateJobExecution. The step timer applies only to the job execution that you update. You can set a
new value for this timer each time you update a job execution. You can also create a step timer when
you call StartNextPendingJobExecution. If the job execution remains in the IN_PROGRESS status for
longer than the step timer interval, it fails and switches to the terminal TIMED_OUT status. The step
timer has no effect on the in-progress timer that you set when you create a job.
Note
The job timeout feature isn't currently available in the PDT (us-gov-west-1) Region.
The status field can be set to IN_PROGRESS, SUCCEEDED, or FAILED. You cannot update the
status of a job execution that is already in a terminal state.
371
AWS IoT Developer Guide
Programming Devices to Work with Jobs
When the device is finished executing the job, it calls the UpdateJobExecution (p. 451) MQTT API. If
the job was successful, set status to SUCCEEDED and, in the message payload, in statusDetails,
add other information about the job as name-value pairs. The in-progress and step timers end when
the job execution is complete.
more info (4)
For example:
{
"status":"SUCCEEDED",
"statusDetails": {
"progress":"100%"
},
"expectedVersion":"2",
"clientToken":"client-001"
}
If the job was not successful, set status to FAILED and, in statusDetails, add information about
the error that occurred:
{
"status":"FAILED",
"statusDetails": {
"errorCode":"101",
"errorMsg":"Unable to install update"
},
"expectedVersion":"2",
"clientToken":"client-001"
}
Note
The statusDetails attribute can contain any number of name-value pairs.
When the AWS IoT Jobs service receives this update, it publishes a message on the $aws/things/
MyThing/jobs/notify topic to indicate the job execution is complete:
{
"timestamp":1476290692776,
"jobs":{}
}
Additional Jobs
additional jobs
If there are other job executions pending for the device, they are included in the message published
to $aws/things/MyThing/jobs/notify.
more info (5)
For example:
{
"timestamp":1476290692776,
"jobs":{
372
AWS IoT Developer Guide
Programming Devices to Work with Jobs
"QUEUED":[{
"jobId":"0002",
"queuedAt":1476290646230,
"lastUpdatedAt":1476290646230
}],
"IN_PROGRESS":[{
"jobId":"0003",
"queuedAt":1476290646230,
"lastUpdatedAt":1476290646230
}]
}
}
Jobs Notifications
The AWS IoT Jobs service publishes MQTT messages to reserved topics when jobs are pending or when
the first job execution in the list changes. Devices can keep track of pending jobs by subscribing to these
topics.
Job notifications are published to MQTT topics as JSON payloads. There are two kinds of notifications:
• A ListNotification contains a list of no more than 10 pending job executions. The job executions
in this list have status values of either IN_PROGRESS or QUEUED. They are sorted by status
(IN_PROGRESS job executions before QUEUED job executions) and then by the times when they were
queued.
A NextNotification is published whenever the first job execution in the list changes.
• A new job execution is added to the list as QUEUED, and it is the first one in the list.
• The status of an existing job execution that was not the first one in the list changes from QUEUED
to IN_PROGRESS and becomes the first one in the list. (This happens when there are no other
IN_PROGRESS job executions in the list or when the job execution whose status changes from
QUEUED to IN_PROGRESS was queued earlier than any other IN_PROGRESS job execution in the list.)
• The status of the job execution that is first in the list changes to a terminal status and is removed
from the list.
For more information about publishing and subscribing to MQTT topics, see Message Broker for AWS
IoT (p. 233).
Note
Notifications are not available when you use HTTP Signature Version 4 or HTTP TLS to
communicate with jobs.
job pending
The AWS IoT Jobs service publishes a message on an MQTT topic when a job is added to or removed
from the list of pending job executions for a thing or the first job execution in the list changes:
• $aws/things/thingName/jobs/notify
• $aws/things/thingName/jobs/notify-next
373
AWS IoT Developer Guide
Programming Devices to Work with Jobs
$aws/things/thingName/jobs/notify:
{
"timestamp" : 10011,
"jobs" : {
"IN_PROGRESS" : [ {
"jobId" : "other-job",
"queuedAt" : 10003,
"lastUpdatedAt" : 10009,
"executionNumber" : 1,
"versionNumber" : 1
} ],
"QUEUED" : [ {
"jobId" : "this-job",
"queuedAt" : 10011,
"lastUpdatedAt" : 10011,
"executionNumber" : 1,
"versionNumber" : 0
} ]
}
}
$aws/things/thingName/jobs/notify-next:
{
"timestamp" : 10011,
"execution" : {
"jobId" : "other-job",
"status" : "IN_PROGRESS",
"queuedAt" : 10009,
"lastUpdatedAt" : 10009,
"versionNumber" : 1,
"executionNumber" : 1,
"jobDocument" : {"c":"d"}
}
}
Possible job execution status values are QUEUED, IN_PROGRESS, FAILED, SUCCEEDED, CANCELED,
TIMED_OUT, REJECTED, and REMOVED.
The following series of examples show the notifications that are published to each topic as job
executions are created and change from one state to another.
First, one job, called job1, is created. This notification is published to the jobs/notify topic:
{
"timestamp": 1517016948,
"jobs": {
"QUEUED": [
{
"jobId": "job1",
"queuedAt": 1517016947,
"lastUpdatedAt": 1517016947,
"executionNumber": 1,
"versionNumber": 1
}
]
374
AWS IoT Developer Guide
Programming Devices to Work with Jobs
}
}
{
"timestamp": 1517016948,
"execution": {
"jobId": "job1",
"status": "QUEUED",
"queuedAt": 1517016947,
"lastUpdatedAt": 1517016947,
"versionNumber": 1,
"executionNumber": 1,
"jobDocument": {
"operation": "test"
}
}
}
When another job is created (job2), this notification is published to the jobs/notify topic:
{
"timestamp": 1517017192,
"jobs": {
"QUEUED": [
{
"jobId": "job1",
"queuedAt": 1517016947,
"lastUpdatedAt": 1517016947,
"executionNumber": 1,
"versionNumber": 1
},
{
"jobId": "job2",
"queuedAt": 1517017191,
"lastUpdatedAt": 1517017191,
"executionNumber": 1,
"versionNumber": 1
}
]
}
}
A notification is not published to the jobs/notify-next topic because the next job in the queue
(job1) has not changed. When job1 starts to execute, its status changes to IN_PROGRESS. No
notifications are published because the list of jobs and the next job in the queue have not changed.
When a third job (job3) is added, this notification is published to the jobs/notify topic:
{
"timestamp": 1517017906,
"jobs": {
"IN_PROGRESS": [
{
"jobId": "job1",
"queuedAt": 1517016947,
"lastUpdatedAt": 1517017472,
"startedAt": 1517017472,
"executionNumber": 1,
"versionNumber": 2
375
AWS IoT Developer Guide
Programming Devices to Work with Jobs
}
],
"QUEUED": [
{
"jobId": "job2",
"queuedAt": 1517017191,
"lastUpdatedAt": 1517017191,
"executionNumber": 1,
"versionNumber": 1
},
{
"jobId": "job3",
"queuedAt": 1517017905,
"lastUpdatedAt": 1517017905,
"executionNumber": 1,
"versionNumber": 1
}
]
}
}
A notification is not published to the jobs/notify-next topic because the next job in the queue is
still job1.
When job1 is complete, its status changes to SUCCEEDED, and this notification is published to the
jobs/notify topic:
{
"timestamp": 1517186269,
"jobs": {
"QUEUED": [
{
"jobId": "job2",
"queuedAt": 1517017191,
"lastUpdatedAt": 1517017191,
"executionNumber": 1,
"versionNumber": 1
},
{
"jobId": "job3",
"queuedAt": 1517017905,
"lastUpdatedAt": 1517017905,
"executionNumber": 1,
"versionNumber": 1
}
]
}
}
At this point, job1 has been removed from the queue, and the next job to be executed is job2. This
notification is published to the jobs/notify-next topic:
{
"timestamp": 1517186269,
"execution": {
"jobId": "job2",
"status": "QUEUED",
"queuedAt": 1517017191,
"lastUpdatedAt": 1517017191,
"versionNumber": 1,
"executionNumber": 1,
"jobDocument": {
"operation": "test"
376
AWS IoT Developer Guide
Programming Devices to Work with Jobs
}
}
}
If job3 must begin executing before job2 (which is not recommended), the status of job3 can be
changed to IN_PROGRESS. If this happens, job2 is no longer next in the queue, and this notification
is published to the jobs/notify-next topic:
{
"timestamp": 1517186779,
"execution": {
"jobId": "job3",
"status": "IN_PROGRESS",
"queuedAt": 1517017905,
"startedAt": 1517186779,
"lastUpdatedAt": 1517186779,
"versionNumber": 2,
"executionNumber": 1,
"jobDocument": {
"operation": "test"
}
}
}
No notification is published to the jobs/notify topic because no job has been added or removed.
If the device rejects job2 and updates its status to REJECTED, this notification is published to the
jobs/notify topic:
{
"timestamp": 1517189392,
"jobs": {
"IN_PROGRESS": [
{
"jobId": "job3",
"queuedAt": 1517017905,
"lastUpdatedAt": 1517186779,
"startedAt": 1517186779,
"executionNumber": 1,
"versionNumber": 2
}
]
}
}
If job3 (which is still in progress) is force deleted, this notification is published to the jobs/notify
topic:
{
"timestamp": 1517189551,
"jobs": {}
}
At this point, the queue is empty. This notification is published to the jobs/notify-next topic:
{
"timestamp": 1517189551
}
377
AWS IoT Developer Guide
Using the AWS IoT Jobs APIs
In general, job management and control uses an HTTPS protocol API. Devices can use either an MQTT or
an HTTPS protocol API. (The HTTPS API is designed for a low volume of calls typical when creating and
tracking jobs. It usually opens a connection for a single request, and then closes the connection after the
response is received. The MQTT API allows long polling. It is designed for large amounts of traffic that
can scale to millions of devices.)
Note
Each AWS IoT Jobs HTTPS API has a corresponding command that allows you to call the API
from the AWS CLI. The commands are lowercase, with hyphens between the words that make up
the name of the API. For example, you can invoke the CreateJob API on the CLI by typing:
Job
Job data type
{
"jobArn": "string",
"jobId": "string",
"status": "IN_PROGRESS|CANCELED|SUCCEEDED",
"forceCanceled": boolean,
"targetSelection": "CONTINUOUS|SNAPSHOT",
"comment": "string",
"targets": ["string"],
"description": "string",
"createdAt": timestamp,
"lastUpdatedAt": timestamp,
"completedAt": timestamp,
"jobProcessDetails": {
"processingTargets": ["string"],
"numberOfCanceledThings": long,
"numberOfSucceededThings": long,
"numberOfFailedThings": long,
"numberOfRejectedThings": long,
"numberOfQueuedThings": long,
"numberOfInProgressThings": long,
"numberOfRemovedThings": long,
378
AWS IoT Developer Guide
Job Management and Control API
"numberOfTimedOutThings": long
},
"presignedUrlConfig": {
"expiresInSec": number,
"roleArn": "string"
},
"jobExecutionsRolloutConfig": {
"exponentialRate": {
"baseRatePerMinute": integer,
"incrementFactor": integer,
"rateIncreaseCriteria": {
"numberOfNotifiedThings": integer, // Set one or the other
"numberOfSucceededThings": integer // of these two values.
},
"maximumPerMinute": integer
}
},
"abortConfig": {
"criteriaList": [
{
"action": "string",
"failureType": "string",
"minNumberOfExecutedThings": integer,
"thresholdPercentage": integer
}
]
},
"timeoutConfig": {
"inProgressTimeoutInMinutes": long
}
}
description (1)
jobArn
The unique identifier you assigned to this job when it was created.
status
Specifies whether the job continues to run (CONTINUOUS) or is complete after those things
specified as targets have completed the job (SNAPSHOT). If CONTINUOUS, the job might also
be run on a thing when a change is detected in a target. For example, a job runs on a thing when
the thing is added to a target group, even after the job was completed by all things originally in
the group.
comment
If the job was updated, describes the reason for the update.
targets
A list of AWS IoT things and thing groups to which the job should be sent.
description
379
AWS IoT Developer Guide
Job Management and Control API
createdAt
The time, in seconds since the epoch, when the job was created.
lastUpdatedAt
The time, in seconds since the epoch, when the job was last updated.
completedAt
The time, in seconds since the epoch, when the job was completed.
jobProcessDetails
A list of AWS IoT things and thing groups that are currently executing the job.
numberOfCanceledThings
The number of AWS IoT things that successfully completed the job.
numberOfFailedThings
The number of AWS IoT things that failed to complete the job.
numberOfRejectedThings
The number of AWS IoT things that are awaiting execution of the job.
numberOfInProgressThings
The number of AWS IoT things that are currently executing the job.
numberOfRemovedThings
The number of AWS IoT things that are no longer scheduled to execute the job because they
have been deleted or removed from the group that was a target of the job.
numberOfTimedOutThings
How long (in seconds) presigned URLs are valid. Valid values are 60 - 3600. The default
value is 3600 seconds. Presigned URLs are generated when the AWS IoT Jobs service
receives an MQTT request for the job document.
roleArn
The ARN of an IAM role that grants permission to download files from an Amazon S3
bucket. The role must also grant permission for AWS IoT to download the files. For more
information about how to create and configure the role, see Create Jobs (p. 358).
380
AWS IoT Developer Guide
Job Management and Control API
jobExecutionRolloutConfig
The maximum number of things (devices) to which the job is sent for execution, per minute.
exponentialRate
The minimum number of things that are notified of a pending job, per minute, at the
start of job rollout. This parameter allows you to define the initial rate of rollout.
incrementFactor
The criteria to initiate the increase in rate of rollout for a job. You can specify either
numberOfNotifiedThings or numberOfSucceededThing, but not both.
numberOfNotifiedThings
The threshold for number of notified things that initiate the increase in rate of
rollout.
numberOfSucceededThings
The threshold for number of succeeded things that initiate the increase in rate of
rollout.
abortConfig
The type of job execution failure to define a rule to initiate a job abort.
minNumberOfExecutedThings
The threshold as a percentage of the total number of executed things that initiate a job
abort.
timeoutConfig
Optional. Specifies the amount of time each device has to finish its execution of the job. The
timer is started when the job execution status is set to IN_PROGRESS. If the job execution status
is not set to another terminal state before the time expires, it is set to TIMED_OUT.
381
AWS IoT Developer Guide
Job Management and Control API
Note
The job timeout feature isn't currently available in the PDT (us-gov-west-1) Region.
inProgressTimeoutInMinutes
Specifies the amount of time, in minutes, this device has to finish execution of this
job. A timer is started, or restarted, whenever this job's execution status is specified as
IN_PROGRESS with this field populated. If the job execution status is not set to a terminal
state before the timer expires, or before another job execution status update is sent with
this field populated, the status is set to TIMED_OUT.
JobSummary
JobSummary data type
{
"jobArn": "string",
"jobId": "string",
"status": "IN_PROGRESS|CANCELED|SUCCEEDED",
"targetSelection": "CONTINUOUS|SNAPSHOT",
"thingGroupId": "string",
"createdAt": timestamp,
"lastUpdatedAt": timestamp,
"completedAt": timestamp
}
description (2)
jobArn
The unique identifier you assigned to this job when it was created.
status
Specifies whether the job continues to run (CONTINUOUS) or is complete after all those things
specified as targets have completed the job (SNAPSHOT). If CONTINUOUS, the job might also
be run on a thing when a change is detected in a target. For example, a job runs on a thing when
the thing is added to a target group, even after the job was completed by all things originally in
the group.
thingGroupId
The UNIX timestamp for when the job was last updated.
382
AWS IoT Developer Guide
Job Management and Control API
completedAt
JobExecution
JobExection data type
{
"approximateSecondsBeforeTimedOut": 50,
"executionNumber": 1234567890,
"forceCanceled": true|false,
"jobId": "string",
"lastUpdatedAt": timestamp,
"queuedAt": timestamp,
"startedAt": timestamp,
"status": "QUEUED|IN_PROGRESS|FAILED|SUCCEEDED|CANCELED|TIMED_OUT|REJECTED|
REMOVED",
"forceCanceled": boolean,
"statusDetails": {
"detailsMap": {
"string": "string" ...
},
"status": "string"
},
"thingArn": "string",
"versionNumber": 123
}
description (3)
approximateSecondsBeforeTimedOut
The estimated number of seconds that remain before the job execution status is changed to
TIMED_OUT. The timeout interval can be anywhere between 1 minute and 7 days (1 to 10080
minutes). The actual job execution timeout can occur up to 60 seconds later than the estimated
duration.
jobId
The unique identifier you assigned to this job when it was created.
executionNumber
A number that identifies this job execution on this device. It can be used later in commands that
return or update job execution information.
thingArn
The time, in seconds since the epoch, when the job execution was queued.
lastUpdatedAt
The time, in seconds since the epoch, when the job execution was last updated.
startedAt
The time, in seconds since the epoch, when the job execution was started.
383
AWS IoT Developer Guide
Job Management and Control API
status
The status of the job execution. Can be one of QUEUED, IN_PROGRESS, FAILED, SUCCEEDED,
CANCELED, TIMED_OUT, REJECTED, or REMOVED.
statusDetails
A collection of name-value pairs that describe the status of the job execution.
JobExecutionSummary
JobExecutionSummary data type
{
"executionNumber": 1234567890,
"queuedAt": timestamp,
"lastUpdatedAt": timestamp,
"startedAt": timestamp,
"status": "QUEUED|IN_PROGRESS|FAILED|SUCCEEDED|CANCELED|TIMED_OUT|REJECTED|REMOVED"
}
description (4)
executionNumber
A number that identifies a job execution on a device. It can be used later in commands that
return or update job execution information.
queuedAt
The time, in seconds since the epoch, when the job execution was queued.
lastUpdatedAt
The time, in seconds since the epoch, when the job execution was last updated.
startAt
The time, in seconds since the epoch, when the job execution was started.
status
The status of the job execution: QUEUED, IN_PROGRESS, FAILED, SUCCEEDED, CANCELED,
TIMED_OUT, REJECTED, or REMOVED.
JobExecutionSummaryForJob
JobExecutionSummaryForJob data type
{
"executionSummaries": [
{
384
AWS IoT Developer Guide
Job Management and Control API
"thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyThing",
"jobExecutionSummary": {
"status": "IN_PROGRESS",
"lastUpdatedAt": 1549395301.389,
"queuedAt": 1541526002.609,
"executionNumber": 1
}
},
...
]
}
description (5)
thingArn
JobExecutionSummaryForThing
JobExecutionSummaryForThing data type
{
"executionSummaries": [
{
"jobExecutionSummary": {
"status": "IN_PROGRESS",
"lastUpdatedAt": 1549395301.389,
"queuedAt": 1541526002.609,
"executionNumber": 1
},
"jobId": "MyThingJob"
},
...
]
}
description (6)
jobId
The unique identifier you assigned to this job when it was created.
jobExecutionSummary
385
AWS IoT Developer Guide
Job Management and Control API
AssociateTargetsWithJob
AssociateTargetsWithJob command
Associates a group with a continuous job. For more information, see CreateJob (p. 393). The
following criteria must be met:
• The job must have been created with the targetSelection field set to CONTINUOUS.
• The job status must currently be IN_PROGRESS.
• The total number of targets associated with a job must not exceed 100.
HTTPS (1)
Request:
POST /jobs/jobId/targets
{
"targets": [ "string" ],
"comment": "string"
}
jobId
The unique identifier you assigned to this job when it was created.
targets
A list of thing group ARNs that define the targets of the job.
comment
Optional. A comment string that describes why the job was associated with the targets.
Response:
{
"jobArn": "string",
"jobId": "string",
"description": "string"
}
jobArn
The unique identifier you assigned to this job when it was created.
description
CLI (1)
Synopsis:
386
AWS IoT Developer Guide
Job Management and Control API
[--comment <value>] \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format:
{
"targets": [
"string"
],
"jobId": "string",
"comment": "string"
}
cli-input-json fields:
TargetArn string
Output:
{
"jobArn": "string",
"jobId": "string",
"description": "string"
}
387
AWS IoT Developer Guide
Job Management and Control API
MQTT (1)
Not available.
CancelJob
CancelJob command
Cancels a job.
HTTPS (2)
Request:
PUT /jobs/jobId/cancel
{
"force": boolean,
"comment": "string",
"reasonCode": "string"
}
jobId
The unique identifier you assigned to this job when it was created.
force
[Optional] If true, job executions with status IN_PROGRESS and QUEUED are canceled.
Otherwise, only job executions with status QUEUED are canceled. The default is false.
Warning
Canceling a job with a status of IN_PROGRESS causes a device that is executing the job
to be unable to update the job execution status. Use caution and make sure that each
device executing a job that is canceled is able to recover to a valid state.
comment
[Optional] A comment string that describes why the job was canceled.
reasonCode
[Optional] A reason code string that explains why the job was canceled. If a job is cancelled
because it meets the conditions defined by an abortConfig, this field is auto-populated.
Response:
{
"jobArn": "string",
"jobId": "string",
"description": "string"
}
jobArn
388
AWS IoT Developer Guide
Job Management and Control API
jobId
The unique identifier you assigned to this job when it was created.
description
CLI (2)
Synopsis:
cli-input-json format:
{
"jobId": "string",
"force": boolean,
"comment": "string"
}
cli-input-json fields:
389
AWS IoT Developer Guide
Job Management and Control API
Output:
{
"jobArn": "string",
"jobId": "string",
"description": "string"
}
pattern: [^\\p{C}]+
MQTT (2)
Not available.
CancelJobExecution
CancelJobExecution command
Request:
PUT /things/thingName/jobs/jobId/cancel
390
AWS IoT Developer Guide
Job Management and Control API
"force": boolean,
"expectedVersion": "string",
"statusDetails": {
"string": "string"
...
}
}
thingName
The unique identifier you assigned to the job when it was created.
force
Optional. If true, a job execution with a status of IN_PROGRESS or QUEUED can be canceled.
Otherwise, only a job execution with status of QUEUED can be canceled. If you attempt to
cancel a job execution with a status of IN_PROGRESS and you do not set force to true, an
InvalidStateTransitionException is thrown. The default is false.
Warning
Canceling a job with a status of IN_PROGRESS causes a device that is executing the job
to be unable to update the job execution status. Use caution and make sure that each
device executing a job that is canceled is able to recover to a valid state.
expectedVersion
Optional. The expected current version of the job execution. Each time you update the job
execution, its version is incremented. If the version of the job execution stored in the AWS IoT
Jobs service does not match, the update is rejected with a VersionConflictException error,
and an ErrorResponse that contains the current job execution status data is returned. (This
makes it unnecessary to perform a separate DescribeJobExecution request to obtain the job
execution status data.)
statusDetails
Optional. A collection of name-value pairs that describe the status of the job execution.
Response:
{
}
CLI (3)
Synopsis:
cli-input-json format:
{
"jobId": "string",
391
AWS IoT Developer Guide
Job Management and Control API
"thingName": "string",
"force": boolean,
"expectedVersion": long,
"statusDetails": {
"string": "string"
}
}
cli-input-json fields:
pattern: [a-zA-Z0-9_-]+
392
AWS IoT Developer Guide
Job Management and Control API
DetailsKey string
pattern: [a-zA-Z0-9:_-]+
DetailsValue string
pattern: [^\\p{C}]*+
Output:
None
MQTT (3)
Not available.
CreateJob
CreateJob command
Creates a job. You can provide the job document as a link to a file in an Amazon S3 bucket
(documentSource parameter) or in the body of the request (document parameter).
A job can have an optional TimeoutConfig, which sets the value of the in-progress timer. The in-
progress timer can't be updated and applies to all executions of the job.
Note
The job timeout feature isn't currently available in the PDT (us-gov-west-1) Region.
393
AWS IoT Developer Guide
Job Management and Control API
• The targets argument must be a list of valid thing or thing group ARNs. All things and thing
groups must be in your AWS account.
• The documentSource argument must be a valid Amazon S3 URL to a job document. Amazon S3
URLs are of the form: https://s3.amazonaws.com/bucketName/objectName.
• The document stored in the URL specified by the documentSource argument must be a UTF-8
encoded JSON document.
• The size of a job document is limited to 32 KB due to the limit on the size of an MQTT
message(128 KB) and encryption.
• The jobId must be unique in your AWS account.
HTTPS (4)
Request:
PUT /jobs/jobId
{
"targets": [ "string" ],
"document": "string",
"documentSource": "string",
"description": "string",
"presignedUrlConfigData": {
"roleArn": "string",
"expiresInSec": "integer"
},
"targetSelection": "CONTINUOUS|SNAPSHOT",
"jobExecutionsRolloutConfig": {
"exponentialRate": {
"baseRatePerMinute": integer,
"incrementFactor": integer,
"rateIncreaseCriteria": {
"numberOfNotifiedThings": integer, // Set one or the other
"numberOfSucceededThings": integer // of these two values.
},
"maximumPerMinute": integer
}
},
"abortConfig": {
"criteriaList": [
{
"action": "string",
"failureType": "string",
"minNumberOfExecutedThings": integer,
"thresholdPercentage": integer
}
]
},
"timeoutConfig": {
"inProgressTimeoutInMinutes": long
}
}
jobId
A job identifier, which must be unique for your AWS account. We recommend using a UUID.
Alphanumeric characters, "-", and "_" can be used here.
targets
A list of thing or thing group ARNs that defines the targets of the job.
394
AWS IoT Developer Guide
Job Management and Control API
document
The ARN of the IAM role that contains permissions to access the Amazon S3 bucket. This
is the bucket that contains the data that devices download with the presigned Amazon
S3 URLs. This role must also grant AWS IoT permission to assume the role. For more
information, see Create Jobs (p. 358).
expiresInSec
How long (in seconds) presigned URLs are valid. Valid values are 60 - 3600. The default
value is 3600 seconds. Presigned URLs are generated when the AWS IoT Jobs service
receives an MQTT request for the job document.
targetSelection
Optional. Specifies whether the job continues to run (CONTINUOUS) or is complete after all
those things specified as targets have completed the job (SNAPSHOT). If CONTINUOUS, the job
might also be scheduled to run on a thing when a change is detected in a target. For example, a
job is scheduled to run on a thing when the thing is added to a target group, even after the job
was completed by all things originally in the group.
jobExecutionRolloutConfig
The maximum number of things on which the job is sent for execution, per minute. Valid
values are 1 to 1000. If not specified, the default is 1000. The actual number of things that
receive the job might be less during any particular minute interval (due to system latency),
but is not more than the specified value.
exponentialRate
The minimum number of things that are notified of a pending job, per minute, at the
start of job rollout. This parameter allows you to define the initial rate of rollout.
incrementFactor
The criteria to initiate the increase in rate of rollout for a job. Set values for either the
numberOfNotifiedThings or numberOfSucceededThings, but not both.
395
AWS IoT Developer Guide
Job Management and Control API
numberOfNotifiedThings
The threshold for number of notified things that initiate the increase in rate of
rollout.
numberOfSucceededThings
The threshold for number of succeeded things that initiate the increase in rate of
rollout.
abortConfig
The type of job execution failure to define a rule to initiate a job abort.
minNumberOfExecutedThings
The threshold as a percentage of the total number of executed things that initiate a job
abort.
timeoutConfig
Optional. Specifies the amount of time each device has to finish its execution of the job. The
timer is started when the job execution status is set to IN_PROGRESS. If the job execution status
is not set to another terminal state before the time expires, it is set to TIMED_OUT.
Note
The job timeout feature isn't currently available in the PDT (us-gov-west-1) Region.
inProgressTimeoutInMinutes
Specifies the amount of time, in minutes, this device has to finish execution of this
job. A timer is started, or restarted, whenever this job's execution status is specified as
IN_PROGRESS with this field populated. If the job execution status is not set to a terminal
state before the timer expires, or before another job execution status update is sent with
this field populated, the status is set to TIMED_OUT.
Response:
{
"jobArn": "string",
"jobId": "string",
"description": "string"
}
jobArn
396
AWS IoT Developer Guide
Job Management and Control API
description
CLI (4)
Synopsis:
cli-input-json format:
{
"jobId": "string",
"targets": [
"string"
],
"documentSource": "string",
"document": "string",
"description": "string",
"presignedUrlConfig": {
"roleArn": "string",
"expiresInSec": long
},
"targetSelection": "string",
"jobExecutionsRolloutConfig": {
"exponentialRate": {
"baseRatePerMinute": integer,
"incrementFactor": integer,
"rateIncreaseCriteria": {
"numberOfNotifiedThings": integer, // Set one or the other
"numberOfSucceededThings": integer // of these two values.
},
"maximumPerMinute": integer
}
},
"abortConfig": {
"criteriaList": [
{
"action": "string",
"failureType": "string",
"minNumberOfExecutedThings": integer,
"thresholdPercentage": integer
}
]
},
"timeoutConfig": {
"inProgressTimeoutInMinutes": long
},
"documentParameters": {
397
AWS IoT Developer Guide
Job Management and Control API
"string": "string"
}
}
cli-input-json fields:
TargetArn string
length max:32768
pattern: [^\\p{C}]+
398
AWS IoT Developer Guide
Job Management and Control API
399
AWS IoT Developer Guide
Job Management and Control API
400
AWS IoT Developer Guide
Job Management and Control API
value: ParameterValue
ParameterKey string
pattern: [a-zA-Z0-9:_-]+
ParameterValue string
pattern: [^\\p{C}]+
Output:
{
"jobArn": "string",
"jobId": "string",
"description": "string"
}
pattern: [a-zA-Z0-9_-]+
length max:2028
pattern: [^\\p{C}]+
MQTT (4)
Not available.
DeleteJob
DeleteJob command
Deleting a job can take time, depending on the number of job executions created for the
job and various other factors. While the job is being deleted, the status of the job is shown
401
AWS IoT Developer Guide
Job Management and Control API
Request syntax:
DELETE /jobs/jobId?force=force
Errors:
402
AWS IoT Developer Guide
Job Management and Control API
InvalidRequestException
The contents of the request were invalid. For example, this code is returned when an
UpdateJobExecution request contains invalid status details. The message contains details about
the error.
An update attempted to change the job or job execution to a state that is invalid because of
its current state (for example, an attempt to change a request in state SUCCEEDED to state
IN_PROGRESS). In this case, the body of the error message also contains the executionState
field.
CLI (5)
Synopsis:
cli-input-json format:
{
"jobId": "string",
"force": boolean
}
cli-input-json fields:
pattern: [a-zA-Z0-9_-]+
403
AWS IoT Developer Guide
Job Management and Control API
Output:
None
MQTT (5)
Not available.
DeleteJobExecution
DeleteJobExecution command
Request syntax:
DELETE /things/thingName/jobs/jobId/executionNumber/executionNumber?force=force
404
AWS IoT Developer Guide
Job Management and Control API
Errors:
InvalidRequestException
The contents of the request were invalid. For example, this code is returned when an
UpdateJobExecution request contains invalid status details. The message contains details about
the error.
An update attempted to change the job execution to a state that is invalid because of
the job execution's current state (for example, an attempt to change a request in state
SUCCEEDED to state IN_PROGRESS). In this case, the body of the error message also contains
the executionState field.
405
AWS IoT Developer Guide
Job Management and Control API
CLI (6)
Synopsis:
cli-input-json format:
{
"jobId": "string",
"thingName": "string",
"executionNumber": long,
"force": boolean
}
cli-input-json fields:
pattern: [a-zA-Z0-9_-]+
406
AWS IoT Developer Guide
Job Management and Control API
Output:
None
MQTT (6)
Not available.
DescribeJob
DescribeJob command
Request:
GET /jobs/jobId
jobId
The unique identifier you assigned to this job when it was created.
Response:
{
"documentSource": "string",
"job": Job
}
407
AWS IoT Developer Guide
Job Management and Control API
documentSource
CLI (7)
Synopsis:
cli-input-json format:
{
"jobId": "string"
}
cli-input-json fields:
Output:
{
"documentSource": "string",
"job": {
"jobArn": "string",
"jobId": "string",
"targetSelection": "string",
"status": "string",
"forceCanceled": boolean,
"comment": "string",
"targets": [
"string"
],
"description": "string",
"presignedUrlConfig": {
"roleArn": "string",
"expiresInSec": long
},
"jobExecutionsRolloutConfig": {
"exponentialRate": {
"baseRatePerMinute": integer,
"incrementFactor": integer,
"rateIncreaseCriteria": {
"numberOfNotifiedThings": integer, // Set one or the other
"numberOfSucceededThings": integer // of these two values.
},
"maximumPerMinute": integer
408
AWS IoT Developer Guide
Job Management and Control API
}
},
"abortConfig": {
"criteriaList": [
{
"action": "string",
"failureType": "string",
"minNumberOfExecutedThings": integer,
"thresholdPercentage": integer
}
]
},
"createdAt": "timestamp",
"lastUpdatedAt": "timestamp",
"completedAt": "timestamp",
"jobProcessDetails": {
"processingTargets": [
"string"
],
"numberOfCanceledThings": "integer",
"numberOfSucceededThings": "integer",
"numberOfFailedThings": "integer",
"numberOfRejectedThings": "integer",
"numberOfQueuedThings": "integer",
"numberOfInProgressThings": "integer",
"numberOfRemovedThings": "integer",
"numberOfTimedOutThings": "integer"
},
"documentParameters": {
"string": "string"
},
"timeoutConfig": {
"inProgressTimeoutInMinutes": number
}
}
}
409
AWS IoT Developer Guide
Job Management and Control API
TargetArn string
pattern: [^\\p{C}]+
410
AWS IoT Developer Guide
Job Management and Control API
411
AWS IoT Developer Guide
Job Management and Control API
ProcessingTargetName string
412
AWS IoT Developer Guide
Job Management and Control API
value: ParameterValue
ParameterKey string
pattern: [a-zA-Z0-9:_-]+
ParameterValue string
pattern: [^\\p{C}]+
413
AWS IoT Developer Guide
Job Management and Control API
MQTT (7)
Not available.
DescribeJobExecution
DescribeJobExecution command
Gets details of a job execution. The job's execution status must be SUCCEEDED or FAILED.
HTTPS (8)
Request:
GET /things/thingName/jobs/jobId?executionNumber=executionNumber
jobId
The unique identifier you assigned to this job when it was created.
thingName
The thing name associated with the device the job execution is running on.
executionNumber
Response:
{
"execution": { JobExecution }
}
execution
414
AWS IoT Developer Guide
Job Management and Control API
CLI (8)
Synopsis:
cli-input-json format:
{
"jobId": "string",
"thingName": "string",
"executionNumber": long
}
cli-input-json fields:
Output:
{
"execution": {
"approximateSecondsBeforeTimedOut": "number"
"jobId": "string",
"status": "string",
"forceCanceled": boolean,
"statusDetails": {
"detailsMap": {
"string": "string"
}
},
"thingArn": "string",
"queuedAt": "timestamp",
"startedAt": "timestamp",
"lastUpdatedAt": "timestamp",
"executionNumber": long,
415
AWS IoT Developer Guide
Job Management and Control API
"versionNumber": long
}
}
approximateSecondsBeforeTimedOut
long The estimated number of
seconds that remain before the
job execution status is changed
to TIMED_OUT. The timeout
interval can be anywhere
between 1 minute and 7 days
(1 to 10080 minutes). The
actual job execution timeout
can occur up to 60 seconds
later than the estimated
duration. This value is not
included if the job execution
has reached a terminal status.
key: DetailsKey
value: DetailsValue
DetailsKey string
pattern: [a-zA-Z0-9:_-]+
DetailsValue string
416
AWS IoT Developer Guide
Job Management and Control API
pattern: [^\\p{C}]*+
MQTT (8)
Not available.
GetJobDocument
GetJobDocument command
Request:
GET /jobs/jobId/job-document
jobId
The unique identifier you assigned to this job when it was created.
417
AWS IoT Developer Guide
Job Management and Control API
Response:
{
"document": "string"
}
document
CLI (9)
Synopsis:
cli-input-json format:
{
"jobId": "string"
}
cli-input-json fields:
Output:
{
"document": "string"
}
length max:32768
MQTT (9)
Not available.
418
AWS IoT Developer Guide
Job Management and Control API
ListJobExecutionsForJob
ListExecutionsForJob command
Request:
GET /jobs/jobId/things?status=status&maxResults=maxResults&nextToken=nextToken
jobId
The unique identifier you assigned to this job when it was created.
status
Optional. A filter that lets you search for jobs that have the specified status: QUEUED,
IN_PROGRESS, SUCCEEDED, FAILED, TIMED_OUT, REJECTED, REMOVED, or CANCELED.
maxResults
Response:
{
"executionSummaries": [ JobExecutionSummary ... ]
}
executionSummaries
A list of JobExecutionSummary (p. 384) objects associated with the specified job ID.
CLI (10)
Synopsis:
cli-input-json format:
{
"jobId": "string",
"status": "string",
"maxResults": "integer",
"nextToken": "string"
}
419
AWS IoT Developer Guide
Job Management and Control API
cli-input-json fields:
enum: QUEUED |
IN_PROGRESS | SUCCEEDED
| FAILED | TIMED_OUT |
REJECTED | REMOVED |
CANCELED
Output:
{
"executionSummaries": [
{
"thingArn": "string",
"jobExecutionSummary": {
"status": "string",
"queuedAt": "timestamp",
"startedAt": "timestamp",
"lastUpdatedAt": "timestamp",
"executionNumber": long
}
}
],
"nextToken": "string"
}
JobExecutionSummaryForJob JobExecutionSummaryForJob
420
AWS IoT Developer Guide
Job Management and Control API
enum: QUEUED |
IN_PROGRESS | SUCCEEDED
| FAILED | TIMED_OUT |
REJECTED | REMOVED |
CANCELED
MQTT (10)
Not available.
ListJobExecutionsForThing
ListJobExecutionsForThing command
Request:
GET /things/thingName/jobs?status=status&maxResults=maxResults&nextToken=nextToken
thingName
421
AWS IoT Developer Guide
Job Management and Control API
status
An optional filter that lets you search for jobs that have the specified status: QUEUED,
IN_PROGRESS, SUCCEEDED, FAILED, TIMED_OUT, REJECTED, REMOVED, or CANCELED.
maxResults
The token for the next set of results, or null if there are no additional results.
Response:
{
"executionSummaries": [ JobExecutionSummary ... ]
}
executionSummaries
A list of the JobExecutionSummary (p. 384) objects for the job executions associated with the
specified thing.
CLI (11)
Synopsis:
cli-input-json format:
{
"thingName": "string",
"status": "string",
"maxResults": "integer",
"nextToken": "string"
}
cli-input-json fields:
pattern: [a-zA-Z0-9:_-]+
422
AWS IoT Developer Guide
Job Management and Control API
Output:
{
"executionSummaries": [
{
"jobId": "string",
"jobExecutionSummary": {
"status": "string",
"queuedAt": "timestamp",
"startedAt": "timestamp",
"lastUpdatedAt": "timestamp",
"executionNumber": long
}
}
],
"nextToken": "string"
}
JobExecutionSummaryForThing JobExecutionSummaryForThing
enum: QUEUED |
IN_PROGRESS | SUCCEEDED
| FAILED | TIMED_OUT|
423
AWS IoT Developer Guide
Job Management and Control API
MQTT (11)
Not available.
ListJobs
ListJobs command
Request:
GET /jobs?
status=status&targetSelection=targetSelection&thingGroupName=thingGroupName&thingGroupId=thingGroup
status
Optional. A filter that lets you search for jobs that have the specified status: IN_PROGRESS,
CANCELED, or SUCCEEDED.
targetSelection
Optional. A filter that lets you search for jobs that have the specified targetSelection value:
CONTINUOUS or SNAPSHOT.
thingGroupName
Optional. A filter that lets you search for jobs that have the specified thing group name as a
target.
424
AWS IoT Developer Guide
Job Management and Control API
thingGroupId
Optional. A filter that lets you search for jobs that have the specified thing group ID as a target.
maxResults
Response:
{
"jobs": [ JobSummary ... ],
}
jobs
A list of JobSummary (p. 382) objects, one for each job in your AWS account that matches the
specified filtering criteria.
CLI (12)
Synopsis:
cli-input-json format:
{
"status": "string",
"targetSelection": "string",
"maxResults": "integer",
"nextToken": "string",
"thingGroupName": "string",
"thingGroupId": "string"
}
cli-input-json fields:
Name Type Description
425
AWS IoT Developer Guide
Job Management and Control API
Output:
{
"jobs": [
{
"jobArn": "string",
"jobId": "string",
"thingGroupId": "string",
"targetSelection": "string",
"status": "string",
"createdAt": "timestamp",
"lastUpdatedAt": "timestamp",
"completedAt": "timestamp"
}
],
"nextToken": "string"
}
member: JobSummary
426
AWS IoT Developer Guide
Job Management and Control API
JobSummary JobSummary
pattern: [a-zA-Z0-9-]+
enum: IN_PROGRESS |
CANCELED | SUCCEEDED
MQTT (12)
Not available.
427
AWS IoT Developer Guide
Job Management and Control API
UpdateJob
UpdateJob command
Updates supported fields of the specified job. Updated values for timeoutConfig take effect for
only newly in-progress executions. Currently in-progress executions continue to execute with the old
timeout configuration.
HTTPS (13)
Request:
PATCH /jobs/jobId
{
"description": "string",
"presignedUrlConfig": {
"expiresInSec": number,
"roleArn": "string"
},
"jobExecutionsRolloutConfig": {
"exponentialRate": {
"baseRatePerMinute": number,
"incrementFactor": number,
"rateIncreaseCriteria": {
"numberOfNotifiedThings": number,
"numberOfSucceededThings": number
},
"maximumPerMinute": number
},
"abortConfig": {
"criteriaList": [
{
"action": "string",
"failureType": "string",
"minNumberOfExecutedThings": number,
"thresholdPercentage": number
}
]
},
"timeoutConfig": {
"inProgressTimeoutInMinutes": number
}
}
jobId
A job identifier that must be unique for your AWS account. We recommend using a UUID.
Alphanumeric characters, "-", and "_" can be used here.
description
The ARN of the IAM role that contains permissions to access the Amazon S3 bucket. This
is the bucket that contains the data that devices download with the presigned Amazon
S3 URLs. This role must also grant AWS IoT permission to assume the role. For more
information, see Create Jobs (p. 358).
428
AWS IoT Developer Guide
Job Management and Control API
expiresInSec
How long (in seconds) presigned URLs are valid. Valid values are 60 - 3600. The default
value is 3600 seconds. Presigned URLs are generated when the AWS IoT Jobs service
receives an MQTT request for the job document.
jobExecutionRolloutConfig
The maximum number of things on which the job is sent for execution, per minute. Valid
values are 1 to 1000. If not specified, the default is 1000. The actual number of things that
receive the job might be less during any particular minute interval (due to system latency),
but are not more than the specified value.
exponentialRate
The minimum number of things that are notified of a pending job, per minute at the
start of job rollout. This parameter allows you to define the initial rate of rollout.
incrementFactor
The criteria to initiate the increase in rate of rollout for a job. Set values for either the
numberOfNotifiedThings or numberOfSucceededThings, but not both.
numberOfNotifiedThings
The threshold for number of notified things that initiate the increase in rate of
rollout.
numberOfSucceededThings
The threshold for number of succeeded things that initiate the increase in rate of
rollout.
abortConfig
The type of job execution failure to define a rule to initiate a job abort.
minNumberOfExecutedThings
The threshold as a percentage of the total number of executed things that initiate a job
abort.
429
AWS IoT Developer Guide
Job Management and Control API
timeoutConfig
Optional. Specifies the amount of time each device has to finish its execution of the job. The
timer is started when the job execution status is set to IN_PROGRESS. If the job execution status
is not set to another terminal state before the time expires, it is set to TIMED_OUT.
inProgressTimeoutInMinutes
Specifies the amount of time, in minutes, this device has to finish execution of this
job. A timer is started, or restarted, whenever this job's execution status is specified as
IN_PROGRESS with this field populated. If the job execution status is not set to a terminal
state before the timer expires, or before another job execution status update is sent with
this field populated, the status is set to TIMED_OUT.
Response:
HTTP/1.1 200
If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body.
CLI (13)
Synopsis:
cli-input-json format:
{
"description": "string",
"presignedUrlConfig": {
"expiresInSec": number,
"roleArn": "string"
},
"jobExecutionsRolloutConfig": {
"exponentialRate": {
"baseRatePerMinute": number,
"incrementFactor": number,
"rateIncreaseCriteria": {
"numberOfNotifiedThings": number,
"numberOfSucceededThings": number
}
},
"maximumPerMinute": number
},
"abortConfig": {
"criteriaList": [
{
"action": "string",
"failureType": "string",
"minNumberOfExecutedThings": number,
"thresholdPercentage": number
}
]
},
430
AWS IoT Developer Guide
Job Management and Control API
"timeoutConfig": {
"inProgressTimeoutInMinutes": number
}
}
cli-input-json fields:
pattern: [^\\p{C}]+
431
AWS IoT Developer Guide
Job Management and Control API
432
AWS IoT Developer Guide
Job Management and Control API
value: ParameterValue
ParameterKey string
pattern: [a-zA-Z0-9:_-]+
ParameterValue string
pattern: [^\\p{C}]+
Output:
HTTP/1.1 200
If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body.
433
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
MQTT (13)
Not available.
JobExecution
JobExecution data type
{
"jobId" : "string",
"thingName" : "string",
"jobDocument" : "string",
"status": "QUEUED|IN_PROGRESS|FAILED|SUCCEEDED|CANCELED|TIMED_OUT|REJECTED|
REMOVED",
"statusDetails": {
"string": "string"
},
"queuedAt" : "timestamp",
"startedAt" : "timestamp",
"lastUpdatedAt" : "timestamp",
"versionNumber" : "number",
"executionNumber": long
}
description (7)
jobId
The unique identifier you assigned to this job when it was created.
thingName
The status of the job execution. Can be one of: QUEUED, IN_PROGRESS, FAILED, SUCCEEDED,
CANCELED, TIMED_OUT, REJECTED, or REMOVED.
statusDetails
A collection of name-value pairs that describe the status of the job execution.
queuedAt
The time, in seconds since the epoch, when the job execution was enqueued.
434
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
startedAt
The time, in seconds since the epoch, when the job execution was started.
lastUpdatedAt
The time, in seconds since the epoch, when the job execution was last updated.
versionNumber
The version of the job execution. Job execution versions are incremented each time they are
updated by a device.
executionNumber
A number that identifies a job execution on a device. It can be used later in commands that
return or update job execution information.
JobExecutionState
JobExecutionState data type
{
"status": "QUEUED|IN_PROGRESS|FAILED|SUCCEEDED|CANCELED|TIMED_OUT|REJECTED|
REMOVED",
"statusDetails": {
"string": "string"
...
}
"versionNumber": "number"
}
description (8)
status
The status of the job execution. Can be one of: QUEUED, IN_PROGRESS, FAILED, SUCCEEDED,
CANCELED, TIMED_OUT, REJECTED, or REMOVED.
statusDetails
A collection of name-value pairs that describe the status of the job execution.
versionNumber
The version of the job execution. Job execution versions are incremented each time they are
updated by a device.
JobExecutionSummary
JobExecutionSummary data type
{
"jobId": "string",
435
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
"queuedAt": timestamp,
"startedAt": timestamp,
"lastUpdatedAt": timestamp,
"versionNumber": "number",
"executionNumber": long
}
description (9)
jobId
The unique identifier you assigned to this job when it was created.
queuedAt
The time, in seconds since the epoch, when the job execution was enqueued.
startedAt
The time, in seconds since the epoch, when the job execution started.
lastUpdatedAt
The time, in seconds since the epoch, when the job execution was last updated.
versionNumber
The version of the job execution. Job execution versions are incremented each time the AWS IoT
Jobs service receives an update from a device.
executionNumber
ErrorResponse
ErrorResponse data type
Contains information about an error that occurred during an AWS IoT Jobs service operation.
syntax (10)
{
"code": "ErrorCode",
"message": "string",
"clientToken": "string",
"timestamp": timestamp,
"executionState": JobExecutionState
}
description (10)
code
The request was sent to a topic in the AWS IoT Jobs namespace that does not map to any
API.
InvalidJson
The contents of the request could not be interpreted as valid UTF-8-encoded JSON.
436
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
InvalidRequest
The contents of the request were invalid. For example, this code is returned when an
UpdateJobExecution request contains invalid status details. The message contains details
about the error.
InvalidStateTransition
An update attempted to change the job execution to a state that is invalid because of
the job execution's current state (for example, an attempt to change a request in state
SUCCEEDED to state IN_PROGRESS). In this case, the body of the error message also
contains the executionState field.
ResourceNotFound
The expected version specified in the request does not match the version of the job
execution in the AWS IoT Jobs service. In this case, the body of the error message also
contains the executionState field.
InternalError
Occurs when a command to describe a job is performed on a job that is in a terminal state.
message
A JobExecutionState (p. 435) object. This field is included only when the code field has
the value InvalidStateTransition or VersionMismatch. This makes it unnecessary in
these cases to perform a separate DescribeJobExecution request to obtain the current job
execution status data.
Device Commands
The following commands are available over the MQTT and HTTPS protocols.
GetPendingJobExecutions
GetPendingJobExecutions command
Gets the list of all jobs for a thing that are not in a terminal state.
437
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
MQTT (12)
Request payload:
{ "clientToken": "string" }
clientToken
Optional. A client token used to correlate requests and responses. Enter an arbitrary value here
and it is reflected in the response.
• $aws/things/thingName/jobs/get/accepted and
• $aws/things/thingName/jobs/get/rejected or
• $aws/things/thingName/jobs/get/# for both.
Response payload:
{
"inProgressJobs" : [ JobExecutionSummary ... ],
"queuedJobs" : [ JobExecutionSummary ... ],
"timestamp" : 1489096425069,
"clientToken" : "client-001"
}
inProgressJobs
The time, in seconds since the epoch, when the message was sent.
HTTPS (12)
Request:
GET /things/thingName/jobs
thingName
Response:
438
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
{
"inProgressJobs" : [ JobExecutionSummary ... ],
"queuedJobs" : [ JobExecutionSummary ... ]
}
inProgressJobs
CLI (12)
Synopsis:
cli-input-json format:
{
"thingName": "string"
}
cli-input-json fields:
pattern: [a-zA-Z0-9:_-]+
Output:
{
"inProgressJobs": [
{
"jobId": "string",
"queuedAt": long,
"startedAt": long,
"lastUpdatedAt": long,
"versionNumber": long,
"executionNumber": long
}
],
"queuedJobs": [
{
"jobId": "string",
"queuedAt": long,
"startedAt": long,
"lastUpdatedAt": long,
"versionNumber": long,
439
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
"executionNumber": long
}
]
}
JobExecutionSummary JobExecutionSummary
JobExecutionSummary JobExecutionSummary
440
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
StartNextPendingJobExecution
StartNextPendingJobExecution command
Gets and starts the next pending job execution for a thing (status IN_PROGRESS or QUEUED).
MQTT (13)
Request payload:
{
"statusDetails": {
"string": "job-execution-state"
...
},
"stepTimeoutInMinutes": long,
"clientToken": "string"
}
441
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
statusDetails
A collection of name-value pairs that describe the status of the job execution. If not specified,
the statusDetails are unchanged.
stepTimeOutInMinutes
Specifies the amount of time this device has to finish execution of this job. If the job execution
status is not set to a terminal state before this timer expires, or before the timer is reset (by
calling UpdateJobExecution, setting the status to IN_PROGRESS and specifying a new
timeout value in field stepTimeoutInMinutes) the job execution status is set to TIMED_OUT.
Setting this timeout has no effect on that job execution timeout that might have been specified
when the job was created (CreateJob using the timeoutConfig field).
clientToken
A client token used to correlate requests and responses. Enter an arbitrary value here and it is
reflected in the response.
• $aws/things/thingName/jobs/start-next/accepted and
• $aws/things/thingName/jobs/start-next/rejected or
• $aws/things/thingName/jobs/start-next/# for both.
Response payload:
{
"execution" : JobExecutionData,
"timestamp" : timestamp,
"clientToken" : "string"
}
execution
{
"execution" : {
"jobId" : "022",
"thingName" : "MyThing",
"jobDocument" : "< contents of job document >",
"status" : "IN_PROGRESS",
"queuedAt" : 1489096123309,
"lastUpdatedAt" : 1489096123309,
"versionNumber" : 1,
"executionNumber" : 1234567890
},
"clientToken" : "client-1",
"timestamp" : 1489088524284,
}
timestamp
The time, in milliseconds since the epoch, when the message was sent to the device.
clientToken
442
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
HTTPS (13)
Request:
PUT /things/thingName/jobs/$next
{
"statusDetails": {
"string": "string"
...
},
"stepTimeoutInMinutes": long
}
thingName
A collection of name-value pairs that describe the status of the job execution. If not specified,
the statusDetails are unchanged.
stepTimeOutInMinutes
Specifies the amount of time this device has to finish execution of this job. If the job execution
status is not set to a terminal state before this timer expires, or before the timer is reset (by
calling UpdateJobExecution, setting the status to IN_PROGRESS and specifying a new
timeout value in field stepTimeoutInMinutes) the job execution status is set to TIMED_OUT.
Setting this timeout has no effect on that job execution timeout that might have been specified
when the job was created (CreateJob using the timeoutConfig field).
Response:
{
"execution" : JobExecution
}
execution
{
"execution" : {
"jobId" : "022",
"thingName" : "MyThing",
"jobDocument" : "< contents of job document >",
"status" : "IN_PROGRESS",
"queuedAt" : 1489096123309,
"lastUpdatedAt" : 1489096123309,
"versionNumber" : 1,
"executionNumber" : 1234567890
},
"clientToken" : "client-1",
"timestamp" : 1489088524284,
}
CLI (13)
Synopsis:
443
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
cli-input-json format:
{
"thingName": "string",
"statusDetails": {
"string": "string"
},
"stepTimeoutInMinutes": long
}
cli-input-json fields:
Name Type Description
pattern: [a-zA-Z0-9:_-]+
DetailsKey string
pattern: [a-zA-Z0-9:_-]+
444
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
DetailsValue string
pattern: [^\\p{C}]*+
Output:
{
"execution": {
"jobId": "string",
"thingName": "string",
"status": "string",
"statusDetails": {
"string": "string"
},
"queuedAt": long,
"startedAt": long,
"lastUpdatedAt": long,
"versionNumber": long,
"executionNumber": long,
"jobDocument": "string"
}
}
pattern: [a-zA-Z0-9:_-]+
DetailsKey string
445
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
pattern: [a-zA-Z0-9:_-]+
DetailsValue string
pattern: [^\\p{C}]*+
DescribeJobExecution
DescribeJobExecution command
You can set the jobId to $next to return the next pending job execution for a thing (status
IN_PROGRESS or QUEUED).
MQTT (14)
Request payload:
{
"executionNumber": long,
"includeJobDocument": boolean,
"clientToken": "string"
}
446
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
thingName
Or use $next to return the next pending job execution for a thing (status IN_PROGRESS or
QUEUED). In this case, any job executions with status IN_PROGRESS are returned first. Job
executions are returned in the order in which they were created.
executionNumber
Optional. A number that identifies a job execution on a device. If not specified, the latest job
execution is returned.
includeJobDocument
Optional. Unless set to false, the response contains the job document. The default is true.
clientToken
A client token used to correlate requests and responses. Enter an arbitrary value here and it is
reflected in the response.
• $aws/things/thingName/jobs/jobId/get/accepted and
• $aws/things/thingName/jobs/jobId/get/rejected or
• $aws/things/thingName/jobs/jobId/get/# for both.
Response payload:
{
"execution" : JobExecutionData,
"timestamp": "timestamp",
"clientToken": "string"
}
execution
The time, in seconds since the epoch, when the message was sent.
clientToken
HTTPS (14)
Request:
GET /things/thingName/jobs/jobId?
executionNumber=executionNumber&includeJobDocument=includeJobDocument
447
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
thingName
Or use $next to return the next pending job execution for a thing (status IN_PROGRESS or
QUEUED). In this case, any job executions with status IN_PROGRESS are returned first. Job
executions are returned in the order in which they were created.
includeJobDocument
Optional. Unless set to false, the response contains the job document. The default is true.
executionNumber
Optional. A number that identifies a job execution on a device. If not specified, the latest job
execution is returned.
Response:
{
"execution" : JobExecution,
}
execution
CLI (14)
Synopsis:
cli-input-json format:
{
"jobId": "string",
"thingName": "string",
"includeJobDocument": boolean,
"executionNumber": long
}
cli-input-json fields:
448
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
Output:
{
"execution": {
"jobId": "string",
"thingName": "string",
"status": "string",
"statusDetails": {
"string": "string"
},
"queuedAt": long,
"startedAt": long,
"lastUpdatedAt": long,
"versionNumber": long,
"executionNumber": long,
"jobDocument": "string"
}
}
449
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
pattern: [a-zA-Z0-9:_-]+
DetailsKey string
pattern: [a-zA-Z0-9:_-]+
DetailsValue string
pattern: [^\\p{C}]*+
450
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
UpdateJobExecution
UpdateJobExecution command
Updates the status of a job execution. You can optionally create a step timer by setting a value for
the stepTimeoutInMinutes property. If you don't update the value of this property by running
UpdateJobExecution again, the job execution times out when the step timer expires.
MQTT (15)
Request payload:
{
"status": "job-execution-state",
"statusDetails": {
"string": "string"
...
},
"expectedVersion": "number",
"executionNumber": long,
"includeJobExecutionState": boolean,
"includeJobDocument": boolean,
"stepTimeoutInMinutes": long,
"clientToken": "string"
}
status
The new status for the job execution (IN_PROGRESS, FAILED, SUCCEEDED, or REJECTED). This
must be specified on every update.
statusDetails
A collection of name-value pairs that describe the status of the job execution. If not specified,
the statusDetails are unchanged.
expectedVersion
The expected current version of the job execution. Each time you update the job execution,
its version is incremented. If the version of the job execution stored in the AWS IoT Jobs
service does not match, the update is rejected with a VersionMismatch error, and an
ErrorResponse (p. 436) that contains the current job execution status data is returned. (This
makes it unnecessary to perform a separate DescribeJobExecution request to obtain the job
execution status data.)
executionNumber
Optional. A number that identifies a job execution on a device. If not specified, the latest job
execution is used.
includeJobExecutionState
Optional. When included and set to true, the response contains the JobExecutionState
field. The default is false.
includeJobDocument
Optional. When included and set to true, the response contains the JobDocument. The default
is false.
stepTimeoutInMinutes
Specifies the amount of time this device has to finish execution of this job. If the job execution
status is not set to a terminal state before this timer expires, or before the timer is reset (by
451
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
again calling UpdateJobExecution, setting the status to IN_PROGRESS and specifying a new
timeout value in this field) the job execution status is set to TIMED_OUT. Setting or resetting this
timeout has no effect on the job execution timeout that might have been specified when the job
was created (by using CreateJob with the timeoutConfig).
clientToken
A client token used to correlate requests and responses. Enter an arbitrary value here and it is
reflected in the response.
• $aws/things/thingName/jobs/jobId/update/accepted and
• $aws/things/thingName/jobs/jobId/update/rejected or
• $aws/things/thingName/jobs/jobId/update/# for both.
Response payload:
{
"executionState": JobExecutionState,
"jobDocument": "string",
"timestamp": timestamp,
"clientToken": "string"
}
executionState
The time, in seconds since the epoch, when the message was sent.
clientToken
HTTPS (15)
Request:
POST /things/thingName/jobs/jobId
{
"status": "job-execution-state",
"statusDetails": {
"string": "string"
...
},
"expectedVersion": "number",
"includeJobExecutionState": boolean,
"includeJobDocument": boolean,
"stepTimeoutInMinutes": long,
"executionNumber": long
}
452
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
thingName
The new status for the job execution (IN_PROGRESS, FAILED, SUCCEEDED, or REJECTED). This
must be specified on every update.
statusDetails
Optional. A collection of name-value pairs that describe the status of the job execution. If not
specified, the statusDetails are unchanged.
expectedVersion
Optional. The expected current version of the job execution. Each time you update the job
execution, its version is incremented. If the version of the job execution stored in the AWS IoT
Jobs service does not match, the update is rejected with a VersionMismatch error, and an
ErrorResponse (p. 436) that contains the current job execution status data is returned. (This
makes it unnecessary to perform a separate DescribeJobExecution request to obtain the job
execution status data.)
includeJobExecutionState
Optional. When included and set to true, the response contains the JobExecutionState data.
The default is false.
includeJobDocument
Optional. When set to true, the response contains the job document. The default is false.
stepTimeoutInMinutes
Specifies the amount of time this device has to finish execution of this job. If the job execution
status is not set to a terminal state before this timer expires, or before the timer is reset (by
again calling UpdateJobExecution, setting the status to IN_PROGRESS and specifying a new
timeout value in this field) the job execution status is set to TIMED_OUT. Setting or resetting this
timeout has no effect on the job execution timeout that might have been specified when the job
was created (by using CreateJob with the timeoutConfig).
executionNumber
Response:
{
"executionState": JobExecutionState,
"jobDocument": "string"
}
executionState
453
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
CLI (15)
Synopsis:
cli-input-json format:
{
"jobId": "string",
"thingName": "string",
"status": "string",
"statusDetails": {
"string": "string"
},
"stepTimeoutInMinutes": number,
"expectedVersion": long,
"includeJobExecutionState": boolean,
"includeJobDocument": boolean,
"executionNumber": long
}
cli-input-json fields:
pattern: [a-zA-Z0-9_-]+
pattern: [a-zA-Z0-9:_-]+
454
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
DetailsKey string
pattern: [a-zA-Z0-9:_-]+
DetailsValue string
pattern: [^\\p{C}]*+
stepTimeoutInMinutes
long
455
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
Output:
{
"executionState": {
"status": "string",
"statusDetails": {
"string": "string"
},
"versionNumber": long
},
"jobDocument": "string"
}
DetailsKey string
pattern: [a-zA-Z0-9:_-]+
DetailsValue string
pattern: [^\\p{C}]*+
456
AWS IoT Developer Guide
Jobs Device MQTT and HTTPS APIs
JobExecutionsChanged
JobExecutionsChanged message
Sent whenever a job execution is added to or removed from the list of pending job executions for a
thing.
MQTT (16)
Topic: $aws/things/thingName/jobs/notify
Message payload:
{
"jobs" : {
"JobExecutionState": [ JobExecutionSummary (p. 384) ... ]
},
"timestamp": timestamp,
}
HTTPS (16)
Not available.
CLI (16)
Not available.
NextJobExecutionChanged
NextJobExecutionChanged message
Sent whenever there is a change to which job execution is next on the list of pending job executions
for a thing, as defined for DescribeJobExecution (p. 446) with jobId $next. This message is not
sent when the next job's execution details change, only when the next job that would be returned
by DescribeJobExecution with jobId $next has changed. Consider job executions J1 and J2
with state QUEUED. J1 is next on the list of pending job executions. If the state of J2 is changed to
IN_PROGRESS while the state of J1 remains unchanged, then this notification is sent and contains
details of J2.
MQTT (17)
Topic: $aws/things/thingName/jobs/notify-next
Message payload:
{
"execution" : JobExecution (p. 383),
457
AWS IoT Developer Guide
Job Rollout and Abort Configuration
"timestamp": timestamp,
}
HTTPS (17)
Not available.
CLI (17)
Not available.
{
...
"jobExecutionsRolloutConfig": {
"exponentialRate": {
"baseRatePerMinute": 50,
"incrementFactor": 2,
"rateIncreaseCriteria": {
"numberOfNotifiedThings": 1000, // Set one or the other
"numberOfSucceededThings": 1000 // of these two values.
},
"maximumPerMinute": 1000
...
}
The baseRatePerMinute parameter specifies the rate at which the jobs are executed until the
numberOfNotifiedThings or numberOfSucceededThings threshold has been met.
The incrementFactor parameter specifies the exponential factor by which the rollout rate increases
after the numberOfNotifiedThings or numberOfSucceededThings threshold has been met.
The maximumPerMinute parameter specifies the upper limit of the rate at which job executions
can occur. Valid values range from 1 to 1000. This parameter is required when you pass an
ExponentialRate object. In a variable rate rollout, this value establishes the upper limit of a job rollout
rate.
A job rollout with the configuration above would start at a rate of 50 job executions per minute. It would
continue at that rate until either 1000 things have received job execution notifications (if a value for
458
AWS IoT Developer Guide
Using Job Rollout Abort Configurations
numberOfNotifiedThings has been specified) or 1000 successful job executions have occurred (if a
value for numberOfSucceededThings has been specified).
The following table illustrates how the rollout would proceed over the first four increments.
{
...
"jobExecutionsRolloutConfig": {
"maximumPerMinute": 1000
...
}
The maximumPerMinute parameter specifies the upper limit of the rate at which job executions can
occur. Valid values range from 1 to 1000. This parameter is optional. If you don't specify a value, the
default value of 1000 is used.
"abortConfig": {
"criteriaList": [
{
"action": "CANCEL",
"failureType": "FAILED",
"minNumberOfExecutedThings": 100,
"thresholdPercentage": 20
},
{
"action": "CANCEL",
"failureType": "TIMED_OUT",
"minNumberOfExecutedThings": 200,
"thresholdPercentage": 50
}
]
}
The action parameter specifies the action to take when the abort criteria have been met. This
parameter is required, and CANCEL is the only valid value.
The failureType parameter specifies which failure types should trigger a job abort. Valid values are
FAILED, REJECTED, TIMED_OUT, and ALL.
459
AWS IoT Developer Guide
Job Limits
The minNumberOfExecutedThings parameter specifies the number of completed job executions that
must occur before the service checks to see if the job abort criteria have been met. In this example,
AWS IoT doesn't check to see if a job abort should occur until at least 100 devices have completed job
executions.
The thresholdPercentage parameter specifies the total number of executed things that initiate a
job abort. In this example, AWS IoT initiates a job abort and cancels the job rollout if at least 20% of all
completed executions have failed in any way after 100 executions have completed.
Note
Deletion of job executions affects the computation value of the total completed execution.
When a job aborts, the service creates an automated comment and reasonCode to differentiate
a user-driven cancellation from a job abort cancellation.
Job Limits
For job limit information, see AWS IoT Job Limits in the AWS General Reference.
460
AWS IoT Developer Guide
Provisioning Templates
Device Provisioning
AWS IoT device provisioning involves the creation and registration of the following entities:
• A certificate. You can provision a device with an existing certificate or have AWS IoT create and register
one for you.
• A policy attached to the certificate.
• A unique identifier for the thing (device).
• A set of attributes for the thing, including existing thing types and groups.
To provision a device, create a template that describes the resources required for your device. Devices
require a thing, a certificate, and one or more policies. A thing is an entry in the registry that contains
attributes that describe the device. Devices use certificates to authenticate with AWS IoT. Policies
determine which operations a device can perform in AWS IoT.
Templates contain variables that are replaced when the template is used to provision a device. A
dictionary (map) is used to provide values for the variables used in a template. You can use the same
template to provision multiple devices. You simply pass in different values for the template variables in
the dictionary.
This is a good option if you only need to provision devices one at a time.
• Just-in-time provisioning (JITP) with a template that registers and provisions a device when it first
connects to AWS IoT.
This is a good option if you need to register large numbers of devices, but you don't have information
about them that you can assemble into a bulk provisioning list.
• Bulk provisioning.
This option allows you to specify a list of single-thing provisioning template values that are stored in
a file in an S3 bucket. This approach works well if you have a large number of known devices whose
desired characteristics you can assemble into a list.
Just-in-time provisioning and bulk provisioning are better options if you need to provision large numbers
of devices. AWS IoT also provides a RegisterThing API that you can use to provision single devices
programmatically.
Provisioning Templates
A provisioning template is a JSON document that uses parameters to describe the resources your device
must use to interact with AWS IoT. A template contains two sections: Parameters and Resources.
Parameters Section
The Parameters section declares the parameters used in the Resources section. Each parameter
declares a name, a type, and an optional default value. The default value is used when the dictionary
461
AWS IoT Developer Guide
Resources Section
passed in with the template does not contain a value for the parameter. The Parameters section of a
template document looks like the following:
{
"Parameters" : {
"ThingName" : {
"Type" : "String"
},
"SerialNumber" : {
"Type" : "String"
},
"Location" : {
"Type" : "String",
"Default" : "WA"
},
"CSR" : {
"Type" : "String"
}
}
}
This template snippet declares four parameters: ThingName, SerialNumber, Location, and CSR. All of
these parameters are of type String. The Location parameter declares a default value of "WA".
Resources Section
The Resources section of the template declares the resources required for your device to communicate
with AWS IoT: a thing, a certificate, and one or more policies. Each resource specifies a logical name, a
type, and a set of properties.
The type specifies the kind of resource you are declaring. Valid types are:
• AWS::IoT::Thing
• AWS::IoT::Certificate
• AWS::IoT::Policy
The properties you specify depend on the type of resource you are declaring.
Thing Resources
Thing resources are declared using the following properties:
• ThingName: String.
• AttributePayload: Optional. A list of name/value pairs.
• ThingTypeName: Optional. String for an associated thing type for the thing.
• ThingGroups: Optional. A list of groups to which the thing belongs.
Certificate Resources
Certificates can be specified in one of the following ways:
462
AWS IoT Developer Guide
Resources Section
Note
When you declare a certificate in a template, use only one of these methods. For example, if you
use a CSR, you cannot also specify a certificate ID or a device certificate.
• CertificateSigningRequest: String.
• CertificateID: String.
• CertificatePem: String.
• CACertificatePem: String.
• Status: Optional. String that can be one of: ACTIVE, INACTIVE, PENDING_ACTIVATION. Defaults to
ACTIVE.
Examples:
{
"certificate" : {
"Type" : "AWS::IoT::Certificate",
"Properties" : {
"CertificateSigningRequest": {"Ref" : "CSR"},
"Status" : "ACTIVE"
}
}
}
{
"certificate" : {
"Type" : "AWS::IoT::Certificate",
"Properties" : {
"CertificateId": {"Ref" : "CertificateId"}
}
}
}
{
"certificate" : {
"Type" : "AWS::IoT::Certificate"
"Properties" : {
"CACertificatePem": {"Ref" : "CACertificatePem"},
"CertificatePem": {"Ref" : "CertificatePem"}
}
}
}
463
AWS IoT Developer Guide
Resources Section
Policy Resources
Policy resources are declared using one of the following properties:
• PolicyName: Optional. String. Defaults to a hash of the policy document. If you are using an existing
IoT policy, enter the name of the policy for the PolicyName property, and do not include the
PolicyDocument property.
• PolicyDocument: Optional. A JSON object specified as an escaped string. If PolicyDocument is not
provided, the policy must already be created.
Note
If a Policy section is present, PolicyName or PolicyDocument, but not both, must be
specified.
Override Settings
If a template specifies a resource that already exists, the OverrideSettings section allows you to
specify the action to take:
DO_NOTHING
Valid only for the ThingGroups and AttributePayload properties of a thing. Merge the existing
attributes or group memberships of the thing with those specified in the template.
When you declare a thing resource, you can specify OverrideSettings for the following properties:
• ATTRIBUTE_PAYLOAD
• THING_TYPE_NAME
• THING_GROUPS
When you declare a certificate resource, you can specify OverrideSettings for the Status property.
Resource Example
The following template snippet declares a thing, a certificate, and a policy:
{
"Resources" : {
"thing" : {
"Type" : "AWS::IoT::Thing",
"Properties" : {
464
AWS IoT Developer Guide
Resources Section
The thing properties include the thing name, a set of attributes, an optional thing type name, and an
optional list of thing groups to which the thing belongs.
Parameters are referenced by {"Ref": "<parameter-name>"}. When the template is evaluated, the
parameters are replaced with the parameter's value from the dictionary passed in with the template.
The properties include the CSR for the certificate, and setting the status to ACTIVE. The CSR text is
passed as a parameter in the dictionary passed with the template.
465
AWS IoT Developer Guide
Template Example
Template Example
The following JSON file is an example of a complete provisioning template that specifies the certificate
with a CSR:
(The PolicyDocument field value must be a JSON object specified as an escaped string.)
{
"Parameters" : {
"ThingName" : {
"Type" : "String"
},
"SerialNumber" : {
"Type" : "String"
},
"Location" : {
"Type" : "String",
"Default" : "WA"
},
"CSR" : {
"Type" : "String"
}
},
"Resources" : {
"thing" : {
"Type" : "AWS::IoT::Thing",
"Properties" : {
"ThingName" : {"Ref" : "ThingName"},
"AttributePayload" : { "version" : "v1", "serialNumber" : {"Ref" :
"SerialNumber"}},
"ThingTypeName" : "lightBulb-versionA",
"ThingGroups" : ["v1-lightbulbs", {"Ref" : "Location"}]
}
},
"certificate" : {
"Type" : "AWS::IoT::Certificate",
"Properties" : {
"CertificateSigningRequest": {"Ref" : "CSR"},
"Status" : "ACTIVE"
}
},
"policy" : {
"Type" : "AWS::IoT::Policy",
"Properties" : {
"PolicyDocument" : "{ \"Version\": \"2012-10-17\", \"Statement\":
[{ \"Effect\": \"Allow\", \"Action\":[\"iot:Publish\"], \"Resource\": [\"arn:aws:iot:us-
east-1:123456789012:topic/foo/bar\"] }] }"
}
}
}
}
The following JSON file is an example of a complete provisioning template that specifies an existing
certificate with a certificate ID:
{
"Parameters" : {
"ThingName" : {
"Type" : "String"
},
"SerialNumber" : {
"Type" : "String"
466
AWS IoT Developer Guide
Programmatic Provisioning
},
"Location" : {
"Type" : "String",
"Default" : "WA"
},
"CertificateId" : {
"Type" : "String"
}
},
"Resources" : {
"thing" : {
"Type" : "AWS::IoT::Thing",
"Properties" : {
"ThingName" : {"Ref" : "ThingName"},
"AttributePayload" : { "version" : "v1", "serialNumber" : {"Ref" :
"SerialNumber"}},
"ThingTypeName" : "lightBulb-versionA",
"ThingGroups" : ["v1-lightbulbs", {"Ref" : "Location"}]
}
},
"certificate" : {
"Type" : "AWS::IoT::Certificate",
"Properties" : {
"CertificateId": {"Ref" : "CertificateId"}
},
"OverrideSettings" : {
"Status" : "DO_NOTHING"
}
},
"policy" : {
"Type" : "AWS::IoT::Policy",
"Properties" : {
"PolicyDocument" : "{ \"Version\": \"2012-10-17\", \"Statement\":
[{ \"Effect\": \"Allow\", \"Action\":[\"iot:Publish\"], \"Resource\": [\"arn:aws:iot:us-
east-1:123456789012:topic/foo/bar\"] }] }"
}
}
}
}
Programmatic Provisioning
To provision a thing, use the RegisterThing API or the register-thing CLI command. The register-
thing CLI command takes the following arguments:
--template-body
A list of name/value pairs for the parameters used in the provisioning template, in JSON format (for
example, {"ThingName" : "MyProvisionedThing", "CSR" : "<csr-text>"}).
RegisterThing or register-thing returns the ARNs for the resources and the text of the certificate it
created:
467
AWS IoT Developer Guide
Just-in-Time Provisioning
"certificatePem": "<certificate-text>",
"resourceArns": {
"PolicyLogicalName": "arn:aws:iot:us-
west-2:123456789012:policy/2A6577675B7CD1823E271C7AAD8184F44630FFD7",
"certificate": "arn:aws:iot:us-west-2:123456789012:cert/
cd82bb924d4c6ccbb14986dcb4f40f30d892cc6b3ce7ad5008ed6542eea2b049",
"thing": "arn:aws:iot:us-west-2:123456789012:thing/MyProvisionedThing"
}
}
If a parameter is omitted from the dictionary, the default value is used. If no default value is specified,
the parameter is not replaced with a value.
Just-in-Time Provisioning
You can have your devices provisioned when they first attempt to connect to AWS IoT. Just-in-time
provisioning (JITP) settings are made on CA certificates. To provision the device, you must enable
automatic registration and associate a provisioning template with the CA certificate used to sign the
device certificate.
You can make these settings when you register a CA certificate with the RegisterCACertificate API or the
register-ca-certificate CLI command:
You can also use the UpdateCACertificate API or the update-ca-certificate CLI command to
update the settings for a CA certificate:
When a device attempts to connect to AWS IoT by using a certificate signed by a registered CA
certificate, AWS IoT loads the template from the CA certificate and calls RegisterThing using the
template. The JITP workflow first registers a certificate with a status value of PENDING_ACTIVATION.
When the device provisioning flow is complete, the status of the certificate is changed to ACTIVE.
AWS IoT defines the following parameters that you can declare and reference in provisioning templates:
• AWS::IoT::Certificate::Country
• AWS::IoT::Certificate::Organization
• AWS::IoT::Certificate::OrganizationalUnit
• AWS::IoT::Certificate::DistinguishedNameQualifier
• AWS::IoT::Certificate::StateName
• AWS::IoT::Certificate::CommonName
• AWS::IoT::Certificate::SerialNumber
• AWS::IoT::Certificate::Id
The values for these provisioning template parameters are limited to what JITP can extract from the
subject field of the certificate of the device being provisioned. The AWS::IoT::Certificate::Id
468
AWS IoT Developer Guide
Just-in-Time Provisioning
parameter refers to an internally generated ID, not an ID that is contained in the certificate. You can get
the value of this ID using the principal() function inside an AWS IoT rule.
The following JSON file is an example of a complete JITP template. The value of the templateBody
field must be a JSON object specified as an escaped string and can use only the values in the preceding
list. You can use a variety of tools to create the stringified JSON object, such as json.dumps (Python)
or JSON.stringify (Node). The value of the roleARN field must be the ARN of a role that has the
AWSIoTThingsRegistration attached to it. Also, your template can use an existing PolicyName instead of
the inline PolicyDocument in the example. (The first example adds line breaks for readability, but you can
copy and paste the template that appears directly below it.)
{
"templateBody" : "{
\r\n \"Parameters\" : {\r\n
\"AWS::IoT::Certificate::CommonName\": {\r\n \"Type\": \"String
\"\r\n },\r\n
\"AWS::IoT::Certificate::SerialNumber\": {\r\n \"Type\": \"String
\"\r\n },\r\n
\"AWS::IoT::Certificate::Country\": {\r\n \"Type\": \"String\"\r
\n },\r\n
\"AWS::IoT::Certificate::Id\": {\r\n \"Type\": \"String\"\r\n
}\r\n },\r\n
\"Resources\": {\r\n
\"thing\": {\r\n
\"Type\": \"AWS::IoT::Thing\",\r\n
\"Properties\": {\r\n
\"ThingName\": {\r\n \"Ref\":
\"AWS::IoT::Certificate::CommonName\"\r\n },\r\n
\"AttributePayload\": {\r\n
\"version\": \"v1\",\r\n
\"serialNumber\": {\r\n
\"Ref\": \"AWS::IoT::Certificate::SerialNumber\"\r
\n }\r\n },\r\n
\"ThingTypeName\": \"lightBulb-versionA\",\r\n
\"ThingGroups\": [\r\n
\"v1-lightbulbs\",\r\n {\r\n
\"Ref\": \"AWS::IoT::Certificate::Country\"\r\n }\r
\n ]\r\n },\r\n
\"OverrideSettings\": {\r\n
\"AttributePayload\": \"MERGE\",\r\n
\"ThingTypeName\": \"REPLACE\",\r\n
\"ThingGroups\": \"DO_NOTHING\"\r\n }\r\n },\r\n
\"certificate\": {\r\n
\"Type\": \"AWS::IoT::Certificate\",\r\n
\"Properties\": {\r\n
\"CertificateId\": {\r\n \"Ref\":
\"AWS::IoT::Certificate::Id\"\r\n },\r\n
\"Status\": \"ACTIVE\"\r\n },\r\n
\"OverrideSettings\": {\r\n
\"Status\": \"DO_NOTHING\"\r\n }\r\n },\r\n
\"policy\": {\r\n
\"Type\": \"AWS::IoT::Policy\",\r\n
\"Properties\": {\r\n
\"PolicyDocument\": \"{
\\\"Version\\\": \\\"2012-10-17\\\",
\\\"Statement\\\": [{
\\\"Effect\\\": \\\"Allow\\\",
\\\"Action\\\":[\\\"iot:Publish\\\"],
\\\"Resource\\\": [\\\"arn:aws:iot:us-
east-1:123456789012:topic\/sample\/topic\\\"] }] }\"\r\n }\r\n }\r\n
}\r\n}",
"roleArn" : "arn:aws:iam::123456789012:role/Provisioning-JITP"
469
AWS IoT Developer Guide
Just-in-Time Provisioning
{
"templateBody" : "{\r\n \"Parameters\" : {\r\n
\"AWS::IoT::Certificate::CommonName\": {\r\n \"Type\": \"String\"\r\n },
\r\n \"AWS::IoT::Certificate::SerialNumber\": {\r\n \"Type\": \"String
\"\r\n },\r\n \"AWS::IoT::Certificate::Country\": {\r\n \"Type\":
\"String\"\r\n },\r\n \"AWS::IoT::Certificate::Id\": {\r\n \"Type
\": \"String\"\r\n }\r\n },\r\n \"Resources\": {\r\n \"thing\": {\r\n
\"Type\": \"AWS::IoT::Thing\",\r\n \"Properties\": {\r\n
\"ThingName\": {\r\n \"Ref\": \"AWS::IoT::Certificate::CommonName
\"\r\n },\r\n \"AttributePayload\": {\r\n
\"version\": \"v1\",\r\n \"serialNumber\": {\r\n
\"Ref\": \"AWS::IoT::Certificate::SerialNumber\"\r\n }\r\n
},\r\n \"ThingTypeName\": \"lightBulb-versionA\",\r\n
\"ThingGroups\": [\r\n \"v1-lightbulbs\",\r\n
{\r\n \"Ref\": \"AWS::IoT::Certificate::Country\"\r\n
}\r\n ]\r\n },\r\n \"OverrideSettings\": {\r
\n \"AttributePayload\": \"MERGE\",\r\n \"ThingTypeName\":
\"REPLACE\",\r\n \"ThingGroups\": \"DO_NOTHING\"\r\n }\r\n
},\r\n \"certificate\": {\r\n \"Type\": \"AWS::IoT::Certificate\",\r\n
\"Properties\": {\r\n \"CertificateId\": {\r\n
\"Ref\": \"AWS::IoT::Certificate::Id\"\r\n },\r\n \"Status
\": \"ACTIVE\"\r\n },\r\n \"OverrideSettings\": {\r\n
\"Status\": \"DO_NOTHING\"\r\n }\r\n },\r\n \"policy\": {\r\n
\"Type\": \"AWS::IoT::Policy\",\r\n \"Properties\": {\r\n
\"PolicyDocument\": \"{ \\\"Version\\\": \\\"2012-10-17\\\", \\\"Statement\\\": [{ \
\\"Effect\\\": \\\"Allow\\\", \\\"Action\\\":[\\\"iot:Publish\\\"], \\\"Resource\\\": [\\
\"arn:aws:iot:us-east-1:123456789012:topic\/foo\/bar\\\"] }] }\"\r\n }\r\n
}\r\n }\r\n}",
"roleArn" : "arn:aws:iam::123456789012:role/JITPRole"
}
You should be able to see the certificate registration as a logged event (RegisterCACertificate) in
AWS CloudTrail . You can also use CloudTrail to troubleshoot issues with your JITP template.
470
AWS IoT Developer Guide
Bulk Provisioning
Bulk Provisioning
You can use the start-thing-registration-task command to provision things in bulk. This
command takes a provisioning template, an Amazon S3 bucket name, a key name, and a role ARN that
allows access to the file in the Amazon S3 bucket. The file in the Amazon S3 bucket contains the values
used to replace the parameters in the template. The file must be a newline-delimited JSON file. Each line
contains all of the parameter values for provisioning a single device. For example:
Note
Only one bulk provisioning operation task can run at a time (per account).
471
AWS IoT Developer Guide
Managing Thing Indexing
When you enable indexing, AWS IoT creates an index for your things or thing groups. After it's active,
you can run queries on your index, such as finding all devices that are handheld and have more than 70
percent battery life. AWS IoT keeps it continuously updated with your latest data.
AWS_Things is the index created for all of your things. AWS_ThingGroups is the index that contains all
of your thing groups.
You can use the AWS IoT console to manage your indexing configuration and run your search queries.
Choose the indexes you would like to use in the console settings page. If you prefer programmatic access,
you can use the AWS SDKs or the AWS CLI.
For information about pricing this and other services, see the AWS IoT Device Management Pricing page.
The following command shows how to use the get-indexing-configuration CLI command to retrieve the
current thing indexing configuration. (In this example, thing indexing is currently disabled.)
thingIndexingMode Result
thingConnectivityIndexingMode
472
AWS IoT Developer Guide
Describing a Thing Index
thingIndexingMode Result
thingConnectivityIndexingMode
Use the update-indexing-configuration CLI command to update the thing indexing configuration. In the
following example, you can search registry data, shadow data, and thing connectivity status data using
the AWS_Things index (after it is built, as described in the next section).
The first time you enable indexing, AWS IoT builds your index. You can't query the index if
indexStatus is in the BUILDING state. The schema for the things index indicates which type of data
(REGISTRY_AND_SHADOW_AND_CONNECTIVITY_STATUS) is indexed.
Changing the configuration of your index causes the index to be rebuilt. During this process, the
indexStatus is REBUILDING. You can execute queries on data in the things index while it is being
rebuilt. For example, if you change the index configuration from REGISTRY to REGISTRY_AND_SHADOW,
473
AWS IoT Developer Guide
Querying a Thing Index
while the index is being rebuilt, you can query registry data, including the latest updates. However, you
can't query the shadow data until the rebuild is complete. The amount of time it takes to build or rebuild
the index depends on the amount of data.
474
AWS IoT Developer Guide
Restrictions and Limitations
"stats":{
"battery":{
"timestamp":34535454
}
}
}
},
"version":10,
"timestamp":34535454
},
"connectivity": {
"connected":true,
"timestamp":1556649855046
}
}],
"nextToken":"AQFCuvk7zZ3D9pOYMbFCeHbdZ+h=G"
}
"connectivity": {
"connected":false,
"timestamp":1556649874716
}
"connectivity": {
"connected":true,
"timestamp":1556649855046
}
A shadow field is indexed only if the value of the field is a simple type or an array that consists
entirely of simple types. (Simple type means a string, number, or one of the literals true or false).
If a field's value is itself a JSON object, or an array that contains an object, indexing is not performed
on that field. For example, given the following shadow state, the value of field "palette" is not
indexed because it's an array whose items are objects. The value of field "colors" is indexed
because each value in the array is a string.
475
AWS IoT Developer Guide
Authorization
"state": {
"reported": {
"switched": "ON",
"colors": [ "RED", "GREEN", "BLUE" ],
"palette": [
{
"name": "RED",
"intensity": 124
},
{
"name": "GREEN",
"intensity": 68
},
{
"name": "BLUE",
"intensity": 201
}
]
}
}
}
Shadow metadata
A field in a shadow's metadata section is indexed, but only if the corresponding field in the shadow's
"state" section is indexed. (In the previous example, the "palette" field in the shadow's
metadata section is not indexed either.)
Unregistered shadows
If you use CreateThing to create a shadow using a thing name that hasn't been registered in your
AWS IoT account, fields in this shadow are not indexed.
Numeric values
If any registry or shadow data is recognized by the service as a numeric value, it's indexed as
such. You can form queries involving ranges and comparison operators on numeric values (for
example, "attribute.foo<5" or "shadow.reported.foo:[75 TO 80]"). To be recognized as
numeric, the value of the data must be a valid JSON "number" type literal (an integer in the range
-2^53...2^53-1 or a double-precision floating point with optional exponential notation) or part of an
array that contains only such values.
Null values
Authorization
You can specify the things index as a resource ARN in an AWS IoT policy action, as follows.
Action Resource
476
AWS IoT Developer Guide
Managing Thing Group Indexing
Note
If you have permissions to query the fleet index, you can access the data of things across the
entire fleet.
Use the get-indexing-configuration CLI command to retrieve the current thing and thing group indexing
configurations.
Use the update-indexing-configuration CLI command to update the thing group indexing
configurations.
Note
You can also update configurations for both thing and thing group indexing in a single
command, as follows.
OFF
No indexing/delete index.
ON
477
AWS IoT Developer Guide
Querying a Thing Group Index
"indexStatus": "ACTIVE",
"indexName": "AWS_ThingGroups",
"schema": "THING_GROUPS"
}
The first time you enable indexing, AWS IoT builds your index. You can't query the index if the
indexStatus is BUILDING.
Authorization
You can specify the thing groups index as a resource ARN in an AWS IoT policy action, as follows.
Action Resource
This command returns the number of things that have a property called connectivity.connected set
to true in their device shadow:
{
"statistics" : {
"count" : 1000
}
}
index-name
The query used to search the index. You can specify "*" to get the count of all indexed things in
your AWS account.
478
AWS IoT Developer Guide
Query Syntax
query-version
The get-statistics CLI command returns data in a JSON object. Currently, the only statistic returned is
count:
{
"statistics" : {
"count" : 1000
}
}
Query Syntax
Queries are specified using a query syntax.
• Leading wildcard search (such as "*xyz"). (Searching for "*" matches all things, however.)
• Regular expressions
• Boosting
• Ranking
• Fuzzy searches
• Proximity search
• Sorting
• Aggregation
479
AWS IoT Developer Guide
Example Thing Queries
• Device shadow and registry versions are not searchable, but are present in the response.
• The maximum number of terms in a query is 5.
attributes.attr1:abc AND attributes.attr2<5 NOT Queries for things that combine terms using
attributes.attr3>10 Boolean expressions. This query returns things
that have an attribute named "attr1" with a value
"abc", an attribute named "attr2" that is less than
5, and an attribute named "attr3" that is not
greater than 10.
480
AWS IoT Developer Guide
Example Thing Group Queries
481
AWS IoT Developer Guide
Example Thing Group Queries
attributes.attr1:abc AND attributes.attr2<5 NOT Queries for thing groups that combine terms
attributes.attr3>10 using Boolean expressions. This query returns
thing groups that have an attribute named "attr1"
with a value "abc", an attribute named "attr2" that
is less than 5, and an attribute named "attr3" that
is not greater than 10.
482
AWS IoT Developer Guide
Audit
IoT fleets may consist of large numbers of devices that have diverse capabilities, are long-lived, and
are geographically distributed. These characteristics make fleet setup complex and error-prone. And
since devices are often constrained in computational power, memory, and storage capabilities, this limits
the use of encryption and other forms of security on the devices themselves. Also, devices often use
software with known vulnerabilities. The combination of these factors makes IoT fleets an attractive
target for hackers and make it difficult to secure your device fleet on an ongoing basis.
AWS IoT Device Defender addresses these challenges by providing tools to identify security issues and
deviations from best practices. AWS IoT Device Defender can audit device fleets to ensure they adhere to
security best practices and detect abnormal behavior on devices.
Note
AWS IoT Device Defender is not available in the China (Beijing) Region.
Audit
An AWS IoT Device Defender audit looks at account and device-related settings and policies to ensure
security measures are in place. An audit can help you detect any drifts from security best practices or
proper access policies, such as multiple devices using the same identity, or overly-permissive policies that
allow one device to read and update data for many other devices. You can run audits as needed ("on-
demand audits") or schedule them to be run periodically ("scheduled audits").
An AWS IoT Device Defender audit runs a set of pre-defined checks (Audit checks (p. 483)) for common
IoT security best practices and device vulnerabilities. Examples of pre-defined checks include policies
that grant permission to read or update data on multiple device's, devices that share an identity (X.509
certificate), or certificates that are expiring or have been revoked but are still active.
Audit checks
Note
When a check is enabled, data collection begins immediately. If you have a large amount of data
in your account to be collected, then results of the check may not be available for some time
after you have enabled it.
REVOKED_CA_CERT_CHECK
Severity: Critical
more info (1)
A CA certificate is marked as revoked in the Certificate Revocation List maintained by the issuing
authority, but is still marked as "ACTIVE" or "PENDING_TRANSFER" in the AWS IoT system.
The following reason codes are returned when this check finds a non-compliant CA certificate:
• CERTIFICATE_REVOKED_BY_ISSUER
483
AWS IoT Developer Guide
Audit checks
A revoked CA certificate should no longer be used to sign device certificates. It may have been
revoked because it was compromised, and newly added devices with certificates signed using this CA
certificate might pose a security threat.
how to fix it (1)
1. Mark the CA certificate as "INACTIVE" in the AWS IoT system using UpdateCACertificate.
2. Review the device certificate registration activity for the time after the CA certificate was revoked
and consider revoking any device certificates that may have been issued with it during this
time. (Use ListCertificatesByCA to list the device certificates signed by the CA certificate and
UpdateCertificate to revoke a device certificate.)
DEVICE_CERTIFICATE_SHARED_CHECK
Multiple, concurrent connections use the same X.509 certificate to authenticate with the AWS IoT
service.
Severity: Critical
more info (2)
When this check is enabled, data collection begins immediately, but results of the check are not
available for at least two hours.
When performed as part of an on-demand audit, this check looks at the certificates and clientIDs
that were used by devices to connect during the 31 days prior to the start of the audit. For scheduled
audits, this check looks at data from the last time the audit was run to the time this instance of the
audit started. If you have taken steps to mitigate this condition during the time checked, note when
the concurrent connections were made to determine if the problem persists.
The following reason codes are returned when this check finds a non-compliant certificate:
• CERTIFICATE_SHARED_BY_MULTIPLE_DEVICES
In addition, the findings returned by this check include the ID of the shared certificate, the IDs of the
clients using the certificate to connect, and the connect/disconnect times. Results are listed in order
of most recent first.
why it matters (2)
Each device should have a unique certificate to authenticate with AWS IoT. When multiple devices
use the same certificate this may indicate that a device has been compromised and its identity
cloned in order to further compromise the system.
how to fix it (2)
Verify that the device certificate has not been compromised. If it has, follow your security best
practices to mitigate the situation.
If you are using the same certificate on multiple devices, you may want to:
484
AWS IoT Developer Guide
Audit checks
UNAUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK
Or, because it grants permission to perform the following AWS IoT actions on a broad set of devices:
In general, devices which connect using an unauthenticated Cognito identity pool role should have
only limited permission to publish/subscribe to thing-specific MQTT topics or use the API commands
to read/modify thing-specific data related to shadow or job execution data.
Severity: Critical
manage or modify things (3)
The following AWS IoT API actions are used to manage or modify things so permission to perform
these should not be granted to devices connecting via an unauthenticated Cognito identity pool:
• AddThingToThingGroup
• AttachThingPrincipal
• CreateThing
• DeleteThing
• DetachThingPrincipal
• ListThings
• ListThingsInThingGroup
• RegisterThing
• RemoveThingFromThingGroup
• UpdateThing
• UpdateThingGroupsForThing
Any role that grants permission to perform these actions on even a single resource is considered
non-compliant.
read thing administrative data (3)
The following AWS IoT API actions are used to read or modify thing data so devices connecting via
an unauthenticated Cognito identity pool should not be given permission to perform these:
• DescribeThing
• ListJobExecutionsForThing
• ListThingGroupsForThing
• ListThingPrincipals
Example:
• non-compliant:
485
AWS IoT Developer Guide
Audit checks
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:DescribeThing",
"iot:ListJobExecutionsForThing",
"iot:ListThingGroupsForThing",
"iot:ListThingPrincipals"
],
"Resource": [
"arn:aws:iot:<region>:<account-id>:/thing/MyThing"
]
}
]
}
This allows the device to perform the specified actions even though it is granted for only one
specific thing.
Devices connecting via an unauthenticated Cognito identity pool should not be given permission
to perform any other AWS IoT API actions other than those discussed in these sections. In order to
manage your account with an application that connects via an unauthenticated Cognito identity
pool, create a separate identity pool not used by devices.
subscribe/publish to MQTT topics (3)
MQTT messages are sent through the AWS IoT message broker and are used by devices to perform
many different actions, including accessing and modifying shadow state and job execution state. A
policy that grants permission to a device to connect, publish or subscribe to MQTT messages should
restrict these actions to specific resources as follows:
Connect
• non-compliant:
arn:aws:iot:<region>:<account-id>:client/*
arn:aws:iot:<region>:<account-id>:client/${iot:ClientId}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "iot:Connect" ],
"Resource": [
"arn:aws:iot:<region>:<account-id>:client/
${iot:Connection.Thing.ThingName}"
486
AWS IoT Developer Guide
Audit checks
],
"Condition": {
"Bool": { "iot:Connection.Thing.IsAttached": "true" }
}
}
]
}
The resource specification contains a variable that matches the device name used to connect,
and the condition statement further restricts the permission by checking that the certificate
used by the MQTT client matches that attached to the thing with the name used.
Publish
• non-compliant:
arn:aws:iot:<region>:<account-id>:topic/$aws/things/*/shadow/update
This allows the device to update the shadow of any device (* = all devices).
arn:aws:iot:<region>:<account-id>:topic/$aws/things/*
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "iot:Publish" ],
"Resource": [
"arn:aws:iot:<region>:<account-id>:topic/$aws/things/
${iot:Connection.Thing.ThingName}/shadow/*"
],
}
]
}
The resource specification contains a wildcard, but it only matches any shadow-related topic
for the device whose thing name is used to connect.
Subscribe
• non-compliant:
arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/*
This allows the device to subscribe to reserved shadow or job topics for all devices.
arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/*
arn:aws:iot:<region>:<account-id>:topic/$aws/things/+/shadow/update
This allows the device to see shadow updates on any device (+ = all devices).
• compliant:
487
AWS IoT Developer Guide
Audit checks
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "iot:Subscribe" ],
"Resource": [
"arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/
${iot:Connection.Thing.ThingName}/shadow/*"
"arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/
${iot:Connection.Thing.ThingName}/jobs/*"
],
}
]
}
The resource specifications contain wildcards but they only match any shadow-related topic
and any job-related topic for the device whose thing name is used to connect.
Receive
• compliant:
arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/*
This is okay because the device can only receive messages from topics on which it has
permission to subscribe.
A policy that grants permission to a device to perform an API action to access or modify device
shadows or job execution data should restrict these actions to specific resources. The API actions are:
• DeleteThingShadow
• GetThingShadow
• UpdateThingShadow
• DescribeJobExecution
• GetPendingJobExecutions
• StartNextPendingJobExecution
• UpdateJobExecution
Examples:
• non-compliant:
arn:aws:iot:<region>:<account-id>:thing/*
This allows the device to perform the specified action on any thing.
• compliant:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
488
AWS IoT Developer Guide
Audit checks
"Action": [
"iot:DeleteThingShadow",
"iot:GetThingShadow",
"iot:UpdateThingShadow",
"iot:DescribeJobExecution",
"iot:GetPendingJobExecutions",
"iot:StartNextPendingJobExecution",
"iot:UpdateJobExecution"
],
"Resource": [
"arn:aws:iot:<region>:<account-id>:/thing/MyThing1",
"arn:aws:iot:<region>:<account-id>:/thing/MyThing2"
]
}
]
}
This allows the device to perform the specified actions on only two specific things.
For this check, AWS IoT Device Defender audits all Cognito identity pools that have been used to
connect to the AWS IoT message broker during the past 31 days prior to the audit execution. All
Cognito identity pools from which either an authenticated or unauthenticated Cognito identity
connected are included in the audit.
The following reason codes are returned when this check finds a non-compliant unauthenticated
Cognito identity pool role:
• ALLOWS_ACCESS_TO_IOT_ADMIN_ACTIONS
• ALLOWS_BROAD_ACCESS_TO_IOT_DATA_PLANE_ACTIONS
Because unauthenticated identities are never authenticated by the user, they pose a much greater
risk than authenticated Cognito identities. If an unauthenticated identity is compromised it could
use administrative actions to modify account settings, delete resources or gain access to sensitive
data. Or, with broad access to device settings, it could access or modify shadows and jobs for all
devices in your account. A guest user might use the permissions to compromise your entire fleet or
launch a DDOS attack with messages.
how to fix it (3)
A policy attached to an unauthenticated Cognito identity pool role should grant only those
permissions required for a device to do its job. We recommend the following steps:
AUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK
489
AWS IoT Developer Guide
Audit checks
Or, because it grants permission to perform the following AWS IoT actions on a broad set of devices:
In general, devices that connect using an authenticated Cognito identity pool role should have only
limited permission to read thing-specific administrative data, publish/subscribe to thing-specific
MQTT topics or use the API commands to read/modify thing-specific data related to shadow or job
execution data.
Severity: Critical
manage or modify things (4)
The following AWS IoT API actions are used to manage or modify things so permission to perform
these should not be granted to devices connecting via an authenticated Cognito identity pool:
• AddThingToThingGroup
• AttachThingPrincipal
• CreateThing
• DeleteThing
• DetachThingPrincipal
• ListThings
• ListThingsInThingGroup
• RegisterThing
• RemoveThingFromThingGroup
• UpdateThing
• UpdateThingGroupsForThing
Any role that grants permission to perform these actions on even a single resource is considered
non-compliant.
manage non-things (4)
Devices connecting via an authenticated Cognito identity pool should not be given permission to
perform any other AWS IoT API actions other than those discussed in these sections. In order to
manage your account with an application that connects via an authenticated Cognito identity pool,
create a separate identity pool not used by devices.
read thing administrative data (4)
The following AWS IoT API actions are used to read thing data so devices connecting via an
authenticated Cognito identity pool should be given permission to perform these on only a limited
set of things:
• DescribeThing
• ListJobExecutionsForThing
• ListThingGroupsForThing
490
AWS IoT Developer Guide
Audit checks
• ListThingPrincipals
Examples:
• non-compliant:
arn:aws:iot:<region>:<account-id>:thing/*
This allows the device to perform the specified action on any thing.
• compliant:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:DescribeThing",
"iot:ListJobExecutionsForThing",
"iot:ListThingGroupsForThing",
"iot:ListThingPrincipals"
],
"Resource": [
"arn:aws:iot:<region>:<account-id>:/thing/MyThing"
]
}
]
}
This allows the device to perform the specified actions on only one specific thing.
• compliant:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:DescribeThing",
"iot:ListJobExecutionsForThing",
"iot:ListThingGroupsForThing",
"iot:ListThingPrincipals"
],
"Resource": [
"arn:aws:iot:<region>:<account-id>:/thing/MyThing*"
]
}
]
}
This is compliant because, although the resource is specified with a wildcard (*), this is preceded by
a specific string, and that limits the set of things accessed to those with names that have the given
prefix.
MQTT messages are sent through the AWS IoT message broker and are used by devices to perform
many different actions, including accessing and modifying shadow state and job execution state. A
491
AWS IoT Developer Guide
Audit checks
policy that grants permission to a device to connect, publish or subscribe to MQTT messages should
restrict these actions to specific resources as follows:
Connect
• non-compliant:
arn:aws:iot:<region>:<account-id>:client/*
arn:aws:iot:<region>:<account-id>:client/${iot:ClientId}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "iot:Connect" ],
"Resource": [
"arn:aws:iot:<region>:<account-id>:client/
${iot:Connection.Thing.ThingName}"
],
"Condition": {
"Bool": { "iot:Connection.Thing.IsAttached": "true" }
}
}
]
}
The resource specification contains a variable that matches the device name used to connect,
and the condition statement further restricts the permission by checking that the certificate
used by the MQTT client matches that attached to the thing with the name used.
Publish
• non-compliant:
arn:aws:iot:<region>:<account-id>:topic/$aws/things/*/shadow/update
This allows the device to update the shadow of any device (* = all devices).
arn:aws:iot:<region>:<account-id>:topic/$aws/things/*
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "iot:Publish" ],
"Resource": [
492
AWS IoT Developer Guide
Audit checks
"arn:aws:iot:<region>:<account-id>:topic/$aws/things/
${iot:Connection.Thing.ThingName}/shadow/*"
],
}
]
}
The resource specification contains a wildcard, but it only matches any shadow-related topic
for the device whose thing name is used to connect.
Subscribe
• non-compliant:
arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/*
This allows the device to subscribe to reserved shadow or job topics for all devices.
arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/#
arn:aws:iot:<region>:<account-id>:topic/$aws/things/+/shadow/update
This allows the device to see shadow updates on any device (+ = all devices).
• compliant:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "iot:Subscribe" ],
"Resource": [
"arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/
${iot:Connection.Thing.ThingName}/shadow/*"
"arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/
${iot:Connection.Thing.ThingName}/jobs/*"
],
}
]
}
The resource specifications contain wildcards but they only match any shadow-related topic
and any job-related topic for the device whose thing name is used to connect.
Receive
• compliant:
arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/*
This is okay because the device can only receive messages from topics on which it has
permission to subscribe.
493
AWS IoT Developer Guide
Audit checks
A policy that grants permission to a device to perform an API action to access or modify device
shadows or job execution data should restrict these actions to specific resources. The API actions are:
• DeleteThingShadow
• GetThingShadow
• UpdateThingShadow
• DescribeJobExecution
• GetPendingJobExecutions
• StartNextPendingJobExecution
• UpdateJobExecution
Examples:
• non-compliant:
arn:aws:iot:<region>:<account-id>:thing/*
This allows the device to perform the specified action on any thing.
• compliant:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:DeleteThingShadow",
"iot:GetThingShadow",
"iot:UpdateThingShadow",
"iot:DescribeJobExecution",
"iot:GetPendingJobExecutions",
"iot:StartNextPendingJobExecution",
"iot:UpdateJobExecution"
],
"Resource": [
"arn:aws:iot:<region>:<account-id>:/thing/MyThing1",
"arn:aws:iot:<region>:<account-id>:/thing/MyThing2"
]
}
]
}
This allows the device to perform the specified actions on only two specific things.
For this check, AWS IoT Device Defender audits all Cognito identity pools that have been used to
connect to the AWS IoT message broker during the past 31 days prior to the audit execution. All
Cognito identity pools from which either an authenticated or unauthenticated Cognito identity
connected are included in the audit.
The following reason codes are returned when this check finds a non-compliant authenticated
Cognito identity pool role:
• ALLOWS_BROAD_ACCESS_TO_IOT_THING_ADMIN_READ_ACTIONS
494
AWS IoT Developer Guide
Audit checks
• ALLOWS_ACCESS_TO_IOT_NON_THING_ADMIN_ACTIONS
• ALLOWS_ACCESS_TO_IOT_THING_ADMIN_WRITE_ACTIONS
A policy attached to an authenticated Cognito identity pool role should grant only those permissions
required for a device to do its job. We recommend the following steps:
IOT_POLICY_OVERLY_PERMISSIVE_CHECK
An AWS IoT policy gives permissions that are too broad/unrestricted. It grants permission to send or
receive MQTT messages for a broad set of devices, or grants permission to access or modify shadow
and job execution data for a broad set of devices.
In general, a policy for a device should grant access to very specific resources associated with
just that device and no, or very few, other devices. With certain exceptions, using a wildcard (for
example, "*") to specify resources in such a policy is considered too broad/unrestricted.
Severity: Critical
MQTT permissions (5)
MQTT messages are sent through the AWS IoT message broker and are used by devices to perform
many different actions, including accessing and modifying shadow state and job execution state. A
policy that grants permission to a device to connect, publish or subscribe to MQTT messages should
restrict these actions to specific resources as follows:
Connect
• non-compliant:
arn:aws:iot:<region>:<account-id>:client/*
arn:aws:iot:<region>:<account-id>:client/${iot:ClientId}
{
"Version": "2012-10-17",
495
AWS IoT Developer Guide
Audit checks
"Statement": [
{
"Effect": "Allow",
"Action": [ "iot:Connect" ],
"Resource": [
"arn:aws:iot:<region>:<account-id>:client/
${iot:Connection.Thing.ThingName}"
],
"Condition": {
"Bool": { "iot:Connection.Thing.IsAttached": "true" }
}
}
]
}
The resource specification contains a variable that matches the device name used to connect,
and the condition statement further restricts the permission by checking that the certificate
used by the MQTT client matches that attached to the thing with the name used.
Publish
• non-compliant:
arn:aws:iot:<region>:<account-id>:topic/$aws/things/*/shadow/update
This allows the device to update the shadow of any device (* = all devices).
arn:aws:iot:<region>:<account-id>:topic/$aws/things/*
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "iot:Publish" ],
"Resource": [
"arn:aws:iot:<region>:<account-id>:topic/$aws/things/
${iot:Connection.Thing.ThingName}/shadow/*"
],
}
]
}
The resource specification contains a wildcard, but it only matches any shadow-related topic
for the device whose thing name is used to connect.
Subscribe
• non-compliant:
arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/*
This allows the device to subscribe to reserved shadow or job topics for all devices.
arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/*
496
AWS IoT Developer Guide
Audit checks
arn:aws:iot:<region>:<account-id>:topic/$aws/things/+/shadow/update
This allows the device to see shadow updates on any device (+ = all devices).
• compliant:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "iot:Subscribe" ],
"Resource": [
"arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/
${iot:Connection.Thing.ThingName}/shadow/*"
"arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/
${iot:Connection.Thing.ThingName}/jobs/*"
],
}
]
}
The resource specifications contain wildcards but they only match any shadow-related topic
and any job-related topic for the device whose thing name is used to connect.
Receive
• compliant:
arn:aws:iot:<region>:<account-id>:topicfilter/$aws/things/*
This is okay because the device can only receive messages from topics on which it has
permission to subscribe.
A policy that grants permission to a device to perform an API action to access or modify device
shadows or job execution data should restrict these actions to specific resources. The API actions are:
• DeleteThingShadow
• GetThingShadow
• UpdateThingShadow
• DescribeJobExecution
• GetPendingJobExecutions
• StartNextPendingJobExecution
• UpdateJobExecution
Examples:
• non-compliant:
arn:aws:iot:<region>:<account-id>:thing/*
This allows the device to perform the specified action on any thing.
• compliant:
497
AWS IoT Developer Guide
Audit checks
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:DeleteThingShadow",
"iot:GetThingShadow",
"iot:UpdateThingShadow",
"iot:DescribeJobExecution",
"iot:GetPendingJobExecutions",
"iot:StartNextPendingJobExecution",
"iot:UpdateJobExecution"
],
"Resource": [
"arn:aws:iot:<region>:<account-id>:/thing/MyThing1",
"arn:aws:iot:<region>:<account-id>:/thing/MyThing2"
]
}
]
}
This allows the device to perform the specified actions on only two specific things.
The following reason code is returned when this check finds a non-compliant IoT policy:
• ALLOWS_BROAD_ACCESS_TO_IOT_DATA_PLANE_ACTIONS
A certificate, Cognito identity or thing group with an overly-permissive policy can, if compromised,
impact the security of your entire account. An attacker could use such broad access to read or
modify shadows, jobs or job executions for all your devices. Or an attacker could use a compromised
certificate to connect malicious devices or launch a DDOS attack on your network.
how to fix it (5)
Follow these steps to fix any non-compliant policies attached to things, thing groups, or other
entities:
1. Create a new, compliant version of the policy using CreatePolicyVersion with the "setAsDefault"
flag set to true (making this new version operative for all entities that use the policy).
2. Get a list of targets (certificates, thing groups) that the policy is attached to using
ListTargetsForPolicy and determine which devices are included in the groups or which use the
certificates to connect.
3. Verify that all associated devices are able to connect to AWS IoT. If a device is unable to connect,
roll back the default policy to the previous version using SetPolicyVersion, revise the policy and
try again.
Use AWS IoT Policy Variables to dynamically reference specific AWS IoT resources in your policies.
498
AWS IoT Developer Guide
Audit checks
CA_CERT_APPROACHING_EXPIRATION_CHECK
Severity: Medium
more info (6)
The following reason codes are returned when this check finds a non-compliant CA certificate:
• CERTIFICATE_APPROACHING_EXPIRATION
• CERTIFICATE_PAST_EXPIRATION
Consult your security best practices for how to proceed. You may want to:
CONFLICTING_CLIENT_IDS_CHECK
Severity: High
more info (7)
Multiple connections were made using the same client ID, causing an already connected device to
be disconnected. The MQTT specification allows only one active connection per client ID, so when
another device connects using the same client ID, it knocks the previous one off the connection.
When performed as part of an on-demand audit, this check looks at how clientIDs were used to
connect during the 31 days prior to the start of the audit. For scheduled audits, this check looks
at data from the last time the audit was run to the time this instance of the audit started. If you
have taken steps to mitigate this condition during the time checked, note when the connections/
disconnections were made to determine if the problem persists.
The following reason codes are returned when this check finds non-compliance:
• DUPLICATE_CLIENT_ID_ACROSS_CONNECTIONS
In addition, the findings returned by this check include the clientID used to connect, principal IDs,
and disconnect times. Results are listed in order of most recent first.
why it matters (7)
Devices with conflicting IDs are forced to constantly reconnect, which may result in lost messages or
leave a device unable to connect.
This may indicate that a device or a device's credentials have been compromised, and might be part
of a DDoS attack. It is also possible that devices are misconfigured in the account or a device has a
bad connection and is forced to reconnect several times per minute.
499
AWS IoT Developer Guide
Audit checks
how to fix it (7)
Register each device as a unique thing in AWS IoT, and use the thing name as the client ID to
connect. Or use a UUID as the client ID when connecting the device over MQTT.
DEVICE_CERT_APPROACHING_EXPIRATION_CHECK
Severity: Medium
more info (8)
The following reason codes are returned when this check finds a non-compliant device certificate:
• CERTIFICATE_APPROACHING_EXPIRATION
• CERTIFICATE_PAST_EXPIRATION
Consult your security best practices for how to proceed. You may want to:
REVOKED_DEVICE_CERT_CHECK
Severity: Medium
more info (9)
A device certificate is in its CA's Certificate revocation list but it is still active in AWS IoT.
The following reason codes are returned when this check finds non-compliance:
• CERTIFICATE_REVOKED_BY_ISSUER
A device certificate is usually revoked because it has been compromised. It is possible that it has not
yet been revoked in AWS IoT due to an error or an oversight.
how to fix it (9)
Verify that the device certificate has not been compromised. If it has, follow your security best
practices to mitigate the situation. You may want to:
500
AWS IoT Developer Guide
How To Perform Audits
LOGGING_DISABLED_CHECK
Severity: Low
more info (10)
The following reason codes are returned when this check finds non-compliance:
• LOGGING_DISABLED
Amazon IoT CloudWatch logs provide visibility into behaviors within AWS IoT, including
authentication failures and unexpected connects and disconnects, that may indicate that a device
has been compromised.
how to fix it (10)
For certain checks, AWS IoT begins collecting data as soon as the check is enabled.
2. Create one or more audit schedules. Use CreateScheduledAudit (p. 512) to specify the checks you
want to perform during an audit and how often these audits should be run.
Or, you can run an on-demand audit when necessary. Use StartOnDemandAuditTask (p. 521) to
specify the checks you want to perform and start an audit running right away. (Results may not be
ready for some time if you have recently enabled a check that is included in the on-demand audit.)
3. You can use the AWS IoT console to view the results of your audits.
Or, you can see the results of your audits with ListAuditFindings (p. 528). With this command, you
can filter the results by the type of check, a specific resource, or the time of the audit. Armed with
this information, you can take the appropriate steps to mitigate any problems found.
Notifications
When an audit is completed, an SNS notification can be sent with a summary of the results of each
audit check that was performed, including details about the number of non-compliant resources
that were found. Use the auditNotificationTargetConfigurations field in the input to the
UpdateAccountAuditConfiguration (p. 508) command. The SNS notification has the following payload:
501
AWS IoT Developer Guide
Notifications
payload example
{
"accountId": "123456789012",
"taskId": "4e2bcd1ccbc2a5dd15292a82ab80c380",
"taskStatus": "FAILED|CANCELED|COMPLETED",
"taskType": "ON_DEMAND_AUDIT_TASK|SCHEDULED_AUDIT_TASK",
"scheduledAuditName": "myWeeklyAudit",
"failedChecksCount": 0,
"canceledChecksCount": 0,
"nonCompliantChecksCount": 1,
"compliantChecksCount": 0,
"totalChecksCount": 1,
"taskStartTime": 1524740766191,
"auditDetails": [
{
"checkName": "DEVICE_CERT_APPROACHING_EXPIRATION_CHECK |
REVOKED_DEVICE_CERT_CHECK |
CA_CERT_APPROACHING_EXPIRATION_CHECK |
REVOKED_CA_CERT_CHECK |
DEVICE_CERTIFICATE_SHARED_CHECK |
IOT_POLICY_UNRESTRICTED_CHECK |
UNAUTHENTICATED_COGNITO_IDENTITY_UNRESTRICTED_ACCESS_CHECK |
AUTHENTICATED_COGNITO_IDENTITY_UNRESTRICTED_ACCESS_CHECK |
CONFLICTING_CLIENT_IDS_CHECK |
LOGGING_DISABLED_CHECK",
"checkRunStatus": "FAILED |
CANCELED |
COMPLETED_COMPLIANT |
COMPLETED_NON_COMPLIANT",
"nonCompliantResourcesCount": 1,
"totalResourcesCount": 1,
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "arn:aws:iot:::schema:auditnotification/1.0",
"type": "object",
"properties": {
"accountId": {
"type": "string"
},
"taskId": {
"type": "string"
},
"taskStatus": {
"type": "string",
"enum": [
"FAILED",
"CANCELED",
"COMPLETED"
]
},
"taskType": {
502
AWS IoT Developer Guide
Notifications
"type": "string",
"enum": [
"SCHEDULED_AUDIT_TASK",
"ON_DEMAND_AUDIT_TASK"
]
},
"scheduledAuditName": {
"type": "string"
},
"failedChecksCount": {
"type": "integer"
},
"canceledChecksCount": {
"type": "integer"
},
"nonCompliantChecksCount": {
"type": "integer"
},
"compliantChecksCount": {
"type": "integer"
},
"totalChecksCount": {
"type": "integer"
},
"taskStartTime": {
"type": "integer"
},
"auditDetails": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"checkName": {
"type": "string",
"enum": [
"DEVICE_CERT_APPROACHING_EXPIRATION_CHECK",
"REVOKED_DEVICE_CERT_CHECK",
"CA_CERT_APPROACHING_EXPIRATION_CHECK",
"REVOKED_CA_CERT_CHECK",
"LOGGING_DISABLED_CHECK"
]
},
"checkRunStatus": {
"type": "string",
"enum": [
"FAILED",
"CANCELED",
"COMPLETED_COMPLIANT",
"COMPLETED_NON_COMPLIANT"
]
},
"nonCompliantResourcesCount": {
"type": "integer"
},
"totalResourcesCount": {
"type": "integer"
},
"message": {
"type": "string",
},
"errorCode": {
"type": "string",
"enum": [
"INSUFFICIENT_PERMISSIONS",
"AUDIT_CHECK_DISABLED"
503
AWS IoT Developer Guide
Permissions
]
}
},
"required": [
"checkName",
"checkRunStatus",
"nonCompliantResourcesCount",
"totalResourcesCount"
]
}
]
}
},
"required": [
"accountId",
"taskId",
"taskStatus",
"taskType",
"failedChecksCount",
"canceledChecksCount",
"nonCompliantChecksCount",
"compliantChecksCount",
"totalChecksCount",
"taskStartTime",
"auditDetails"
]
}
Notifications can also be viewed in the AWS IoT console, along with additional information about the
device, device statistics (for example, last connection time, number of active connections, data transfer
rate), and historical alerts for the device.
Permissions
This section contains information on how to set up the AWS IAM roles and policies required to create, run
and manage AWS IoT Device Defender audits. For more information on AWS IAM, see the AWS Identity
and Access Management User Guide.
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"iot:GetLoggingOptions",
"iot:GetV2LoggingOptions",
"iot:ListCACertificates",
"iot:ListCertificates",
"iot:DescribeCACertificate",
504
AWS IoT Developer Guide
Permissions
"iot:DescribeCertificate",
"iot:ListPolicies",
"iot:GetPolicy",
"iot:GetEffectivePolicies",
"cognito-identity:GetIdentityPoolRoles",
"iam:ListRolePolicies",
"iam:ListAttachedRolePolicies",
"iam:GetPolicy",
"iam:GetPolicyVersion",
"iam:GetRolePolicy"
],
"Resource":[
"*"
]
}
]
}
trust policy
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "iot.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"sns:Publish"
],
"Resource":[
"arn:aws:sns:region:account-id:your-topic-name"
]
}
]
}
505
AWS IoT Developer Guide
Permissions
trust policy
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "iot.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
• UpdateAccountAuditConfiguration
policy
NOTE: You must create the IAM Role with the attached policy in same account from which this
command is run. Cross account access is not allowed. The policy should have "iam:PassRole" permissions
(permissions to pass this role).
In the following policy template audit-permissions-role-arn is the roleArn that you pass
to AWS IoT Device Defender in the UpdateAccountAuditConfiguration request using the
roleArn parameter. audit-notifications-permissions-role-arn is the roleArn that you
pass to AWS IoT Device Defender in the UpdateAccountAuditConfiguration request using the
auditNotificationTargetConfigurations parameter.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:UpdateAccountAuditConfiguration"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"iam:PassRole"
],
"Resource": [
"arn:aws:iam::account-id:role/audit-permissions-role-arn",
"arn:aws:iam::account-id:role/audit-notifications-permissions-role-arn"
]
}
506
AWS IoT Developer Guide
Permissions
]
}
• DescribeAccountAuditConfiguration
• DeleteAccountAuditConfiguration
• StartOnDemandAuditTask
• CancelAuditTask
• DescribeAuditTask
• ListAuditTasks
• ListScheduledAudits
• ListAuditFindings
policy
NOTE: all these commands require * in the Resource field of the policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:DescribeAccountAuditConfiguration",
"iot:DeleteAccountAuditConfiguration",
"iot:StartOnDemandAuditTask",
"iot:CancelAuditTask",
"iot:DescribeAuditTask",
"iot:ListAuditTasks",
"iot:ListScheduledAudits",
"iot:ListAuditFindings"
],
"Resource": [
"*"
]
}
]
}
• CreateScheduledAudit
• UpdateScheduledAudit
• DeleteScheduledAudit
• DescribeScheduledAudit
policy
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:CreateScheduledAudit",
"iot:UpdateScheduledAudit",
"iot:DeleteScheduledAudit",
"iot:DescribeScheduledAudit"
],
507
AWS IoT Developer Guide
Service Limits
"Resource": [
"arn:aws:iot:region:account-id:scheduledaudit/scheduled-audit-name"
]
}
]
}
The format for an AWS IoT Device Defender scheduled audit roleArn is:
arn:aws:iot:region:account-id:scheduledaudit/scheduled-audit-name
Service Limits
Resource Limit Description
Audit Commands
Manage Audit Settings
Configure audit settings for your account using UpdateAccountAuditConfiguration. This command
allows you to enable those checks you want to be available for audits, set up optional notifications, and
configure permissions.
Use DeleteAccountAuditConfiguration to delete your audit settings. This restores all default
values, and effectively disables audits since all checks are disabled by default.
UpdateAccountAuditConfiguration
Configures or reconfigures the Device Defender audit settings for this account. Settings include how
audit notifications are sent and which audit checks are enabled or disabled.
Synopsis
cli-input-json format
508
AWS IoT Developer Guide
Manage Audit Settings
{
"roleArn": "string",
"auditNotificationTargetConfigurations": {
"string": {
"targetArn": "string",
"roleArn": "string",
"enabled": "boolean"
}
},
"auditCheckConfigurations": {
"string": {
"enabled": "boolean"
}
}
}
cli-input-json fields
auditNotificationTargetConfigurations
map Information about the targets
to which audit notifications are
sent.
509
AWS IoT Developer Guide
Manage Audit Settings
Output
None
Errors
InvalidRequestException
DescribeAccountAuditConfiguration
Gets information about the Device Defender audit settings for this account. Settings include how audit
notifications are sent and which audit checks are enabled or disabled.
Synopsis
cli-input-json format
{
}
Output
{
"roleArn": "string",
"auditNotificationTargetConfigurations": {
"string": {
"targetArn": "string",
"roleArn": "string",
"enabled": "boolean"
}
},
510
AWS IoT Developer Guide
Manage Audit Settings
"auditCheckConfigurations": {
"string": {
"enabled": "boolean"
}
}
}
auditNotificationTargetConfigurations
map Information about the targets
to which audit notifications are
sent for this account.
Errors
ThrottlingException
DeleteAccountAuditConfiguration
Restores the default settings for Device Defender audits for this account. Any configuration data you
entered is deleted and all audit checks are reset to disabled.
Synopsis
511
AWS IoT Developer Guide
Schedule Audits
cli-input-json format
{
"deleteScheduledAudits": "boolean"
}
cli-input-json fields
Output
None
Errors
InvalidRequestException
Schedule Audits
Create one or more scheduled audits using CreateScheduledAudit. This command allows you to
specify the checks you want to perform during an audit and how often the audit should be run.
CreateScheduledAudit
Creates a scheduled audit that is run at a specified time interval.
Synopsis
512
AWS IoT Developer Guide
Schedule Audits
[--day-of-week <value>] \
--target-check-names <value> \
[--tags <value>] \
--scheduled-audit-name <value> \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"frequency": "string",
"dayOfMonth": "string",
"dayOfWeek": "string",
"targetCheckNames": [
"string"
],
"tags": [
{
"Key": "string",
"Value": "string"
}
],
"scheduledAuditName": "string"
}
cli-input-json fields
513
AWS IoT Developer Guide
Schedule Audits
Output
{
"scheduledAuditArn": "string"
}
Errors
InvalidRequestException
514
AWS IoT Developer Guide
Schedule Audits
ListScheduledAudits
Lists all of your scheduled audits.
Synopsis
cli-input-json format
{
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
Output
{
"scheduledAudits": [
{
"scheduledAuditName": "string",
"scheduledAuditArn": "string",
"frequency": "string",
"dayOfMonth": "string",
"dayOfWeek": "string"
}
],
"nextToken": "string"
}
member:
ScheduledAuditMetadata
515
AWS IoT Developer Guide
Schedule Audits
Errors
InvalidRequestException
DescribeScheduledAudit
Gets information about a scheduled audit.
Synopsis
cli-input-json format
516
AWS IoT Developer Guide
Schedule Audits
{
"scheduledAuditName": "string"
}
cli-input-json fields
Output
{
"frequency": "string",
"dayOfMonth": "string",
"dayOfWeek": "string",
"targetCheckNames": [
"string"
],
"scheduledAuditName": "string",
"scheduledAuditArn": "string"
}
517
AWS IoT Developer Guide
Schedule Audits
pattern: [a-zA-Z0-9_-]+
Errors
InvalidRequestException
UpdateScheduledAudit
Updates a scheduled audit, including what checks are performed and how often the audit takes place.
Synopsis
cli-input-json format
{
"frequency": "string",
"dayOfMonth": "string",
"dayOfWeek": "string",
518
AWS IoT Developer Guide
Schedule Audits
"targetCheckNames": [
"string"
],
"scheduledAuditName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
519
AWS IoT Developer Guide
Schedule Audits
Output
{
"scheduledAuditArn": "string"
}
Errors
InvalidRequestException
DeleteScheduledAudit
Deletes a scheduled audit.
Synopsis
cli-input-json format
{
"scheduledAuditName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
Output
520
AWS IoT Developer Guide
Run An On-Demand Audit
None
Errors
InvalidRequestException
StartOnDemandAuditTask
Starts an on-demand Device Defender audit.
Synopsis
cli-input-json format
{
"targetCheckNames": [
"string"
]
}
cli-input-json fields
521
AWS IoT Developer Guide
Manage Audit Instances
Output
{
"taskId": "string"
}
pattern: [a-zA-Z0-9-]+
Errors
InvalidRequestException
Use ListAuditTasks to find the audits that were run during a specific time interval.
DescribeAuditTask
Gets information about a Device Defender audit.
Synopsis
cli-input-json format
{
"taskId": "string"
522
AWS IoT Developer Guide
Manage Audit Instances
cli-input-json fields
pattern: [a-zA-Z0-9-]+
Output
{
"taskStatus": "string",
"taskType": "string",
"taskStartTime": "timestamp",
"taskStatistics": {
"totalChecks": "integer",
"inProgressChecks": "integer",
"waitingForDataCollectionChecks": "integer",
"compliantChecks": "integer",
"nonCompliantChecks": "integer",
"failedChecks": "integer",
"canceledChecks": "integer"
},
"scheduledAuditName": "string",
"auditDetails": {
"string": {
"checkRunStatus": "string",
"checkCompliant": "boolean",
"totalResourcesCount": "long",
"nonCompliantResourcesCount": "long",
"errorCode": "string",
"message": "string"
}
}
}
enum: IN_PROGRESS |
COMPLETED | FAILED |
CANCELED
enum:
ON_DEMAND_AUDIT_TASK |
SCHEDULED_AUDIT_TASK
523
AWS IoT Developer Guide
Manage Audit Instances
enum: IN_PROGRESS |
WAITING_FOR_DATA_COLLECTION
| CANCELED |
COMPLETED_COMPLIANT |
COMPLETED_NON_COMPLIANT
| FAILED
524
AWS IoT Developer Guide
Manage Audit Instances
Errors
InvalidRequestException
ListAuditTasks
Lists the Device Defender audits that have been performed during a given time period.
Synopsis
cli-input-json format
{
"startTime": "timestamp",
"endTime": "timestamp",
"taskType": "string",
"taskStatus": "string",
525
AWS IoT Developer Guide
Manage Audit Instances
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
enum:
ON_DEMAND_AUDIT_TASK |
SCHEDULED_AUDIT_TASK
enum: IN_PROGRESS |
COMPLETED | FAILED |
CANCELED
Output
{
"tasks": [
{
"taskId": "string",
"taskStatus": "string",
"taskType": "string"
}
],
"nextToken": "string"
}
526
AWS IoT Developer Guide
Manage Audit Instances
pattern: [a-zA-Z0-9-]+
enum: IN_PROGRESS |
COMPLETED | FAILED |
CANCELED
enum:
ON_DEMAND_AUDIT_TASK |
SCHEDULED_AUDIT_TASK
Errors
InvalidRequestException
CancelAuditTask
Cancels an audit that is in progress. The audit can be either scheduled or on-demand. If the audit is not
in progress, an "InvalidRequestException" occurs.
Synopsis
527
AWS IoT Developer Guide
Check Audit Results
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"taskId": "string"
}
cli-input-json fields
Output
None
Errors
ResourceNotFoundException
ListAuditFindings
Lists the findings (results) of a Device Defender audit or of the audits performed during a specified time
period. (Findings are retained for 180 days.)
Synopsis
528
AWS IoT Developer Guide
Check Audit Results
[--next-token <value>] \
[--start-time <value>] \
[--end-time <value>] \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"taskId": "string",
"checkName": "string",
"resourceIdentifier": {
"deviceCertificateId": "string",
"caCertificateId": "string",
"cognitoIdentityPoolId": "string",
"clientId": "string",
"policyVersionIdentifier": {
"policyName": "string",
"policyVersionId": "string"
},
"account": "string"
},
"maxResults": "integer",
"nextToken": "string",
"startTime": "timestamp",
"endTime": "timestamp"
}
cli-input-json fields
pattern: (0x)?[a-fA-F0-9]+
pattern: (0x)?[a-fA-F0-9]+
529
AWS IoT Developer Guide
Check Audit Results
pattern: [w+=,.@-]+
pattern: [0-9]+
Output
{
"findings": [
{
"taskId": "string",
"checkName": "string",
"taskStartTime": "timestamp",
"findingTime": "timestamp",
"severity": "string",
"nonCompliantResource": {
"resourceType": "string",
"resourceIdentifier": {
"deviceCertificateId": "string",
"caCertificateId": "string",
"cognitoIdentityPoolId": "string",
"clientId": "string",
"policyVersionIdentifier": {
"policyName": "string",
"policyVersionId": "string"
530
AWS IoT Developer Guide
Check Audit Results
},
"account": "string"
},
"additionalInfo": {
"string": "string"
}
},
"relatedResources": [
{
"resourceType": "string",
"resourceIdentifier": {
"deviceCertificateId": "string",
"caCertificateId": "string",
"cognitoIdentityPoolId": "string",
"clientId": "string",
"policyVersionIdentifier": {
"policyName": "string",
"policyVersionId": "string"
},
"account": "string"
},
"additionalInfo": {
"string": "string"
}
}
],
"reasonForNonCompliance": "string",
"reasonForNonComplianceCode": "string"
}
],
"nextToken": "string"
}
pattern: [a-zA-Z0-9-]+
531
AWS IoT Developer Guide
Check Audit Results
enum: DEVICE_CERTIFICATE |
CA_CERTIFICATE | IOT_POLICY
| COGNITO_IDENTITY_POOL
| CLIENT_ID |
ACCOUNT_SETTINGS
pattern: (0x)?[a-fA-F0-9]+
pattern: (0x)?[a-fA-F0-9]+
pattern: [w+=,.@-]+
pattern: [0-9]+
member: RelatedResource
532
AWS IoT Developer Guide
Check Audit Results
enum: DEVICE_CERTIFICATE |
CA_CERTIFICATE | IOT_POLICY
| COGNITO_IDENTITY_POOL
| CLIENT_ID |
ACCOUNT_SETTINGS
pattern: (0x)?[a-fA-F0-9]+
pattern: (0x)?[a-fA-F0-9]+
pattern: [w+=,.@-]+
pattern: [0-9]+
533
AWS IoT Developer Guide
Detect
Errors
InvalidRequestException
Detect
AWS IoT Device Defender Detect allows you to identify unusual behavior that may indicate a
compromised device by monitoring the behavior of your devices. Using a combination of cloud-side
metrics (from AWS IoT) and device-side metrics (from agents you install on your devices) you can detect
changes in connection patterns, devices that communicate to unauthorized or unrecognized endpoints,
and changes in inbound and outbound device traffic patterns. You create security profiles, which contain
definitions of expected device behaviors, and assign them to a group of devices or to all the devices in
your fleet. AWS IoT Device Defender Detect uses these security profiles to detect anomalies and send
alerts via Amazon CloudWatch metrics and Amazon SNS notifications.
AWS IoT Device Defender Detect is capable of detecting a variety of security issues frequently found in
connected devices:
• Traffic from a device to a known malicious IP address or to an unauthorized endpoint that indicates a
potential malicious command and control channel.
• Anomalous traffic, such as a spike in outbound traffic, that indicates a device is participating in a DDoS.
• Devices with remote management interfaces and ports that are remotely accessible.
• A spike in the rate of messages sent to your account— so that a rogue device does not end up costing
you in per-message charges.
Use cases:
You can use AWS IoT Device Defender Detect to measure the attack surface of your devices. For
example, you can identify devices with service ports which are often the target of attack campaigns
(telnet service running on ports 23/2323, SSH service running on port 22, HTTP/S services running
on ports 80/443/8080/8081). While these service ports might have legitimate reasons to be used on
the devices, they are also usually part of the attack surface for adversaries and carry associated risks.
After Detect alerts you to the attack surface, you can either decide to minimize it (by eliminating
unused network services) or run additional assessments to identify security weaknesses (for
example, telnet configured with common, default or weak passwords).
534
AWS IoT Developer Guide
Concepts
You can use AWS IoT Device Defender Detect to alert you to unexpected device behavioral metrics
(the number of open ports, number of connections, an unexpected open port, connections to
unexpected IP addresses) which might indicate a security breach. For example, a higher than
expected number of TCP connections may indicate a device is being used for a DDoS attack. A
process listening on a port other than the one you expect may indicate a backdoor installed on a
device for remote control. You can use Detect to probe the health of your device fleets and verify
your security assumptions (for example, no device is listening on port 23 or 2323).
Detect a mis-configured device
A spike in the number or size of messages sent from a device to your account might indicate a mis-
configured device. Such a device could increase your per-message charges. Similarly, a device with
many authorization failures could require a re-configured policy.
Concepts
metric
AWS IoT Device Defender Detect uses metrics to detect anomalous behavior. Detect compares the
reported value of a metric with the expected value you provide. These metrics can be taken from
two sources: (a) cloud-side metrics, and (b) device-side metrics:
(a) Abnormal behavior on the AWS IoT network is detected by using cloud-side metrics such as the
number of authorization failures, or the number or size of messages a device sends or receives via
AWS IoT.
(b) AWS IoT Device Defender Detect can also collect, aggregate, and monitor metrics data generated
by AWS IoT devices, for example, the ports a device is listening on, the number of bytes or packets
sent, or the device's TCP connections.
You can use AWS IoT Device Defender Detect with cloud-side metrics alone. To use device-side
metrics you must first deploy an agent on your AWS IoT connected devices or device gateways to
collect the metrics and send them to AWS IoT. See Sending Metrics from Devices (p. 550)
security profile
A security profile defines anomalous behaviors for a group of devices (a thing group) or for all
devices in your account, and specifies what actions to take when an anomaly is detected. You can
create a security profile and associate it with a group of devices using the console or with AWS IoT
API commands. AWS IoT Device Defender Detect starts recording security-related data and uses the
behaviors defined in the security profile to detect anomalies in the behavior of the devices.
behavior
A behavior tells AWS IoT Device Defender Detect how to recognize when a device is doing something
abnormal. Each behavior consists of a name, a metric, an operator, and a value or a statistical
threshold. For some metrics, a time period (durationSeconds) is also required. Any device action
that does not match a defined behavior statement triggers an alert.
alert
When an anomaly is detected, an alert notification can be sent via a CloudWatch metric (see AWS
IoT Metrics (p. 620)) or an SNS notification. An alert notification is also displayed in the AWS
IoT CDM console along with additional information about the alert, and a history of alerts for the
device. An alert is also sent when a monitored device stops exhibiting anomalous behavior or when it
had been causing an alert but stops reporting for an extended period.
535
AWS IoT Developer Guide
Behaviors
Behaviors
A security profile contains a set of behaviors. Each behavior contains a metric that specifies the
normal behavior for a group of devices or for all devices in your account (see Metrics (p. 537) and
CreateSecurityProfile (p. 556)).
The following describes some of the fields that are used in the definition of a behavior:
name
The name of the metric used. That is, what is measured by the behavior.
criteria
The criteria that determine if a device is behaving normally in regard to the metric.
comparisonOperator
The operator that relates the thing measured (metric) to the criteria (value or
statisticalThreshold).
The value to be compared with the metric. Depending on the type of metric, this should
contain a count (a value), cidrs (a list of CIDRs) or ports (a list of ports).
statisticalThreshold
The statistical threshold by which a behavior violation is determined. This field contains a
statistic field which has the following possible values: "p0", "p0.1", "p0.01", "p1", "p10",
"p50", "p90", "p99", "p99.9", "p99.99", or "p100".
This statistic indicates a percentile. It resolves to a value by which compliance with the
behavior is determined. Metrics are collected one or more times over the specified duration
(durationSeconds) from all reporting devices associated with this security profile, and
percentiles are calculated based on that data. After that, measurements are collected for a
device and accumulated over the same duration. If the resulting value for the device falls above
or below (comparisonOperator) the value associated with the percentile specified, then the
device is considered to be in compliance with the behavior, otherwise it is in violation of the
behavior.
A percentile indicates the percentage of all the measurements considered which fall below the
associated value. For example, if the value associated with "p90" (the 90th percentile) is 123,
then 90% of all measurements were below 123.
durationSeconds
Use this to specify the period of time over which the behavior is evaluated, for those
criteria which have a time dimension (for example, NUM_MESSAGES_SENT). For a
statisticalThreshhold metric comparison, this is the time period during which
measurements are collected for all devices to determine the statisticalThreshold values,
and then for each device to determine how its behavior ranks in comparison.
536
AWS IoT Developer Guide
Metrics
consecutiveDatapointsToAlarm
If a device is in violation of the behavior for the specified number of consecutive datapoints, an
alarm occurs. If not specified, the default is 1. (Note that this differs from the IoT console where
a value of 3 is presented by default, but can be overridden.)
consecutiveDatapointsToClear
If an alert has occurred and the offending device is no longer in violation of the behavior for the
specified number of consecutive datapoints, the alarm is cleared. If not specified, the default is
1. (Note that this differs from the IoT console where a value of 3 is presented by default, but can
be overridden.)
Metrics
aws:message-byte-size
Use this metric to specify the maximum or minimum size (in bytes) of each message transmitted
from a device to AWS IoT.
Source: cloud-side
Units: bytes
Example:
{
"name": "Max Message Size",
"metric": "aws:message-byte-size",
"criteria": {
"comparisonOperator": "less-than",
"value": {
"count": 1024
},
"consecutiveDatapointsToAlarm": 3,
"consecutiveDatapointsToClear": 3
}
}
{
"name": "Large Message Size",
"metric": "aws:message-byte-size",
"criteria": {
"comparisonOperator": "less-than",
"statisticalThreshold": {
"statistic": "p90"
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 3,
"consecutiveDatapointsToClear": 3
}
537
AWS IoT Developer Guide
Metrics
An alarm occurs for a device if, during three consecutive 5 minute periods, it transmits messages
whose cumulative size is more than that measured for 90 percent of all other devices reporting for
this security profile behavior.
aws:num-messages-received / aws:num-messages-sent
The number of messages received or sent by a device during a given time period.
more info (2)
Use this metric to specify the maximum or minimum number of messages that may be sent or
received between AWS IoT and each device in a given period of time.
Source: cloud-side
Units: messages
Duration: a non-negative integer, valid values are 300, 600, 900, 1800 or 3600 seconds
Example:
{
"name": "Out bound message count",
"metric": "aws:num-messages-sent",
"criteria": {
"comparisonOperator": "less-than",
"value": {
"count": 50
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 2,
"consecutiveDatapointsToClear": 2
}
}
{
"name": "Out bound message rate",
"metric": "aws:num-messages-sent",
"criteria": {
"comparisonOperator": "less-than",
"statisticalThreshold": {
"statistic": "p99"
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 2,
"consecutiveDatapointsToClear": 2
}
}
538
AWS IoT Developer Guide
Metrics
aws:all-bytes-out
The number of outbound bytes from a device during a given time period.
more info (3)
Use this metric to specify the maximum or minimum amount of out-bound traffic that a device
should send, measured in bytes in a given period of time.
Source: device-side
Units: bytes
Duration: a non-negative integer, valid values are 300, 600, 900, 1800 or 3600 seconds
Example:
{
"name": "TCP outbound traffic",
"metric": "aws:all-bytes-out",
"criteria": {
"comparisonOperator": "less-than",
"value": {
"count": 4096
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 5,
"consecutiveDatapointsToClear": 4
}
}
{
"name": "TCP outbound traffic",
"metric": "aws:all-bytes-out",
"criteria": {
"comparisonOperator": "less-than",
"statisticalThreshold": {
"statistic": "p50"
},
"durationSeconds": 900,
"consecutiveDatapointsToAlarm": 5,
"consecutiveDatapointsToClear": 4
}
}
aws:all-bytes-in
Use this metric to specify the maximum or minimum amount of in-bound traffic that a device should
receive, measured in bytes in a given period of time.
539
AWS IoT Developer Guide
Metrics
Source: device-side
Units: bytes
Duration: a non-negative integer, valid values are 300, 600, 900, 1800 or 3600 seconds
Example:
{
"name": "TCP inbound traffic",
"metric": "aws:all-bytes-in",
"criteria": {
"comparisonOperator": "less-than",
"value": {
"count": 4096
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 1,
"consecutiveDatapointsToClear": 3
}
}
{
"name": "TCP inbound traffic",
"metric": "aws:all-bytes-in",
"criteria": {
"comparisonOperator": "less-than",
"statisticalThreshold": {
"statistic": "p90"
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 1,
"consecutiveDatapointsToClear": 3
}
}
aws:all-packets-out
The number of outbound packets from a device during a given time period.
more info (5)
Use this metric to specify the maximum or minimum amount of total outbound traffic that a device
should send in a given period of time.
Source: device-side
Units: packets
540
AWS IoT Developer Guide
Metrics
Duration: a non-negative integer, valid values are 300, 600, 900, 1800 or 3600 seconds
Example:
{
"name": "TCP outbound traffic",
"metric": "aws:all-packets-out",
"criteria": {
"comparisonOperator": "less-than",
"value": {
"count": 100
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 1,
"consecutiveDatapointsToClear": 3
}
}
{
"name": "TCP outbound traffic",
"metric": "aws:all-packets-out",
"criteria": {
"comparisonOperator": "less-than",
"statisticalThreshold": {
"statistic": "p90"
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 1,
"consecutiveDatapointsToClear": 3
}
}
aws:all-packets-in
Use this metric to specify the maximum or minimum amount of total inbound traffic that a device
should receive in a given period of time.
Source: device-side
Units: packets
Duration: a non-negative integer, valid values are 300, 600, 900, 1800 or 3600 seconds
Example:
{
"name": "TCP inbound traffic",
"metric": "aws:all-packets-in",
541
AWS IoT Developer Guide
Metrics
"criteria": {
"comparisonOperator": "less-than",
"value": {
"count": 100
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 2,
"consecutiveDatapointsToClear": 1
}
}
{
"name": "TCP inbound traffic",
"metric": "aws:all-packets-in",
"criteria": {
"comparisonOperator": "less-than",
"statisticalThreshold": {
"statistic": "p90"
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 2,
"consecutiveDatapointsToClear": 1
}
}
aws:num-authorization-failures
Use this metric to specify the maximum number of authorization failures allowed for each device in
a given period of time. An authorization failure occurs when a request from a device to AWS IoT is
denied, for example, if a device attempts to publish to a topic for which it does not have sufficient
permissions.
Source: cloud-side
Unit: failures
Units: failures
Duration: a non-negative integer, valid values are 300, 600, 900, 1800 or 3600 seconds
Example:
{
"name": "Authorization Failures",
"metric": "aws:num-authorization-failures",
"criteria": {
"comparisonOperator": "less-than",
"value": {
"count": 5
542
AWS IoT Developer Guide
Metrics
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 2,
"consecutiveDatapointsToClear": 1
}
}
{
"name": "Authorization Failures",
"metric": "aws:num-authorization-failures",
"criteria": {
"comparisonOperator": "less-than",
"statisticalThreshold": {
"statistic": "p50"
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 2,
"consecutiveDatapointsToClear": 1
}
}
aws:source-ip-address
Use this metric to specify a set of whitelisted or blacklisted CIDRs from which each device must or
must not connect to AWS IoT.
Source: cloud-side
Units: n/a
Example:
{
"name": "Blacklisted source IPs",
"metric": "aws:source-ip-address",
"criteria": {
"comparisonOperator": "not-in-cidr-set",
"value": {
"cidrs": [ "12.8.0.0/16", "15.102.16.0/24" ]
}
}
}
aws:destination-ip-addresses
A set of IP destinations.
543
AWS IoT Developer Guide
Metrics
Use this metric to specify a set of whitelisted or blacklisted CIDRs that each device must or must not
communicate with.
Source: device-side
Units: n/a
Example:
{
"name": "Blacklisted destination IPs",
"metric": "aws:destination-ip-addresses",
"criteria": {
"comparisonOperator": "not-in-cidr-set",
"value": {
"cidrs": [ "12.8.0.0/16", "15.102.16.0/24" ]
}
}
}
aws:listening-tcp-ports / aws:listening-udp-ports
Use this metric to specify a set of whitelisted or blacklisted TCP/UDP ports that each device must or
must not listen on.
Source: device-side
Units: n/a
Example:
{
"name": "Listening TCP Ports",
"metric": "aws:listening-tcp-ports",
"criteria": {
"comparisonOperator": "in-port-set",
"value": {
"ports": [ 443, 80 ]
}
}
}
544
AWS IoT Developer Guide
Metrics
aws:num-listening-tcp-ports / aws:num-listening-udp-ports
Use this metric to specify the maximum or minimum number of TCP or UDP ports that each device
should listen on.
Source: device-side
Units: ports
Example:
{
"name": "Max TCP Ports",
"metric": "aws:num-listening-tcp-ports",
"criteria": {
"comparisonOperator": "less-than-equals",
"value": {
"count": 4
},
"consecutiveDatapointsToAlarm": 2,
"consecutiveDatapointsToClear": 1
}
}
{
"name": "Max TCP Ports",
"metric": "aws:num-listening-tcp-ports",
"criteria": {
"comparisonOperator": "less-than-equals",
"statisticalThreshold": {
"statistic": "p90"
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 2,
"consecutiveDatapointsToClear": 1
}
}
aws:num-established-tcp-connections
Use this metric to specify the maximum or minimum number of active TCP connections that each
device should have. (All TCP states)
Source: device-side
545
AWS IoT Developer Guide
Metrics
Units: connections
Example:
{
"name": "TCP Connection Count",
"metric": "aws:num-established-tcp-connections",
"criteria": {
"comparisonOperator": "less-than",
"value": {
"count": 3
},
"consecutiveDatapointsToAlarm": 3,
"consecutiveDatapointsToClear": 3
}
}
{
"name": "TCP Connection Count",
"metric": "aws:num-established-tcp-connections",
"criteria": {
"comparisonOperator": "less-than",
"statisticalThreshold": {
"statistic": "p90"
},
"durationSeconds": 900,
"consecutiveDatapointsToAlarm": 3,
"consecutiveDatapointsToClear": 3
}
}
aws:num-connection-attempts
The number of times a device has attempted to make a connection in a given time period.
more info (13)
Use this metric to specify the maximum or minimum number of connection attempts for each
device. Both successful and unsuccessful attempts are counted.
Source: cloud-side
Duration: a non-negative integer, valid values are 300, 600, 900, 1800 or 3600 seconds
Example:
{
"name": "Connection Attempts",
"metric": "aws:num-connection-attempts",
"criteria": {
546
AWS IoT Developer Guide
Metrics
"comparisonOperator": "greater-than",
"value": {
"count": 5
},
"durationSeconds": 600,
"consecutiveDatapointsToAlarm": 1,
"consecutiveDatapointsToClear": 2
}
}
{
"name": "Connection Attempts",
"metric": "aws:num-connection-attempts",
"criteria": {
"comparisonOperator": "greater-than",
"statisticalThreshold": {
"statistic": "p10"
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 1,
"consecutiveDatapointsToClear": 2
}
}
aws:num-disconnects
The number of times a device has disconnected from AWS IoT during a given time period.
more info (14)
Use this metric to specify the maximum or minimum number of times a device has disconnected
from AWS IoT during a given time period.
Source: cloud-side
Units: disconnects
Duration: a non-negative integer, valid values are 300, 600, 900, 1800 or 3600 seconds
Example:
{
"name": "Disconnections",
"metric": "aws:num-disconnects",
"criteria": {
"comparisonOperator": "greater-than",
"value": {
"count": 5
},
"durationSeconds": 600,
"consecutiveDatapointsToAlarm": 1,
"consecutiveDatapointsToClear": 2
}
}
547
AWS IoT Developer Guide
How To Use AWS IoT Device Defender Detect
{
"name": "Disconnections",
"metric": "aws:num-disconnects",
"criteria": {
"comparisonOperator": "greater-than",
"statisticalThreshold": {
"statistic": "p10"
},
"durationSeconds": 300,
"consecutiveDatapointsToAlarm": 1,
"consecutiveDatapointsToClear": 2
}
}
To attach a security profile to a group of devices, you must specify the ARN of the thing group which
contains them. A thing group ARN has the following format:
arn:aws:iot:<region>:<accountid>:thinggroup/<thing-group-name>
To attach a security profile to all of the devices in an account, you must specify an ARN with the
following format:
arn:aws:iot:<region>:<accountid>:all/things
6. You can also keep track of violations with ListActiveViolations (p. 568) which allows you to see
what violations have been detected for a given security profile or target device.
Use ListViolationEvents (p. 577) to see what violations have been detected during a specified time
period. You can filter these results by a given security profile or device.
548
AWS IoT Developer Guide
Permissions
7. If your devices violate the behaviors you have defined too often, or not often enough, you will want
to fine-tune the behavior definitions.
8. To review the security profiles you have set up and the devices that are being monitored,
use ListSecurityProfiles (p. 573), ListSecurityProfilesForTarget (p. 574), and
ListTargetsForSecurityProfile (p. 576).
You can get more details about a particular security profile with DescribeSecurityProfile (p. 562).
9. To make changes to a security profile, use UpdateSecurityProfile (p. 583). You may detach a
security profile from an account or target thing group using DetachSecurityProfile (p. 567) or
delete a security profile entirely with DeleteSecurityProfile (p. 561).
Permissions
This section contains information on how to set up the AWS IAM roles and policies required to manage
AWS IoT Device Defender Detect. For more information on AWS IAM, see the AWS Identity and Access
Management User Guide.
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"sns:Publish"
],
"Resource":[
"arn:aws:sns:region:account-id:your-topic-name"
]
}
]
}
trust policy
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "iot.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
549
AWS IoT Developer Guide
Service Limits
You also need an IAM permissions policy attached to the IAM user that allows the user to pass roles. See
Granting a User Permissions to Pass a Role to an AWS Service.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Action": [
"iam:GetRole",
"iam:PassRole"
],
"Resource": "arn:aws:iam::>account-id<:role/Role_To_Pass"
}
]
}
Service Limits
• The maximum number of security profiles per target (thing group or user account) is 5.
• The maximum number of behaviors per security profile is 100.
• The maximum number of value elements (counts, IP addresses, ports) per security profile is 1000.
• Device metric reporting may be throttled to one metric report per 5 minutes per device. So limit your
device reporting to one metric report every 5 minutes to avoid throttling.
• AWS IoT Device Defender Detect violations are stored for 90 days after they have been generated.
You must securely deploy an agent on your AWS IoT connected devices or device gateways to collect
device-side metrics. AWS IoT Device Defender provides sample agents to use as examples when creating
your own. If you are unable to provide device metrics, you can still get limited functionality based on
cloud-side metrics.
$aws/things/THING_NAME/Defender/metrics/json
550
AWS IoT Developer Guide
Sending Metrics from Devices
or
$aws/things/THING_NAME/Defender/metrics/cbor
Device Defender will reply with the receipt status of your metrics reports using one of these topics:
$aws/things/THING_NAME/Defender/metrics/json/accepted
$aws/things/THING_NAME/Defender/metrics/cbor/accepted
$aws/things/THING_NAME/Defender/metrics/json/rejected
$aws/things/THING_NAME/Defender/metrics/cbor/rejected
Header Block:
551
AWS IoT Developer Guide
Sending Metrics from Devices
Metrics Block:
TCP Connections:
tcp_connections
tc metrics N Object
established_connections
ec tcp_connections
N List<Connection>
ESTABLISHED
TCP State
connections cs established_connections
N List<Object>
total t established_connections
N Number >= 0 Number of
established
connections
listening_tcp_ports
tp metrics N Object
total t listening_tcp_ports
N Number >= 0
listening_udp_ports
up metrics N Object
552
AWS IoT Developer Guide
Sending Metrics from Devices
total t listening_udp_ports
N Number >= 0
Network Stats:
{
"header": {
"report_id": 1530304554,
"version": "1.0"
},
"metrics": {
"listening_tcp_ports": {
"ports": [
{
"interface": "eth0",
"port": 24800
},
{
"interface": "eth0",
"port": 22
},
{
"interface": "eth0",
"port": 53
}
],
"total": 3
},
"listening_udp_ports": {
"ports": [
553
AWS IoT Developer Guide
Sending Metrics from Devices
{
"interface": "eth0",
"port": 5353
},
{
"interface": "eth0",
"port": 67
}
],
"total": 2
},
"network_stats": {
"bytes_in": 29358693495,
"bytes_out": 26485035,
"packets_in": 10013573555,
"packets_out": 11382615
},
"tcp_connections": {
"established_connections": {
"connections": [
{
"local_interface": "eth0",
"local_port": 80,
"remote_addr": "192.168.0.1:8000"
},
{
"local_interface": "eth0",
"local_port": 80,
"remote_addr": "192.168.0.1:8000"
}
],
"total": 2
}
}
}
}
{
"hed": {
"rid": 1530305228,
"v": "1.0"
},
"met": {
"tp": {
"pts": [
{
"if": "eth0",
"pt": 24800
},
{
"if": "eth0",
"pt": 22
},
{
"if": "eth0",
"pt": 53
}
],
"t": 3
},
"up": {
"pts": [
{
554
AWS IoT Developer Guide
Detect Commands
"if": "eth0",
"pt": 5353
},
{
"if": "eth0",
"pt": 67
}
],
"t": 2
},
"ns": {
"bi": 29359307173,
"bo": 26490711,
"pi": 10014614051,
"po": 11387620
},
"tc": {
"ec" : {
"cs": [
{
"li": "eth0",
"lp": 80,
"rad": "192.168.0.1:8000"
},
{
"li": "eth0",
"lp": 80,
"rad": "192.168.0.1:8000"
}
],
"t": 2
}
}
}
}
Detect Commands
AttachSecurityProfile
Associates a Device Defender security profile with a thing group or with this account. Each thing group or
account can have up to five security profiles associated with it.
Synopsis:
cli-input-json format:
{
"securityProfileName": "string",
"securityProfileTargetArn": "string"
}
555
AWS IoT Developer Guide
CreateSecurityProfile
cli-input-json fields:
pattern: [a-zA-Z0-9:_-]+
Output:
None
Errors:
InvalidRequestException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
CreateSecurityProfile
Creates a Device Defender security profile.
Synopsis:
cli-input-json format:
556
AWS IoT Developer Guide
CreateSecurityProfile
{
"securityProfileName": "string",
"securityProfileDescription": "string",
"behaviors": [
{
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
}
],
"alertTargets": {
"string": {
"alertTargetArn": "string",
"roleArn": "string"
}
},
"additionalMetricsToRetain": [
"string"
],
"tags": [
{
"Key": "string",
"Value": "string"
}
]
}
cli-input-json fields:
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
557
AWS IoT Developer Guide
CreateSecurityProfile
pattern: [a-zA-Z0-9:_-]+
558
AWS IoT Developer Guide
CreateSecurityProfile
559
AWS IoT Developer Guide
CreateSecurityProfile
Output:
{
"securityProfileName": "string",
560
AWS IoT Developer Guide
DeleteSecurityProfile
"securityProfileArn": "string"
}
pattern: [a-zA-Z0-9:_-]+
Errors:
InvalidRequestException
DeleteSecurityProfile
Deletes a Device Defender security profile.
Synopsis:
cli-input-json format:
{
"securityProfileName": "string",
"expectedVersion": "long"
}
cli-input-json fields:
561
AWS IoT Developer Guide
DescribeSecurityProfile
Output:
None
Errors:
InvalidRequestException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
DescribeSecurityProfile
Gets information about a Device Defender security profile.
Synopsis:
cli-input-json format:
{
"securityProfileName": "string"
}
cli-input-json fields:
562
AWS IoT Developer Guide
DescribeSecurityProfile
Output:
{
"securityProfileName": "string",
"securityProfileArn": "string",
"securityProfileDescription": "string",
"behaviors": [
{
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
}
],
"alertTargets": {
"string": {
"alertTargetArn": "string",
"roleArn": "string"
}
},
"additionalMetricsToRetain": [
"string"
],
"version": "long",
"creationDate": "timestamp",
"lastModifiedDate": "timestamp"
}
pattern: [a-zA-Z0-9:_-]+
563
AWS IoT Developer Guide
DescribeSecurityProfile
pattern: [a-zA-Z0-9:_-]+
564
AWS IoT Developer Guide
DescribeSecurityProfile
565
AWS IoT Developer Guide
DescribeSecurityProfile
Errors:
InvalidRequestException
566
AWS IoT Developer Guide
DetachSecurityProfile
ResourceNotFoundException
DetachSecurityProfile
Disassociates a Device Defender security profile from a thing group or from this account.
Synopsis:
cli-input-json format:
{
"securityProfileName": "string",
"securityProfileTargetArn": "string"
}
cli-input-json fields:
pattern: [a-zA-Z0-9:_-]+
Output:
None
Errors:
InvalidRequestException
567
AWS IoT Developer Guide
ListActiveViolations
ThrottlingException
ListActiveViolations
Lists the active violations for a given Device Defender security profile.
Synopsis:
cli-input-json format:
{
"thingName": "string",
"securityProfileName": "string",
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields:
pattern: [a-zA-Z0-9:_-]+
Output:
{
"activeViolations": [
{
568
AWS IoT Developer Guide
ListActiveViolations
"violationId": "string",
"thingName": "string",
"securityProfileName": "string",
"behavior": {
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
},
"lastViolationValue": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"lastViolationTime": "timestamp",
"violationStartTime": "timestamp"
}
],
"nextToken": "string"
}
member: ActiveViolation
pattern: [a-zA-Z0-9-]+
569
AWS IoT Developer Guide
ListActiveViolations
pattern: [a-zA-Z0-9:_-]+
570
AWS IoT Developer Guide
ListActiveViolations
571
AWS IoT Developer Guide
ListActiveViolations
Errors:
InvalidRequestException
572
AWS IoT Developer Guide
ListSecurityProfiles
ResourceNotFoundException
ListSecurityProfiles
Lists the Device Defender security profiles you have created. You can use filters to list only those security
profiles associated with a thing group or only those associated with your account.
Synopsis:
cli-input-json format:
{
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields:
Output:
{
"securityProfileIdentifiers": [
{
"name": "string",
"arn": "string"
}
],
"nextToken": "string"
}
573
AWS IoT Developer Guide
ListSecurityProfilesForTarget
pattern: [a-zA-Z0-9:_-]+
Errors:
InvalidRequestException
ListSecurityProfilesForTarget
Lists the Device Defender security profiles attached to a target (thing group).
Synopsis:
cli-input-json format:
{
"nextToken": "string",
"maxResults": "integer",
"recursive": "boolean",
"securityProfileTargetArn": "string"
}
574
AWS IoT Developer Guide
ListSecurityProfilesForTarget
cli-input-json fields:
Output:
{
"securityProfileTargetMappings": [
{
"securityProfileIdentifier": {
"name": "string",
"arn": "string"
},
"target": {
"arn": "string"
}
}
],
"nextToken": "string"
}
pattern: [a-zA-Z0-9:_-]+
575
AWS IoT Developer Guide
ListTargetsForSecurityProfile
Errors:
InvalidRequestException
ListTargetsForSecurityProfile
Lists the targets (thing groups) associated with a given Device Defender security profile.
Synopsis:
cli-input-json format:
{
"securityProfileName": "string",
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields:
Name Type Description
pattern: [a-zA-Z0-9:_-]+
576
AWS IoT Developer Guide
ListViolationEvents
Output:
{
"securityProfileTargets": [
{
"arn": "string"
}
],
"nextToken": "string"
}
Errors:
InvalidRequestException
ListViolationEvents
Lists the Device Defender security profile violations discovered during the given time period. You can use
filters to limit the results to those alerts issued for a particular security profile, behavior or thing (device).
Synopsis:
577
AWS IoT Developer Guide
ListViolationEvents
cli-input-json format:
{
"startTime": "timestamp",
"endTime": "timestamp",
"thingName": "string",
"securityProfileName": "string",
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields:
Output:
{
"violationEvents": [
{
"violationId": "string",
"thingName": "string",
"securityProfileName": "string",
"behavior": {
578
AWS IoT Developer Guide
ListViolationEvents
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
},
"metricValue": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"violationEventType": "string",
"violationEventTime": "timestamp"
}
],
"nextToken": "string"
}
pattern: [a-zA-Z0-9-]+
579
AWS IoT Developer Guide
ListViolationEvents
pattern: [a-zA-Z0-9:_-]+
580
AWS IoT Developer Guide
ListViolationEvents
581
AWS IoT Developer Guide
ListViolationEvents
Errors:
582
AWS IoT Developer Guide
UpdateSecurityProfile
InvalidRequestException
UpdateSecurityProfile
Updates a Device Defender security profile.
Synopsis:
cli-input-json format:
{
"securityProfileName": "string",
"securityProfileDescription": "string",
"behaviors": [
{
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
}
],
"alertTargets": {
"string": {
"alertTargetArn": "string",
583
AWS IoT Developer Guide
UpdateSecurityProfile
"roleArn": "string"
}
},
"additionalMetricsToRetain": [
"string"
],
"deleteBehaviors": "boolean",
"deleteAlertTargets": "boolean",
"deleteAdditionalMetricsToRetain": "boolean",
"expectedVersion": "long"
}
cli-input-json fields:
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
pattern: [a-zA-Z0-9:_-]+
584
AWS IoT Developer Guide
UpdateSecurityProfile
585
AWS IoT Developer Guide
UpdateSecurityProfile
586
AWS IoT Developer Guide
UpdateSecurityProfile
Output:
{
"securityProfileName": "string",
"securityProfileArn": "string",
"securityProfileDescription": "string",
"behaviors": [
{
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
}
],
"alertTargets": {
"string": {
"alertTargetArn": "string",
"roleArn": "string"
}
},
"additionalMetricsToRetain": [
"string"
],
"version": "long",
"creationDate": "timestamp",
"lastModifiedDate": "timestamp"
587
AWS IoT Developer Guide
UpdateSecurityProfile
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
pattern: [a-zA-Z0-9:_-]+
588
AWS IoT Developer Guide
UpdateSecurityProfile
589
AWS IoT Developer Guide
UpdateSecurityProfile
Errors:
InvalidRequestException
590
AWS IoT Developer Guide
ValidateSecurityProfileBehaviors
VersionConflictException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
ValidateSecurityProfileBehaviors
Validates a Device Defender security profile behaviors specification.
Synopsis:
cli-input-json format:
{
"behaviors": [
{
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
}
]
}
cli-input-json fields:
591
AWS IoT Developer Guide
ValidateSecurityProfileBehaviors
pattern: [a-zA-Z0-9:_-]+
592
AWS IoT Developer Guide
ValidateSecurityProfileBehaviors
593
AWS IoT Developer Guide
ValidateSecurityProfileBehaviors
Output:
{
"valid": "boolean",
"validationErrors": [
{
"errorMessage": "string"
}
]
}
Errors:
InvalidRequestException
594
AWS IoT Developer Guide
Device Agent Integration with AWS IoT Greengrass
InternalFailureException
Prerequisites:
In general, the process described here follows the Create and Package a Lambda Function section of the
AWS IoT Greengrass Developers Guide.
3. Install the AWS IoT Device Defender sample agent in the virtual environment Install from PyPi.
cd aws-iot-device-defender-agent-sdk-python
#This must be run from the same directory as setup.py
pip install .
5. Create an empty directory to assemble your Lambda function, we will refer to this as your “Lambda
directory”.
mkdir metrics_lambda
cd metrics_lambda
6. Complete steps 1-4 from this section: Create and Package a Lambda Function.
7. Unzip the AWS IoT Greengrass python sdk into your Lambda directory.
unzip ../aws_greengrass_core_sdk/sdk/python_sdk_1_1_0.zip
cp -R ../aws_greengrass_core_sdk/examples/HelloWorld/greengrass_common .
cp -R ../aws_greengrass_core_sdk/examples/HelloWorld/greengrasssdk .
595
AWS IoT Developer Guide
Device Agent Integration with AWS IoT Greengrass
cp -R ../aws_greengrass_core_sdk/examples/HelloWorld/greengrass_ipc_python_sdk .
8. Copy the AWSIoTDeviceDefenderAgentSDK module to the root level of your Lambda directory.
cp -R ../aws-iot-device-defender-agent-sdk-python/AWSIoTDeviceDefenderAgentSDK .
9. Copy the AWS IoT Greengrass agent to the root level of your Lambda directory.
cp ../aws-iot-device-defender-agent-sdk-python/samples/greengrass/
greengrass_core_metrics_agent/greengrass_defender_agent.py .
10. Customize the AWS IoT Greengrass agent to include the name of your AWS IoT Greengrass Core
device, and the desired metrics sample rate:
• Replace GREENGRASS_CORENAME with the name of your AWS IoT Greengrass Core.
• Set the SAMPLE_RATE_SECONDS to your desired metrics reporting interval. (Note: 5 minutes (300
seconds) is the shortest reporting interval supported by AWS IoT Device Defender.)
11. Copy the dependencies from your virtual environment (or your system) into the the root level of
your Lambda directory.
cp -R ../metrics_lambda_environment/lib/python2.7/site-packages/psutil .
cp -R ../metrics_lambda_environment/lib/python2.7/site-packages/cbor .
12. Create your Lambda function zipfile. (Note: you should perform this command in the root level of
your Lambda directory.)
rm *.zip
zip -r greengrass_defender_metrics_lambda.zip *
Review your AWS IoT Device Defender device metrics using the AWS IoT Console
1. Temporarily modify the publish topic in your AWS IoT Greengrass Lambda function to "metrics/test".
596
AWS IoT Developer Guide
Security Best Practices for Device Agents
The agent process should granted only the minimum permissions necessary to perform its duties.
Basic Mechanisms
• Agent should be run as non-root user.
• Agent should run as a dedicated user, in its own group.
• User/groups should be granted Read-Only permissions on the resources required to gather and
transmit metrics.
• Example: read-only on /proc /sys for the sample agent.
• For an example of how to setup a process to run with reduced permissions, see the Setup
Instructions which are included with the Python Sample Agent.
There are a number of well-known Linux mechanisms that can help you further restrict/isolate your
agent process:
Advanced Mechanisms
• CGroups
• SELinux
• Chroot
• Linux Namespaces
Operational Resiliency
An agent process must be resilient to unexpected operational errors and exceptions and must not
crash or exit permanently. The code needs to gracefully handle exceptions and, as a precaution, it
must be configured to automatically restart in case of unexpected termination (for example, due to
system restarts or uncaught exceptions).
Least Dependencies
An agent must use the least possible number of dependencies (i.e. third-party libraries) in its
implementation. If use of a library is justified due to the complexity of a task (for example,
transport layer security) only use well-maintained dependencies and establish a mechanism to keep
dependencies up to date. If the added dependencies contain functionality not used by the agent
and active by default (for example, opening ports, domain sockets), disable them in your code or by
means of the library's configuration files.
Process Isolation
An agent process must only contain functionality required for performing device metric gathering
and transmission. It must not piggyback on other system processes as a container or implement
functionality for other out of scope use-cases. Additionally, the agent process must refrain from
creating inbound communication channels such as domain socket and network service ports which
would allow local or remote processes to interfere with its operation and impact its integrity and
isolation.
597
AWS IoT Developer Guide
AWS IoT Device Defender Troubleshooting Guide
Stealthiness
An agent process must not be named with keywords such as security, monitoring, or audit indicating
its purpose and security value. Generic code names or random and unique-per-device process names
must be preferred. The same principle must be followed in naming the directory in which the agent's
binaries reside and any names and values of process arguments.
Least Information Shared
Any agent artifacts deployed to devices must not contain sensitive information such as privileged
credentials, debugging and dead code, or inline comments or documentation files which reveal
details about server-side processing of agent-gathered metrics or other details about backend
systems.
Transport Layer Security
To establish TLS secure channels for data transmission, an agent process must enforce all client-
side validations, such as certificate chain and domain name validation, at the application level, if not
enabled by default. Furthermore, an agent must use a root certificate store which contains trusted
authorities and does not contain certificates belonging to compromised certificate issuers.
Secure Deployment
Any agent deployment mechanism, such as code push or sync and repositories containing its
binaries, source code and any configuration files (including trusted root certificates), must be access
controlled to prevent unauthorized code injection or tampering. If the deployment mechanism relies
on network communication, then cryptographic methods must be utilized to protect the integrity of
deployment artifacts in transit.
Further Reading
• Security and Identity for AWS IoT
• Understanding the AWS IoT Security Model
• Redhat: A Bite of Python
• 10 common security gotchas in Python and how to avoid them
• What Is Least Privilege & Why Do You Need It?
• OWASP Embedded Security Top 10
• OWASP IoT Project
A: You can use the AWS IoT Device Defender Detect feature for devices that are registered as things
with AWS IoT. To use the cloud-side metrics, devices must connect using the thing name as their
client Id.
Audit
Q: I enabled a check and my audit has been showing "In-Progress" for a long time. Is something wrong?
When will I get results?
A: When a check is enabled, data collection begins immediately. However, if you have a large amount
of data in your account to be collected (certificates, things, policies, etc.) then the results of the
check may not be available for some time after you have enabled it.
598
AWS IoT Developer Guide
AWS IoT Device Defender Troubleshooting Guide
Detect
Q: How do I know what thresholds should be set in an AWS IoT Device Defender security profile
behavior?
A: Start by creating a security profile behavior with low thresholds and attach it to a thing group
consisting of a representative set of devices. Device defender will alert you with the metric
datapoints emitted by the device for the behaviors that are violated. You can then fine-tune the
device behavior thresholds to match your use case.
Q: I created a behavior, but it is not triggering a violation when I expect it to. How should I fix it?
A: Keep in mind that when you define a behavior you are indicating how you expect your device to
behave normally. For example, if you have a security camera that only connects to one central server
on TCP port 8888, you don’t expect it to make any other connections. To be alerted if the camera
makes a connection on another port, you could define a behavior such as:
{
"name": "Listening TCP Ports",
"metric": "aws:listening-tcp-ports",
"criteria": {
"comparisonOperator": "in-port-set",
"value": {
"ports": [ 8888 ]
}
}
}
Once the behavior has been created, if the camera makes a TCP connection on TCP Port 443, the
device behavior would be violated and would trigger an alert.
Q: One or more of my behaviors are in violation. How do I clear the violation?
A: Alarms will clear once the device returns to expected behavior, as defined by the behavior profiles
you have defined. Behavior profiles are evaluated upon receipt of metrics data for your device.
Q: I deleted a behavior that was in violation, how do I stop the alerts?
A: Deleting a behavior will stop all future violations and alerts for that behavior. Prior alerts will
need to be drained from your notification mechanism as normal. However, when a behavior is
deleted, the record of violations of that behavior will be retained for the same time period as all
other violations in your account.
Device Metrics
Q: I’m submitting metrics reports that I know violate my behaviors, but no violations are being triggered.
What's wrong?
A: Check that your metrics reports are being accepted by subscribing to the following MQTT topics:
$aws/things/THING_NAME/defender/metrics/FORMAT/rejected
$aws/things/THING_NAME/defender/metrics/FORMAT/accepted
where “THING_NAME” is the name of the thing reporting the metric and FORMAT is either “json” or
“cbor” depending on the format of the metrics report the thing submits.
After you have subscribed, you should receive messages on these topics for each metric report
submitted. A "rejected" message indicates that there was a problem parsing the metric report. An
error message is included in the message payload to help you correct any errors in your metric
report. An "accepted" message indicates the metric report was parsed properly.
599
AWS IoT Developer Guide
AWS IoT Device Defender Troubleshooting Guide
A: An empty list of ports or IP addresses is always considered in conformity with the corresponding
behavior. If the corresponding behavior was in violation, then the violation will be cleared.
Q: My device metric reports are getting rejected with an error message of "XXXX Not a Thing". How can I
fix it?
A: Make sure you are submitting metrics for a thing which is registered in your AWS IoT account.
AWS IoT Device Defender requires things to be registered in your account to evaluate reported
metrics against defined behaviors.
If you are submitting metrics from a registered thing, verify that you are sending a well-
formed metrics report using one of the supported formats. (Device Metrics Document
Specification (p. 551))
Q: What value should I supply in the report id field in my device metrics report?
A: This should be a unique value for each metric report, expressed as a positive integer. A common
practice is to use a Unix epoch timestamp.
Q: Should I create a dedicated MQTT connection for AWS IoT Device Defender metrics?
You should use a registered thing name as the clientId when connecting to AWS IoT.
Q: Can I publish metrics for a device with a different clientId?
It is possible to publish metrics on behalf of another thing, as long as that thing is registered in your
AWS account. This can be accomplished by publishing the metrics to the AWS IoT Device Defender
reserved topic for that device. For example, "Thing-1" would like to publish metrics for itself and also
on behalf of "Thing-2". "Thing-1" collects its own metrics and publishes them on the MQTT topic:
$aws/things/Thing-1/defender/metrics/json
"Thing-1" will then obtain metrics from "Thing-2" and publish these metrics on the MQTT topic:
$aws/things/Thing-2/defender/metrics/json
As long as "Thing-1" and "Thing-2" are registered in your account, metric submission and evaluation
will work properly.
Q: How many security profiles and behaviors can I have in my account?
A: Refer to the Detect Service Limits (p. 550) section of the AWS IoT Device Defender Developer
Guide.
Q: What does a prototypical target role for an alert target look like?
A: A role that allows AWS IoT Device Defender to publish alerts on an alert target (SNS topic)
requires 2 things:
1. a trust relationship specifying iot.amazonaws.com as the trusted entity and
2. an attached policy which grants AWS IoT permission to publish on a specified SNS topic, for
example:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
600
AWS IoT Developer Guide
AWS IoT Device Defender Troubleshooting Guide
"Action": "sns:Publish",
"Resource": "<sns-topic-arn>"
}
]
}
601
AWS IoT Developer Guide
Event Messages
Note
This section contains information about messages published by AWS IoT when things or jobs are
updated or changed. For information about the AWS IoT Events service that allows you to create
detectors to monitor your devices for failures or changes in operation, and to trigger specific
actions when they occur, see the AWS IoT Events service overview.
AWS IoT publishes event messages when certain events occur. For example, events are generated by
the registry when things are added, updated, or deleted. Each event causes a single event message to
be sent. Event messages are published over MQTT with a JSON payload. The content of the payload
depends on the type of event.
Note
Event messages are guaranteed to be published once. It is possible for them to be published
more than once. The ordering of event messages is not guaranteed.
To receive event messages, your device must use an appropriate policy that allows it to connect to the
AWS IoT device gateway and subscribe to MQTT event topics. You must also subscribe to the appropriate
topic filters.
The following is an example of the policy required for receiving lifecycle events:
{
"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Action":[
"iot:Subscribe",
"iot:Receive"
],
"Resource":[
"arn:aws:iot:region:account:/$aws/events/*"
]
}]
}
You control which event types are published by calling the UpdateEventConfigurations API or by using
the update-event-configurations CLI command. For example:
You can get the current event configuration by calling the DescribeEventConfigurations API or by using
the describe-event-configurations CLI command. For example:.
{
"lastModifiedDate": 1552671347.841,
"eventConfigurations": {
"THING_TYPE": {
"Enabled": false
},
602
AWS IoT Developer Guide
Registry Events
"JOB_EXECUTION": {
"Enabled": false
},
"THING_GROUP_HIERARCHY": {
"Enabled": false
},
"CERTIFICATE": {
"Enabled": false
},
"THING_TYPE_ASSOCIATION": {
"Enabled": false
},
"THING_GROUP_MEMBERSHIP": {
"Enabled": false
},
"CA_CERTIFICATE": {
"Enabled": false
},
"THING": {
"Enabled": true
},
"JOB": {
"Enabled": false
},
"POLICY": {
"Enabled": false
},
"THING_GROUP": {
"Enabled": false
}
},
"creationDate": 1552671347.84
}
Registry Events
The registry publishes event messages when things, thing types, and thing groups are created, updated,
or deleted. The registry currently supports the following event types:
Thing Created/Updated/Deleted
The registry publishes the following event messages when things are created, updated, or deleted:
• $aws/events/thing/<thingName>/created
• $aws/events/thing/<thingName>/updated
• $aws/events/thing/<thingName>/deleted
{
"eventType" : "THING_EVENT",
"eventId" : "f5ae9b94-8b8e-4d8e-8c8f-b3266dd89853",
"timestamp" : 1234567890123,
"operation" : "CREATED|UPDATED|DELETED",
"accountId" : "123456789012",
"thingId" : "b604f69c-aa9a-4d4a-829e-c480e958a0b5",
"thingName" : "MyThing",
"versionNumber" : 1,
"thingTypeName" : null,
"attributes": {
"attribute3": "value3",
603
AWS IoT Developer Guide
Registry Events
"attribute1": "value1",
"attribute2": "value2"
}
}
Set to "THING_EVENT".
eventId
The version of the thing being created, updated, or deleted. This value is set to 1 when a thing is
created. It is incremented by 1 each time the thing is updated.
thingTypeName
The thing type associated with the thing, if one exists. Otherwise, null.
attributes
The registry publishes the following event messages when thing types are created, deprecated,
undeprecated, or deleted:
• $aws/events/thingType/<thingTypeName>/created
• $aws/events/thingType/<thingTypeName>/updated
• $aws/events/thingType/<thingTypeName>/deleted
{
"eventType" : "THING_TYPE_EVENT",
"eventId" : "8827376c-4b05-49a3-9b3b-733729df7ed5",
"timestamp" : 1234567890123,
"operation" : "CREATED|UPDATED|DELETED",
"accountId" : "123456789012",
604
AWS IoT Developer Guide
Registry Events
"thingTypeId" : "c530ae83-32aa-4592-94d3-da29879d1aac",
"thingTypeName" : "MyThingType",
"isDeprecated" : false|true,
"deprecationDate" : null,
"searchableAttributes" : [ "attribute1", "attribute2", "attribute3" ],
"description" : "My thing type"
}
Set to "THING_TYPE_EVENT".
eventId
The UNIX timestamp for when the thing type was deprecated.
searchableAttributes
A collection of name-value pairs associated with the thing type that can be used for searching.
description
The registry publishes the following event messages when a thing type is associated or disassociated
with a thing.
• $aws/events/thingTypeAssociation/thing/<thingName>/<typeName>
{
"eventId" : "87f8e095-531c-47b3-aab5-5171364d138d",
"eventType" : "THING_TYPE_ASSOCIATION_EVENT",
605
AWS IoT Developer Guide
Registry Events
"operation" : "CREATED|DELETED",
"thingId" : "b604f69c-aa9a-4d4a-829e-c480e958a0b5",
"thingName": "myThing",
"thingTypeName" : "MyThingType",
"timestamp" : 1234567890123,
}
Set to "THING_TYPE_ASSOCIATION_EVENT".
operation
The thing type associated with, or no longer associated with, the thing.
timestamp
The registry publishes the following event messages when a thing group is created, updated, or
deleted.
• $aws/events/thingGroup/<groupName>/created
• $aws/events/thingGroup/<groupName>/updated
• $aws/events/thingGroup/<groupName>/deleted
{
"eventType" : "THING_GROUP_EVENT",
"eventId" : "87f8e095-531c-47b3-aab5-5171364d138d",
"timestamp" : 1234567890123,
"operation" : "CREATED|UPDATED|DELETED",
"accountId" : "123456789012",
"thingGroupId" : "8f82a106-6b1d-4331-8984-a84db5f6f8cb",
"thingGroupName" : "MyRootThingGroup",
"versionNumber" : 1,
"parentGroupName" : null,
"parentGroupId" : null,
"description" : "My root thing group",
"rootToParentThingGroups" : null,
"attributes" : {
"attribute1" : "value1",
"attribute3" : "value3",
"attribute2" : "value2"
606
AWS IoT Developer Guide
Registry Events
}
}
Set to "THING_GROUP_EVENT".
eventId
The version of the thing group. This value is set to 1 when a thing group is created. It is
incremented by 1 each time the thing group is updated.
parentGroupName
An array of information about the parent thing group. There is one entry for each parent thing
group, starting with the parent of the current thing group and continuing until the root thing
group has been reached. Each entry contains the thing group name and the thing group ARN.
attributes
The registry publishes the following event messages when a thing is added to or removed from a
thing group.
• $aws/events/thingGroupMembership/thingGroup/<thingGroupName>/
thing/<thingName>/added
607
AWS IoT Developer Guide
Registry Events
• $aws/events/thingGroupMembership/thingGroup/<thingGroupName>/
thing/<thingName>/removed
{
"eventType" : "THING_GROUP_MEMBERSHIP_EVENT",
"eventId" : "d684bd5f-6f6e-48e1-950c-766ac7f02fd1",
"timestamp" : 1234567890123,
"operation" : "ADDED|REMOVED",
"accountId" : "123456789012",
"groupArn" : "arn:aws:iot:ap-northeast-2:123456789012:thinggroup/
MyChildThingGroup",
"groupId" : "06838589-373f-4312-b1f2-53f2192291c4",
"thingArn" : "arn:aws:iot:ap-northeast-2:123456789012:thing/MyThing",
"thingId" : "b604f69c-aa9a-4d4a-829e-c480e958a0b5",
"membershipId" : "8505ebf8-4d32-4286-80e9-c23a4a16bbd8"
}
Set to "THING_GROUP_MEMBERSHIP_EVENT".
eventId
ADDED when a thing is added to a thing group. REMOVED when a thing is removed from a thing
group.
accountId
The ARN of the thing that was added or removed from the thing group.
thingId
The ID of the thing that was added or removed from the thing group.
membershipId
An ID that represents the relationship between the thing and the thing group. This value is
generated when you add a thing to a thing group.
Thing Group Added to or Deleted from a Thing Group
The registry publishes the following event messages when a thing group is added to or removed
from another thing group.
• $aws/events/thingGroupHierarchy/thingGroup/<parentThingGroupName>/
childThingGroup/<childThingGroupName>/added
608
AWS IoT Developer Guide
Jobs Events
• $aws/events/thingGroupHierarchy/thingGroup/<parentThingGroupName>/
childThingGroup/<childThingGroupName>/removed
{
"eventType" : "THING_GROUP_HIERARCHY_EVENT",
"eventId" : "264192c7-b573-46ef-ab7b-489fcd47da41",
"timestamp" : 1234567890123,
"operation" : "ADDED|REMOVED",
"accountId" : "123456789012",
"thingGroupId" : "8f82a106-6b1d-4331-8984-a84db5f6f8cb",
"thingGroupName" : "MyRootThingGroup",
"childGroupId" : "06838589-373f-4312-b1f2-53f2192291c4",
"childGroupName" : "MyChildThingGroup"
}
Set to "THING_GROUP_HIERARCHY_EVENT".
eventId
ADDED when a thing is added to a thing group. REMOVED when a thing is removed from a thing
group.
accountId
Jobs Events
Jobs publishes to reserved topics on the MQTT protocol when jobs are pending, completed, or canceled,
and when a device reports success or failure when executing a job. Devices or management and
monitoring applications can keep track of the status of jobs by subscribing to these topics. You need to
use the UpdateEventConfigurations API to control what kinds of job events you receive.
Because it can take some time to cancel or delete a job, two messages are sent to indicate the start
and end of a request. For example, when a cancellation request starts, a message is sent to the $aws/
events/job/jobID/cancellation_in_progress topic. When the cancellation request is complete,
609
AWS IoT Developer Guide
Jobs Events
a message is sent to the $aws/events/job/jobID/canceled topic. A similar process occurs for a job
deletion request. Management and monitoring applications can subscribe to these topics to keep track of
the status of jobs.
For more information about publishing and subscribing to MQTT topics, see Message Broker for AWS
IoT (p. 233).
Job Completed/Canceled/Deleted
The AWS IoT Jobs service publishes a message on an MQTT topic when a job is completed, canceled,
deleted, or cancellation or deletion are in progress:
• $aws/events/job/jobID/completed
• $aws/events/job/jobID/canceled
• $aws/events/job/jobID/deleted
• $aws/events/job/jobID/cancellation_in_progress
• $aws/events/job/jobID/deletion_in_progress
{
"eventType": "JOB",
"eventId": "7364ffd1-8b65-4824-85d5-6c14686c97c6",
"timestamp": 1234567890,
"operation": "completed",
"jobId": "27450507-bf6f-4012-92af-bb8a1c8c4484",
"status": "COMPLETED",
"targetSelection": "SNAPSHOT|CONTINUOUS",
"targets": [
"arn:aws:iot:us-east-1:123456789012:thing/a39f6f91-70cf-4bd2-a381-9c66df1a80d0",
"arn:aws:iot:us-east-1:123456789012:thinggroup/2fc4c0a4-6e45-4525-
a238-0fe8d3dd21bb"
],
"description": "My Job Description",
"completedAt": 1234567890123,
"createdAt": 1234567890123,
"lastUpdatedAt": 1234567890123,
"jobProcessDetails": {
"numberOfCanceledThings": 0,
"numberOfRejectedThings": 0,
"numberOfFailedThings": 0,
"numberOfRemovedThings": 0,
"numberOfSucceededThings": 3
}
}
{
"eventType": "JOB",
"eventId": "568d2ade-2e9c-46e6-a115-18afa1286b06",
"timestamp": 1234567890,
"operation": "canceled",
"jobId": "4d2a531a-da2e-47bb-8b9e-ff5adcd53ef0",
"status": "CANCELED",
"targetSelection": "SNAPSHOT|CONTINUOUS",
"targets": [
"arn:aws:iot:us-east-1:123456789012:thing/Thing0-947b9c0c-ff10-4a80-b4b3-
cd33d0145a0f",
"arn:aws:iot:us-east-1:123456789012:thinggroup/ThingGroup1-95c644d5-1621-41a6-9aa5-
ad2de581d18f"
],
610
AWS IoT Developer Guide
Jobs Events
{
"eventType": "JOB",
"eventId": "568d2ade-2e9c-46e6-a115-18afa1286b06",
"timestamp": 1234567890,
"operation": "deleted",
"jobId": "4d2a531a-da2e-47bb-8b9e-ff5adcd53ef0",
"status": "DELETED",
"targetSelection": "SNAPSHOT|CONTINUOUS",
"targets": [
"arn:aws:iot:us-east-1:123456789012:thing/Thing0-947b9c0c-ff10-4a80-b4b3-
cd33d0145a0f",
"arn:aws:iot:us-east-1:123456789012:thinggroup/
ThingGroup1-95c644d5-1621-41a6-9aa5-ad2de581d18f"
],
"description": "My job description",
"createdAt": 1234567890123,
"lastUpdatedAt": 1234567890123,
"comment": "Comment for this operation"
}
{
"eventType": "JOB",
"eventId": "568d2ade-2e9c-46e6-a115-18afa1286b06",
"timestamp": 1234567890,
"operation": "cancellation_in_progress",
"jobId": "4d2a531a-da2e-47bb-8b9e-ff5adcd53ef0",
"status": "CANCELLATION_IN_PROGRESS",
"targetSelection": "SNAPSHOT|CONTINUOUS",
"targets": [
"arn:aws:iot:us-east-1:123456789012:thing/Thing0-947b9c0c-ff10-4a80-b4b3-
cd33d0145a0f",
"arn:aws:iot:us-east-1:123456789012:thinggroup/
ThingGroup1-95c644d5-1621-41a6-9aa5-ad2de581d18f"
],
"description": "My job description",
"createdAt": 1234567890123,
"lastUpdatedAt": 1234567890123,
"comment": "Comment for this operation"
}
{
"eventType": "JOB",
"eventId": "568d2ade-2e9c-46e6-a115-18afa1286b06",
"timestamp": 1234567890,
"operation": "deletion_in_progress",
"jobId": "4d2a531a-da2e-47bb-8b9e-ff5adcd53ef0",
"status": "DELETION_IN_PROGRESS",
"targetSelection": "SNAPSHOT|CONTINUOUS",
"targets": [
"arn:aws:iot:us-east-1:123456789012:thing/Thing0-947b9c0c-ff10-4a80-b4b3-
cd33d0145a0f",
611
AWS IoT Developer Guide
Lifecycle Events
"arn:aws:iot:us-east-1:123456789012:thinggroup/
ThingGroup1-95c644d5-1621-41a6-9aa5-ad2de581d18f"
],
"description": "My job description",
"createdAt": 1234567890123,
"lastUpdatedAt": 1234567890123,
"comment": "Comment for this operation"
}
The AWS IoT Jobs service publishes a message when a device updates a job execution to terminal
status:
• $aws/events/jobExecution/jobID/succeeded
• $aws/events/jobExecution/jobID/failed
• $aws/events/jobExecution/jobID/rejected
• $aws/events/jobExecution/jobID/canceled
• $aws/events/jobExecution/jobID/timed_out
• $aws/events/jobExecution/jobID/removed
• $aws/events/jobExecution/jobID/deleted
{
"eventType": "JOB_EXECUTION",
"eventId": "cca89fa5-8a7f-4ced-8c20-5e653afb3572",
"timestamp": 1234567890,
"operation": "succeeded|failed|rejected|canceled|removed|timed_out",
"jobId": "154b39e5-60b0-48a4-9b73-f6f8dd032d27",
"thingArn": "arn:aws:iot:us-east-1:123456789012:myThing/6d639fbc-8f85-4a90-924d-
a2867f8366a7",
"status": "SUCCEEDED|FAILED|REJECTED|CANCELED|REMOVED|TIMED_OUT",
"statusDetails": {
"key": "value"
}
}
Lifecycle Events
AWS IoT publishes lifecycle events on the MQTT topics discussed in the following sections. These
messages allow you to be notified of lifecycle events from the message broker.
Note
Lifecycle messages might be sent out of order. You might receive duplicate messages.
Connect/Disconnect Events
AWS IoT publishes a message to the following MQTT topics when a client connects or disconnects:
The following is a list of JSON elements that are contained in the connection/disconnection messages
published to the $aws/events/presence/connected/clientId topic.
612
AWS IoT Developer Guide
Subscribe/Unsubscribe Events
clientId
Only found in disconnection messages. True if the client initiated the disconnect. Otherwise, False.
eventType
The credential used to authenticate. For TLS mutual authentication certificates, this is the certificate
ID. For other connections, this is IAM credentials.
sessionIdentifier
A globally unique identifier in AWS IoT that exists for the life of the session.
timestamp
An approximation of when the event occurred, expressed in milliseconds since the Unix epoch. The
accuracy of the timestamp is +/- 2 minutes.
versionNumber
The version number for the lifecycle event. This is a monotonically increasing long integer value
for each client ID connection. The version number can be used by a subscriber to infer the order of
lifecycle events.
Note
The Connect and Disconnect messages for a client connection have the same version
number.
The version number might skip values and is not guaranteed to be consistently increasing
by 1 for each event.
If a client is not connected for approximately one hour, the version number is reset to 0. For
persistent sessions, the version number is reset to 0 after a client has been disconnected
longer than the configured time-to-live (TTL) for the persistent session.
Subscribe/Unsubscribe Events
AWS IoT publishes a message to the following MQTT topic when a client subscribes or unsubscribes to an
MQTT topic:
$aws/events/subscriptions/subscribed/clientId
or
613
AWS IoT Developer Guide
Subscribe/Unsubscribe Events
$aws/events/subscriptions/unsubscribed/clientId
Where clientId is the MQTT client ID that connects to the AWS IoT message broker.
{
"clientId": "186b5",
"timestamp": 1460065214626,
"eventType": "subscribed" | "unsubscribed",
"sessionIdentifier": "00000000-0000-0000-0000-000000000000",
"principalIdentifier": "000000000000/ABCDEFGHIJKLMNOPQRSTU:some-user/
ABCDEFGHIJKLMNOPQRSTU:some-user"
"topics" : ["foo/bar","device/data","dog/cat"]
}
The following is a list of JSON elements that are contained in the subscribed and unsubscribed messages
published to the $aws/events/subscriptions/subscribed/clientId and $aws/events/
subscriptions/unsubscribed/clientId topics.
clientId
The credential used to authenticate. For TLS mutual authentication certificates, this is the certificate
ID. For other connections, this is IAM credentials.
sessionIdentifier
A globally unique identifier in AWS IoT that exists for the life of the session.
timestamp
An approximation of when the event occurred, expressed in milliseconds since the Unix epoch. The
accuracy of the timestamp is +/- 2 minutes.
topics
Note
Lifecycle messages might be sent out of order. You might receive duplicate messages.
614
AWS IoT Developer Guide
AWS Mobile SDK for Android
The AWS IoT Device SDKs help you to easily and quickly connect your devices to AWS IoT. The AWS IoT
Device SDKs include open-source libraries, developer guides with samples, and porting guides so that
you can build innovative IoT products or solutions on your choice of hardware platforms.
615
AWS IoT Developer Guide
AWS IoT C++ Device SDK
customer firmware along with application code, other libraries, and RTOS. For more information, see the
following:
616
AWS IoT Developer Guide
AWS IoT Device SDK for Python
617
AWS IoT Developer Guide
Monitoring Tools
The next step is to establish a baseline for normal AWS IoT performance in your environment, by
measuring performance at various times and under different load conditions. As you monitor AWS IoT,
store historical monitoring data so that you can compare it with current performance data, identify
normal performance patterns and performance anomalies, and devise methods to address issues.
For example, if you're using Amazon EC2, you can monitor CPU utilization, disk I/O, and network
utilization for your instances. When performance falls outside your established baseline, you might need
to reconfigure or optimize the instance to reduce CPU utilization, improve disk I/O, or reduce network
traffic.
• PublishIn.Success
• PublishOut.Success
• Subscribe.Success
• Ping.Success
• Connect.Success
• GetThingShadow.Accepted
• UpdateThingShadow.Accepted
• DeleteThingShadow.Accepted
• RulesExecuted
Topics
• Monitoring Tools (p. 618)
• Monitoring with Amazon CloudWatch (p. 619)
• Monitoring with CloudWatch Logs (p. 629)
• Logging AWS IoT API Calls with AWS CloudTrail (p. 649)
Monitoring Tools
AWS provides tools that you can use to monitor AWS IoT. You can configure some of these tools to
do the monitoring for you. Some of the tools require manual intervention. We recommend that you
automate monitoring tasks as much as possible.
618
AWS IoT Developer Guide
Automated Tools
• Amazon CloudWatch Alarms – Watch a single metric over a time period that you specify, and perform
one or more actions based on the value of the metric relative to a given threshold over a number of
time periods. The action is a notification sent to an Amazon Simple Notification Service (Amazon SNS)
topic or Amazon EC2 Auto Scaling policy. CloudWatch alarms do not invoke actions simply because
they are in a particular state. The state must have changed and been maintained for a specified
number of periods. For more information, see Monitoring with Amazon CloudWatch (p. 619).
• Amazon CloudWatch Logs – Monitor, store, and access your log files from AWS CloudTrail or other
sources. For more information, see Monitoring Log Files in the Amazon CloudWatch User Guide.
• Amazon CloudWatch Events – Match events and route them to one or more target functions or
streams to make changes, capture state information, and take corrective action. For more information,
see What Is Amazon CloudWatch Events in the Amazon CloudWatch User Guide.
• AWS CloudTrail Log Monitoring – Share log files between accounts, monitor CloudTrail log files in real
time by sending them to CloudWatch Logs, write log processing applications in Java, and validate that
your log files have not changed after delivery by CloudTrail. For more information, see Working with
CloudTrail Log Files in the AWS CloudTrail User Guide.
619
AWS IoT Developer Guide
Metrics and Dimensions
access historical information and gain a better perspective on how your web application or service is
performing. By default, AWS IoT metric data is sent automatically to CloudWatch in one minute periods.
For more information, see What Are Amazon CloudWatch, Amazon CloudWatch Events, and Amazon
CloudWatch Logs? in the Amazon CloudWatch User Guide.
Topics
• AWS IoT Metrics and Dimensions (p. 620)
• How Do I Use AWS IoT Metrics? (p. 627)
• Creating CloudWatch Alarms to Monitor AWS IoT (p. 627)
Metrics are grouped first by the service namespace, and then by the various dimension combinations
within each namespace.
Metric Description
NumLogEventsFailedToPublishThrottled The number of log events within the batch that have
failed to publish due to throttling errors.
620
AWS IoT Developer Guide
Metrics and Dimensions
Rule Metrics
Metric Description
Metric Description
Metric Description
621
AWS IoT Developer Guide
Metrics and Dimensions
Metric Description
622
AWS IoT Developer Guide
Metrics and Dimensions
Metric Description
Note
The message broker metrics are displayed in the AWS IoT console under Protocol Metrics.
623
AWS IoT Developer Guide
Metrics and Dimensions
Metric Description
Note
The device shadow metrics are displayed in the AWS IoT console under Protocol Metrics.
Jobs Metrics
Metric Description
624
AWS IoT Developer Guide
Metrics and Dimensions
Metric Description
Metric Description
625
AWS IoT Developer Guide
Metrics and Dimensions
Metric Description
number of resources that were out of compliance for
each check of each audit performed.
Metric Description
Dimension Description
ActionType The action type specified by the rule that triggered the
request.
Protocol The protocol used to make the request. Valid values are:
MQTT or HTTP
626
AWS IoT Developer Guide
Using AWS IoT Metrics
Dimension Description
• How can I be notified if my things do not connect successfully each day? (p. 627)
• How can I be notified if my things are not publishing data each day? (p. 628)
• How can I be notified if my thing's shadow updates are being rejected each day? (p. 629)
627
AWS IoT Developer Guide
Creating CloudWatch Alarms
--alarm-name ConnectSuccessAlarm \
--alarm-description "Alarm when my Things don't connect successfully" \
--namespace AWS/IoT \
--metric-name Connect.Success \
--dimensions Name=Protocol,Value=MQTT \
--statistic Sum \
--threshold 10 \
--comparison-operator LessThanThreshold \
--period 86400 \
--unit Count \
--evaluation-periods 1 \
--alarm-actions arn:aws:sns:us-east-1:1234567890:things-not-connecting-successfully
628
AWS IoT Developer Guide
Monitoring with CloudWatch Logs
For more information about CloudWatch Logs, see CloudWatch Logs. For information about supported
AWS IoT CloudWatch Logs, see CloudWatch Log Entry Format (p. 634).
To enable AWS IoT logging, you must create an IAM role, register the role with AWS IoT, and then
configure AWS IoT logging.
Note
Before you enable AWS IoT logging, make sure you understand the CloudWatch Logs access
permissions. Users with access to CloudWatch Logs can see debugging information from your
devices. For more information, see Authentication and Access Control for Amazon CloudWatch
Logs.
1. From the navigation pane, choose Roles, and then choose Create new role.
2. Choose AWS Service Role, and then for service role type, choose AWS IoT.
629
AWS IoT Developer Guide
Log Level
Role policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:PutMetricFilter",
"logs:PutRetentionPolicy"
],
"Resource": [
"*"
]
}
]
}
Trust policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "iot.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
Log Level
The log level specifies which types of logs are generated.
ERROR
630
AWS IoT Developer Guide
Configure AWS IoT Logging
WARN
Anything that can potentially cause inconsistencies in the system, but might not cause the operation
to fail.
You can configure logging to be global or fine-grained. Global logging sets one logging level for all logs
no matter what resource triggered the logs. Fine-grained logging allows you to set a logging level for a
specific resource or set of resources. Currently, only thing groups are supported. You can use the AWS IoT
console, the CLI, or the API to enable global logging. You must use the CLI or API to enable fine-grained
logging.
Global Logging
Use the set-v2-logging-options CLI command to set the logging options for your account. set-
v2-logging-options takes three arguments:
--role-arn
Your logging role ARN. The logging role grants AWS IoT permission to write to your logs in
CloudWatch Logs.
--default-log-level
The log level to use. Valid values are: ERROR, WARN, INFO, DEBUG, or DISABLED
--disable-all-logs | --no-disable-all-logs
When set to true (--disable-all-logs) disables all logs. The default (parameter not used) is
false.
For example:
You can use the get-v2-logging-options CLI command to get the current logging options.
631
AWS IoT Developer Guide
Configure AWS IoT Logging
Note
AWS IoT continues to support older commands (set-logging-options and get-logging-
options) to set and get global logging on your account. Be aware that when these commands
are used, the resulting logs contain plain-text, rather than JSON payloads and logging latency is
generally higher. No further improvements will be made to the implementation of these older
commands. We recommend that you use the "v2" versions to configure your logging options
and, when possible, change legacy applications that use the older versions.
1. Sign in to the the AWS IoT console. For more information, see Sign in to the AWS IoT Console (p. 5).
2. In the left navigation pane, choose Settings.
3. In the Logs section of the Settings page, choose Edit. The Logs section displays your settings for
role and level of verbosity.
4. On the Configure role setting page, choose the level of verbosity that describes the level of detail
that you want to appear in the CloudWatch logs.
632
AWS IoT Developer Guide
Configure AWS IoT Logging
5. Choose Select to specify a role that you created previously, or Create Role to create a role to use for
logging.
6. Choose Update to save your changes.
Review your CloudWatch logs to see if you are satisfied with the level of collected information. If
not, you can always change the logging level later.
Fine-Grained Logging
Fine-grained logging allows you to specify a logging level for a target. A target is defined by a resource
type and a resource name. Currently, AWS IoT supports thing groups as targets. Fine-grained logging
allows you to set a logging level for a specific thing group. Say we have a thing group called "Phones"
that contains things that represent different kinds of phones. We then create another thing group called
"MobilePhones" and make it a child of the "Phones" thing group. Fine-grained logging allows you to
configure one logging level for all things in the "Phones" group (and any child groups) and another
logging level for things in the "MobilePhones" group. In this example, we have assigned two different
logging levels to things in the "MobilePhones" group — one from the logging level for the "Phones"
thing group and another from the "MobilePhones" thing group — but the logging level specified for the
child thing group will override the logging level specified for the parent thing group.
Use the set-v2-logging-options CLI command to enable fine-grained logging and set the default
logging level. It takes the following optional arguments:
--role-arn
An IAM role that allows AWS IoT to write to your CloudWatch Logs. If not specified, AWS IoT uses the
logging role associated with your account. The logging role is associated with your account when it is
created. For more information, see Create a Logging Role (p. 629).
--default-log-level
The logging level used if not specified. Valid values are: DEBUG, INFO, ERROR, WARN, and DISABLED.
--disable-all-logs | --no-disable-all-logs
When set to true (--disable-all-logs), disables all logs. The default (parameter not used) is
false.
The get-v2-logging-options CLI command returns the configured IAM logging role, the default
logging level, and the disableAllLogs value.
Use the set-v2-logging-level CLI command to configure fine-grained logging for a target. It takes
the following arguments:
--log-target
A JSON object that contains the resource type (field targetType) and name (field targetName) of
the entity for which you are configuring logging. AWS IoT currently supports THING_GROUP for the
resource type. You can configure up to 10 logging targets.
--log-level
The logging level used when generating logs for the specified resource. Valid values are: DEBUG,
INFO, ERROR, WARN, and DISABLED
Use the list-v2-logging-levels CLI command to get a list of the currently configured fine-grained
logging levels. Call the delete-v2-logging-level CLI command to delete a logging level. Use the
delete-v2-logging-level command to delete a fine-grained logging level.
633
AWS IoT Developer Guide
CloudWatch Log Entry Format
timestamp
The UNIX timestamp of when the client connected to the AWS IoT message broker.
logLevel
The log level being used. For more information, see the section called “Log Level” (p. 630).
traceId
A randomly generated identifier that can be used to correlate all logs for a specific request.
accountId
The event type for which the log was generated. The value of the event type for each event is listed
in the following sections.
Connect Log
The AWS IoT message broker generates a Connect log when an MQTT client connects.
more info (1)
For example:
{
"timestamp": "2017-08-10 15:37:23.476",
"logLevel": "INFO",
"traceId": "20b23f3f-d7f1-feae-169f-82263394fbdb",
"accountId": "123456789012",
"status": "Success",
"eventType": "Connect",
"protocol": "MQTT",
"clientId": "abf27092886e49a8a5c1922749736453",
"principalId": "145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167",
"sourceIp": "205.251.233.181",
"sourcePort": 13490
634
AWS IoT Developer Guide
CloudWatch Log Entry Format
In addition to the attributes common to CloudWatch Logs, Connect log entries contain the
following attributes:
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
clientId
Subscribe Log
The AWS IoT message broker generates a Subscribe log when an MQTT client subscribes to a topic.
more info (2)
For example:
{
"timestamp": "2017-08-10 15:39:04.413",
"logLevel": "INFO",
"traceId": "7aa5c38d-1b49-3753-15dc-513ce4ab9fa6",
"accountId": "123456789012",
"status": "Success",
"eventType": "Subscribe",
"protocol": "MQTT",
"topicName": "$aws/things/MyThing/shadow/#",
"clientId": "abf27092886e49a8a5c1922749736453",
"principalId": "145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167",
"sourceIp": "205.251.233.181",
"sourcePort": 13490
}
In addition to the attributes common to CloudWatch Logs, Subscribe log entries contain the
following attributes:
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
topicName
635
AWS IoT Developer Guide
CloudWatch Log Entry Format
clientId
Publish-In Log
When the AWS IoT message broker receives an MQTT message, it generates a Publish-In log.
more info (3)
For example:
{
"timestamp": "2017-08-10 15:39:30.961",
"logLevel": "INFO",
"traceId": "672ec480-31ce-fd8b-b5fb-22e3ac420699",
"accountId": "123456789012",
"status": "Success",
"eventType": "Publish-In",
"protocol": "MQTT",
"topicName": "$aws/things/MyThing/shadow/get",
"clientId": "abf27092886e49a8a5c1922749736453",
"principalId":
"145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167",
"sourceIp": "205.251.233.181",
"sourcePort": 13490
}
In addition to the attributes common to CloudWatch Logs, Publish-In log entries contain the
following attributes:
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
topicName
636
AWS IoT Developer Guide
CloudWatch Log Entry Format
sourceIp
Publish-Out Log
When the message broker publishes an MQTT message, it generates a Publish-Out log.
more info (4)
For example:
{
"timestamp": "2017-08-10 15:39:30.961",
"logLevel": "INFO",
"traceId": "672ec480-31ce-fd8b-b5fb-22e3ac420699",
"accountId": "123456789012",
"status": "Success",
"eventType": "Publish-Out",
"protocol": "MQTT",
"topicName": "$aws/things/MyThing/shadow/get",
"clientId": "abf27092886e49a8a5c1922749736453",
"principalId": "145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167",
"sourceIp": "205.251.233.181",
"sourcePort": 13490
}
In addition to the attributes common to CloudWatch Logs, Publish-Out log entries contain the
following attributes:
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
topicName
637
AWS IoT Developer Guide
CloudWatch Log Entry Format
Disconnect Log
The AWS IoT message broker generates a Disconnect log when an MQTT client disconnects.
more info (5)
For example:
{
"timestamp": "2017-08-10 15:37:23.476",
"logLevel": "INFO",
"traceId": "20b23f3f-d7f1-feae-169f-82263394fbdb",
"accountId": "123456789012",
"status": "Success",
"eventType": "Disconnect",
"protocol": "MQTT",
"clientId": "abf27092886e49a8a5c1922749736453",
"principalId": "145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167",
"sourceIp": "205.251.233.181",
"sourcePort": 13490
}
In addition to the attributes common to CloudWatch Logs, Disconnect log entries contain the
following attributes:
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
clientId
GetThingShadow Logs
The Device Shadow service generates a GetThingShadow log when a get request for a shadow is
received.
more info (6)
For example:
{
"timestamp": "2017-08-09 17:56:30.941",
"logLevel": "INFO",
"traceId": "b575f19a-97a2-cf72-0ed0-c64a783a2504",
638
AWS IoT Developer Guide
CloudWatch Log Entry Format
"accountId": "123456789012",
"status": "Success",
"eventType": "GetThingShadow",
"protocol": "MQTT",
"deviceShadowName": "MyThing",
"topicName": "$aws/things/MyThing/shadow/get"
}
In addition to the attributes common to CloudWatch Logs, GetThingShadow log entries contain the
following attributes:
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
deviceShadowName
UpdateThingShadow Logs
The Device Shadow service generates a UpdateThingShadow log when a request to update a
device's shadow is received.
more info (7)
For example:
{
"timestamp": "2017-08-07 18:43:59.436",
"logLevel": "INFO",
"traceId": "d0074ba8-0c4b-a400-69df-76326d414c28",
"accountId": "123456789012",
"status": "Success",
"eventType": "UpdateThingShadow",
"protocol": "MQTT",
"deviceShadowName": "Jack",
"topicName": "$aws/things/Jack/shadow/update"
}
In addition to the attributes common to CloudWatch Logs, UpdateThingShadow log entries contain
the following attributes:
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
deviceShadowName
639
AWS IoT Developer Guide
CloudWatch Log Entry Format
DeleteThingShadow Logs
The Device Shadow service generates a DeleteThingShadow log when a request to delete a
device's shadow is received.
more info (8)
For example:
{
"timestamp": "2017-08-07 18:47:56.664",
"logLevel": "INFO",
"traceId": "1a60d02e-15b9-605b-7096-a9f584a6ad3f",
"accountId": "123456789012",
"status": "Success",
"eventType": "DeleteThingShadow",
"protocol": "MQTT",
"deviceShadowName": "Jack",
"topicName": "$aws/things/Jack/shadow/delete"
}
In addition to the attributes common to CloudWatch Logs, DeleteThingShadow log entries contain
the following attributes:
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
deviceShadowName
The AWS IoT rules engine generates a RuleMatch log when the message broker receives a message
that matches a rule.
more info (9)
For example:
{
"timestamp": "2017-08-10 16:32:46.002",
"logLevel": "INFO",
"traceId": "30aa7ccc-1d23-0b97-aa7b-76196d83537e",
"accountId": "123456789012",
"status": "Success",
"eventType": "RuleMatch",
"clientId": "abf27092886e49a8a5c1922749736453",
"topicName": "rules/test",
"ruleName": "JSONLogsRule",
"principalId": "145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167"
640
AWS IoT Developer Guide
CloudWatch Log Entry Format
In addition to the attributes common to CloudWatch Logs, RuleMatch log entries contain the
following attributes:
eventType
The rules engine generates a FunctionExecution log when a rule's SQL query calls an external
function. An external function is called when a rule's action makes an HTTP request to AWS IoT or
another web service (for example, calling get_thing_shadow or machinelearning_predict).
more info (10)
{
"timestamp": "2017-07-13 18:33:51.903",
"logLevel": "DEBUG",
"traceId": "180532b7-0cc7-057b-687a-5ca1824838f5",
"status": "Success",
"eventType": "FunctionExecution",
"clientId": "N/A",
"topicName":"rules/test",
"ruleName": "ruleTestPredict",
"ruleAction": "MachinelearningPredict",
"resources": {
"ModelId": "predict-model"
},
"principalId": "145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167"
}
In addition to the attributes common to CloudWatch Logs, FunctionExecution log entries contain
the following attributes:
eventType
641
AWS IoT Developer Guide
CloudWatch Log Entry Format
ruleName
When the AWS IoT rules engine starts to trigger a rule's action, it generates a StartingExecution
log.
more info (11)
For example:
{
"timestamp": "2017-08-10 16:32:46.002",
"logLevel": "DEBUG",
"traceId": "30aa7ccc-1d23-0b97-aa7b-76196d83537e",
"accountId": "123456789012",
"status": "Success",
"eventType": "StartingRuleExecution",
"clientId": "abf27092886e49a8a5c1922749736453",
"topicName": "rules/test",
"ruleName": "JSONLogsRule",
"ruleAction": "RepublishAction",
"principalId": "145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167"
}
In addition to the attributes common to CloudWatch Logs, StartingExecution log entries contain
the following attributes:
eventType
When the AWS IoT rules engine triggers a rule's action, it generates a RuleExecution log.
642
AWS IoT Developer Guide
CloudWatch Log Entry Format
For example:
{
"timestamp": "2017-08-10 16:32:46.070",
"logLevel": "INFO",
"traceId": "30aa7ccc-1d23-0b97-aa7b-76196d83537e",
"accountId": "123456789012",
"status": "Success",
"eventType": "RuleExecution",
"clientId": "abf27092886e49a8a5c1922749736453",
"topicName": "rules/test",
"ruleName": "JSONLogsRule",
"ruleAction": "RepublishAction",
"resources": {
"RepublishTopic": "rules/republish"
},
"principalId": "145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167"
}
In addition to the attributes common to CloudWatch Logs, RuleExecution log entries contain the
following attributes:
eventType
When the AWS IoT rules engine cannot find a rule with a given name, it generates a RuleNotFound
error log.
more info (13)
For example:
{
"timestamp": "2017-10-04 19:25:46.070",
"logLevel": "ERROR",
"traceId": "30aa7ccc-1d23-0b97-aa7b-76196d83537e",
643
AWS IoT Developer Guide
CloudWatch Log Entry Format
"accountId": "123456789012",
"status": "Failure",
"eventType": "RuleNotFound",
"clientId": "abf27092886e49a8a5c1922749736453",
"topicName": "$aws/rules/example_rule",
"ruleName": "example_rule",
"principalId": "145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167",
"reason": "RuleNotFound",
"details": "Rule example_rule not found"
}
In addition to the attributes common to CloudWatch Logs, RuleNotFound log entries contain the
following attributes:
eventType
When a message is throttled, the AWS IoT rules engine generates a RuleMessageThrottled error
log.
more info (14)
For example:
{
"timestamp": "2017-10-04 19:25:46.070",
"logLevel": "ERROR",
"traceId": "30aa7ccc-1d23-0b97-aa7b-76196d83537e",
"accountId": "123456789012",
"status": "Failure",
"eventType": "RuleMessageThrottled",
"clientId": "abf27092886e49a8a5c1922749736453",
"topicName": "$aws/rules/example_rule",
"ruleName": "example_rule",
"principalId": "145179c40e2219e18a909d896a5340b74cf97a39641beec2fc3eeafc5a932167",
"reason": "RuleExecutionThrottled",
"details": "Message for Rule example_rule throttled"
}
644
AWS IoT Developer Guide
CloudWatch Log Entry Format
eventType
Job Logs
The AWS IoT Job service generates logs for the following events. Logs are generated when an MQTT or
HTTP request is received from the device.
The AWS IoT Jobs service generates a GetJobExecution log when the service receives a job
execution request.
more info (16)
For example:
{
"timestamp": "2018-06-13 17:45:17.197",
"logLevel": "DEBUG",
"accountId": "123456789012",
"status": "Success",
"eventType": "GetPendingJobExecution",
"protocol": "MQTT",
"clientId": "299966ad-54de-40b4-99d3-4fc8b52da0c5",
"topicName": "$aws/things/299966ad-54de-40b4-99d3-4fc8b52da0c5/jobs/get",
"clientToken": "24b9a741-15a7-44fc-bd3c-1ff2e34e5e82",
"details": "The request status is SUCCESS."
}
eventType
645
AWS IoT Developer Guide
CloudWatch Log Entry Format
protocol
The protocol used when making the request. Valid values are MQTT or HTTP.
clientId
A unique, case sensitive identifier to ensure the idempotency of the request. For more
information, see How to Ensure Idempotency.
details
The AWS IoT Jobs service generates a DescribeJobExecution log when the service receives a
request to describe a job execution.
more info (17)
For example:
{
"timestamp": "2017-08-10 19:13:22.841",
"logLevel": "DEBUG",
"accountId": "123456789012",
"status": "Success",
"eventType": "DescribeJobExecution",
"protocol": "MQTT",
"clientId": "thingOne",
"jobId": "002",
"topicName": "$aws/things/thingOne/jobs/002/get",
"clientToken": "myToken",
"details": "The request status is SUCCESS."
}
In addition to the attributes common to CloudWatch Logs, GetJobExecution log entries contain
the following attributes:
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
clientId
646
AWS IoT Developer Guide
CloudWatch Log Entry Format
clientToken
A unique, case sensitive identifier to ensure the idempotency of the request. For more
information, see How to Ensure Idempotency.
details
The AWS IoT Jobs service generates an UpdateJobExecution log when the service receives a
request to update a job execution.
more info (18)
For example:
{
"timestamp": "2017-08-10 19:25:14.758",
"logLevel": "DEBUG",
"accountId": "123456789012",
"status": "Success",
"eventType": "UpdateJobExecution",
"protocol": "MQTT",
"clientId": "thingOne",
"jobId": "002",
"topicName": "$aws/things/thingOne/jobs/002/update",
"clientToken": "myClientToken",
"versionNumber": "1",
"details": "The destination status is IN_PROGRESS. The request status is SUCCESS."
}
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
clientId
A unique, case sensitive identifier to ensure the idempotency of the request. For more
information, see How to Ensure Idempotency.
versionNumber
647
AWS IoT Developer Guide
CloudWatch Log Entry Format
details
When it receives a request to start the next pending job execution, the AWS IoT Jobs service
generates a StartNextPendingJobExecution log.
more info (19)
For example:
{
"timestamp": "2018-06-13 17:49:51.036",
"logLevel": "DEBUG",
"accountId": "123456789012",
"status": "Success",
"eventType": "StartNextPendingJobExecution",
"protocol": "MQTT",
"clientId": "95c47808-b1ca-4794-bc68-a588d6d9216c",
"topicName": "$aws/things/95c47808-b1ca-4794-bc68-a588d6d9216c/jobs/start-next",
"clientToken": "bd7447c4-3a05-49f4-8517-dd89b2c68d94",
"details": "The request status is SUCCESS."
}
eventType
The protocol used when making the request. Valid values are MQTT or HTTP.
clientId
A unique, case sensitive identifier to ensure the idempotency of the request. For more
information, see How to Ensure Idempotency.
details
The AWS IoT Jobs service generates a ReportFinalJobExecutionCount log when a job is
completed.
more info (20)
For example:
{
"timestamp": "2017-08-10 19:44:16.776",
648
AWS IoT Developer Guide
Viewing Logs
"logLevel": "INFO",
"accountId": "123456789012",
"status": "Success",
"eventType": "ReportFinalJobExecutionCount",
"jobId": "002",
"details": "Job 002 completed. QUEUED job execution count: 0 IN_PROGRESS job
execution count: 0 FAILED job execution count: 0 SUCCEEDED job execution count: 1
CANCELED job execution count: 0 REJECTED job execution count: 0 REMOVED job execution
count: 0"
}
eventType
Viewing Logs
To view your logs
You can also enter a query in the Filter events text box. Here are some interesting queries to try:
• { $.logLevel = "INFO" }
Find all logs that have a status of Success and an event type of GetThingShadow.
For more information about creating filter expressions, see CloudWatch Logs Queries.
649
AWS IoT Developer Guide
AWS IoT Information in CloudTrail
calls from the AWS IoT console and from code calls to the AWS IoT APIs. If you create a trail, you can
enable continuous delivery of CloudTrail events to an Amazon S3 bucket, including events for AWS IoT.
If you don't configure a trail, you can still view the most recent events in the CloudTrail console in Event
history. Using the information collected by CloudTrail, you can determine the request that was made to
AWS IoT, the IP address from which the request was made, who made the request, when it was made,
and other details.
To learn more about CloudTrail, see the AWS CloudTrail User Guide.
For an ongoing record of events in your AWS account, including events for AWS IoT, create a trail. A
trail enables CloudTrail to deliver log files to an Amazon S3 bucket. By default, when you create a trail
in the console, the trail applies to all AWS Regions. The trail logs events from all AWS Regions in the
AWS partition and delivers the log files to the Amazon S3 bucket that you specify. You can configure
other AWS services to further analyze and act upon the event data collected in CloudTrail logs. For more
information, see:
Note
AWS IoT data plane actions (device side) are not logged by CloudTrail. Use CloudWatch to
monitor these.
AWS IoT control plane actions are logged by CloudTrail. For example, calls to the CreateThing,
ListThings, and ListTopicRules sections generate entries in the CloudTrail log files.
Every event or log entry contains information about who generated the request. The identity
information helps you determine the following:
• Whether the request was made with root or IAM user credentials.
• Whether the request was made with temporary security credentials for a role or federated user.
• Whether the request was made by another AWS service.
For more information, see the CloudTrail userIdentity Element. AWS IoT actions are documented in the
AWS IoT API Reference.
The following example shows a CloudTrail log entry that demonstrates the AttachPolicy action.
650
AWS IoT Developer Guide
Understanding AWS IoT Log File Entries
{
"timestamp":"1460159496",
"AdditionalEventData":"",
"Annotation":"",
"ApiVersion":"",
"ErrorCode":"",
"ErrorMessage":"",
"EventID":"8bff4fed-c229-4d2d-8264-4ab28a487505",
"EventName":"AttachPolicy",
"EventTime":"2016-04-08T23:51:36Z",
"EventType":"AwsApiCall",
"ReadOnly":"",
"RecipientAccountList":"",
"RequestID":"d4875df2-fde4-11e5-b829-23bf9b56cbcd",
"RequestParamters":{
"principal":"arn:aws:iot:us-
east-1:123456789012:cert/528ce36e8047f6a75ee51ab7beddb4eb268ad41d2ea881a10b67e8e76924d894",
"policyName":"ExamplePolicyForIoT"
},
"Resources":"",
"ResponseElements":"",
"SourceIpAddress":"52.90.213.26",
"UserAgent":"aws-internal/3",
"UserIdentity":{
"type":"AssumedRole",
"principalId":"AKIAI44QH8DHBEXAMPLE",
"arn":"arn:aws:sts::12345678912:assumed-role/iotmonitor-us-east-1-beta-
InstanceRole-1C5T1YCYMHPYT/i-35d0a4b6",
"accountId":"222222222222",
"accessKeyId":"access-key-id",
"sessionContext":{
"attributes":{
"mfaAuthenticated":"false",
"creationDate":"Fri Apr 08 23:51:10 UTC 2016"
},
"sessionIssuer":{
"type":"Role",
"principalId":"AKIAI44QH8DHBEXAMPLE",
"arn":"arn:aws:iam::123456789012:role/executionServiceEC2Role/iotmonitor-
us-east-1-beta-InstanceRole-1C5T1YCYMHPYT",
"accountId":"222222222222",
"userName":"iotmonitor-us-east-1-InstanceRole-1C5T1YCYMHPYT"
}
},
"invokedBy":{
"serviceAccountId":"111111111111"
}
},
"VpcEndpointId":""
}
651
AWS IoT Developer Guide
Diagnosing Connectivity Issues
Tasks
• Diagnosing Connectivity Issues (p. 652)
• Diagnosing Rules Issues (p. 652)
• Diagnosing Problems with Shadows (p. 653)
• Diagnosing Salesforce IoT Input Stream Action Issues (p. 654)
• AWS IoT Limits (p. 655)
• AWS IoT Errors (p. 655)
Add the AWS IoT CA certificate to your client’s trust store. Refer to the documentation on Server
Authentication in AWS IoT Core and then follow the links to download the appropriate CA
certificate.
How can I validate a correctly configured certificate?
Use the OpenSSL s_client command to test a connection to the AWS IoT endpoint:
Authorization
I received a PUBNACK or SUBNACK response from the broker. What do I do?
Make sure that there is a policy attached to the certificate you are using to call AWS IoT. All publish/
subscribe operations are denied by default.
The most common rules issue is authorization. The logs show if your role is not authorized to perform
AssumeRole on the resource. Here is an example log generated by fine-grained logging (p. 633):
652
AWS IoT Developer Guide
Diagnosing Problems with Shadows
{
"timestamp": "2017-12-09 22:49:17.954",
"logLevel": "ERROR",
"traceId": "ff563525-6469-506a-e141-78d40375fc4e",
"accountId": "123456789012",
"status": "Failure",
"eventType": "RuleExecution",
"clientId": "iotconsole-123456789012-3",
"topicName": "test-topic",
"ruleName": "rule1",
"ruleAction": "DynamoAction",
"resources": {
"ItemHashKeyField": "id",
"Table": "trashbin",
"Operation": "Insert",
"ItemHashKeyValue": "id",
"IsPayloadJSON": "true"
},
"principalId": "ABCDEFG1234567ABCD890:outis",
"details": "User: arn:aws:sts::123456789012:assumed-role/dynamo-testbin/5aUMInJH
is not authorized to perform: dynamodb:PutItem on resource: arn:aws:dynamodb:us-
east-1:123456789012:table/testbin (Service: AmazonDynamoDBv2; Status Code: 400; Error Code:
AccessDeniedException; Request ID: AKQJ987654321AKQJ123456789AKQJ987654321AKQJ987654321)"
}
For more information, see the section called “Viewing Logs” (p. 649).
External services are controlled by the end user. Before rule execution, make sure external services are
set up with enough throughput and capacity units.
A device's shadow document is rejected with If you are unfamiliar with JSON, modify the
"Invalid JSON document." examples provided in this guide for your own
use. For more information, see Device Shadow
Document Syntax.
I submitted correct JSON, but none or only parts Be sure you are following the JSON formatting
of it are stored in the device's shadow document. guidelines. Only JSON fields in the desired and
653
AWS IoT Developer Guide
Diagnosing Salesforce Action Issues
I received an error that the device's shadow The device's shadow supports 8 KB of data
exceeds the allowed size. only. Try shortening field names inside of your
JSON document or simply create more shadows
by creating more things. A device can have an
unlimited number of things/shadows associated
with it. The only requirement is that each thing
name must be unique in your account.
When I receive a device's shadow, it is larger than Upon receipt, the AWS IoT service adds metadata
8 KB. How can this happen? to the device's shadow. The service includes this
data in its response, but it does not count toward
the limit of 8 KB. Only the data for desired and
reported state inside the state document sent to
the device's shadow counts toward the limit.
My request has been rejected due to incorrect Perform a GET operation to sync to the latest
version. What should I do? state document version. When using MQTT,
subscribe to the ./update/accepted topic to be
notified about state changes and receive the
latest version of the JSON document.
The timestamp is off by several seconds. The timestamp for individual fields and the whole
JSON document is updated when the document
is received by the AWS IoT service or when the
state document is published onto the ./update/
accepted and ./update/delta message. Messages
can be delayed over the network, which can cause
the timestamp to be off by a few seconds.
My device can publish and subscribe on the Be sure you have created policies in IAM to allow
corresponding shadow topics, but when I attempt access to these topics and for the corresponding
to update the shadow document over the HTTP action (UPDATE/GET/DELETE) for the credentials
REST API, I get HTTP 403. you are using. IAM policies and certificate policies
are independent.
If CloudWatch Logs are not set up, see the Monitoring with CloudWatch Logs (p. 629) section. After
you have activated the logs, you are able to see the execution trace of the Salesforce action.
654
AWS IoT Developer Guide
Action Success and Failure
View the logs generated by execution of the Salesforce action in CloudWatch Logs. If you see
"Action executed successfully," then it means that the AWS IoT rules engine received
confirmation from the Salesforce IoT that the message was successfully pushed to the targeted
input stream.
If you are experiencing problems with the Salesforce IoT platform, contact Salesforce IoT support.
What do I do if messages have not been sent successfully to a Salesforce IoT input stream?
View the logs generated by execution of the Salesforce action in CloudWatch Logs. Depending on
the log entry, you can try the following actions:
Failed to locate the host
Check that the url parameter of the action is correct and that your Salesforce IoT input stream
exists.
Received Internal Server Error from Salesforce
Salesforce IoT does not support a binary payload at this time. Check that you are sending a
JSON payload.
Received Unauthorized Exception from Salesforce
Check that the token parameter of the action is correct and that your token is still valid.
Received Not Found Exception from Salesforce
Check that the url parameter of the action is correct and that your Salesforce IoT input stream
exists.
If you receive an error that is not listed here, contact AWS Support.
655
AWS IoT Developer Guide
AWS IoT Errors
401 Unauthorized.
403 Forbidden.
401 Unauthorized.
401 Unauthorized.
403 Forbidden.
409 Conflict.
656
AWS IoT Developer Guide
IOT Commands
This chapter contains the following sections:
• AcceptCertificateTransfer (p. 661)
• AddThingToBillingGroup (p. 662)
• AddThingToThingGroup (p. 663)
• AssociateTargetsWithJob (p. 664)
• AttachPolicy (p. 666)
• AttachPrincipalPolicy (p. 667)
• AttachSecurityProfile (p. 668)
• AttachThingPrincipal (p. 669)
• CancelAuditTask (p. 670)
• CancelCertificateTransfer (p. 671)
• CancelJob (p. 672)
• CancelJobExecution (p. 674)
• ClearDefaultAuthorizer (p. 676)
• CreateAuthorizer (p. 677)
• CreateBillingGroup (p. 679)
• CreateCertificateFromCsr (p. 680)
• CreateDynamicThingGroup (p. 682)
• CreateJob (p. 686)
• CreateKeysAndCertificate (p. 691)
• CreateOTAUpdate (p. 692)
• CreatePolicy (p. 698)
• CreatePolicyVersion (p. 699)
• CreateRoleAlias (p. 701)
• CreateScheduledAudit (p. 702)
• CreateSecurityProfile (p. 705)
• CreateStream (p. 709)
• CreateThing (p. 712)
• CreateThingGroup (p. 714)
• CreateThingType (p. 717)
• CreateTopicRule (p. 719)
• DeleteAccountAuditConfiguration (p. 733)
• DeleteAuthorizer (p. 734)
• DeleteBillingGroup (p. 735)
• DeleteCACertificate (p. 736)
• DeleteCertificate (p. 737)
• DeleteDynamicThingGroup (p. 738)
• DeleteJob (p. 739)
• DeleteJobExecution (p. 741)
657
AWS IoT Developer Guide
658
AWS IoT Developer Guide
659
AWS IoT Developer Guide
660
AWS IoT Developer Guide
AcceptCertificateTransfer
AcceptCertificateTransfer
Accepts a pending certificate transfer. The default state of the certificate is INACTIVE.
To check for pending certificate transfers, call ListCertificates to enumerate your certificates.
Synopsis
cli-input-json format
{
"certificateId": "string",
"setAsActive": "boolean"
}
cli-input-json fields
Output
None
Errors
ResourceNotFoundException
You can't revert the certificate transfer because the transfer is already complete.
InvalidRequestException
661
AWS IoT Developer Guide
AddThingToBillingGroup
ThrottlingException
AddThingToBillingGroup
Adds a thing to a billing group.
Synopsis
cli-input-json format
{
"billingGroupName": "string",
"billingGroupArn": "string",
"thingName": "string",
"thingArn": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
662
AWS IoT Developer Guide
AddThingToThingGroup
Output
None
Errors
InvalidRequestException
AddThingToThingGroup
Adds a thing to a thing group.
Synopsis
cli-input-json format
{
"thingGroupName": "string",
"thingGroupArn": "string",
"thingName": "string",
"thingArn": "string",
"overrideDynamicGroups": "boolean"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
663
AWS IoT Developer Guide
AssociateTargetsWithJob
pattern: [a-zA-Z0-9:_-]+
Output
None
Errors
InvalidRequestException
AssociateTargetsWithJob
Associates a group with a continuous job. The following criteria must be met:
• The job must have been created with the targetSelection field set to "CONTINUOUS".
• The job status must currently be "IN_PROGRESS".
• The total number of targets associated with a job must not exceed 100.
Synopsis
664
AWS IoT Developer Guide
AssociateTargetsWithJob
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"targets": [
"string"
],
"jobId": "string",
"comment": "string"
}
cli-input-json fields
Output
{
"jobArn": "string",
"jobId": "string",
"description": "string"
}
pattern: [^\\p{C}]+
665
AWS IoT Developer Guide
AttachPolicy
Errors
InvalidRequestException
AttachPolicy
Attaches a policy to the specified target.
Synopsis
cli-input-json format
{
"policyName": "string",
"target": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
Output
None
666
AWS IoT Developer Guide
AttachPrincipalPolicy
Errors
ResourceNotFoundException
AttachPrincipalPolicy
Attaches the specified policy to the specified principal (certificate or other credential).
Synopsis
cli-input-json format
{
"policyName": "string",
"principal": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
667
AWS IoT Developer Guide
AttachSecurityProfile
Output
None
Errors
ResourceNotFoundException
AttachSecurityProfile
Associates a Device Defender security profile with a thing group or with this account. Each thing group or
account can have up to five security profiles associated with it.
Synopsis
cli-input-json format
{
"securityProfileName": "string",
"securityProfileTargetArn": "string"
668
AWS IoT Developer Guide
AttachThingPrincipal
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
None
Errors
InvalidRequestException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
AttachThingPrincipal
Attaches the specified principal to the specified thing. A principal can be X.509 certificates, IAM users,
groups, and roles, Amazon Cognito identities or federated identities.
Synopsis
669
AWS IoT Developer Guide
CancelAuditTask
cli-input-json format
{
"thingName": "string",
"principal": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
None
Errors
ResourceNotFoundException
CancelAuditTask
Cancels an audit that is in progress. The audit can be either scheduled or on-demand. If the audit is not
in progress, an "InvalidRequestException" occurs.
Synopsis
670
AWS IoT Developer Guide
CancelCertificateTransfer
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"taskId": "string"
}
cli-input-json fields
Output
None
Errors
ResourceNotFoundException
CancelCertificateTransfer
Cancels a pending transfer for the specified certificate.
Note Only the transfer source account can use this operation to cancel a transfer. (Transfer destinations
can use RejectCertificateTransfer instead.) After transfer, AWS IoT returns the certificate to the source
account in the INACTIVE state. After the destination account has accepted the transfer, the transfer
cannot be cancelled.
After a certificate transfer is cancelled, the status of the certificate changes from PENDING_TRANSFER to
INACTIVE.
Synopsis
671
AWS IoT Developer Guide
CancelJob
[--generate-cli-skeleton]
cli-input-json format
{
"certificateId": "string"
}
cli-input-json fields
Output
None
Errors
ResourceNotFoundException
You can't revert the certificate transfer because the transfer is already complete.
InvalidRequestException
CancelJob
Cancels a job.
Synopsis
672
AWS IoT Developer Guide
CancelJob
[--reason-code <value>] \
[--comment <value>] \
[--force | --no-force] \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"jobId": "string",
"reasonCode": "string",
"comment": "string",
"force": "boolean"
}
cli-input-json fields
Output
{
"jobArn": "string",
"jobId": "string",
"description": "string"
673
AWS IoT Developer Guide
CancelJobExecution
pattern: [^\\p{C}]+
Errors
InvalidRequestException
CancelJobExecution
Cancels the execution of a job for a given thing.
Synopsis
cli-input-json format
{
"jobId": "string",
"thingName": "string",
"force": "boolean",
"expectedVersion": "long",
674
AWS IoT Developer Guide
CancelJobExecution
"statusDetails": {
"string": "string"
}
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
675
AWS IoT Developer Guide
ClearDefaultAuthorizer
Output
None
Errors
InvalidRequestException
An update attempted to change the job execution to a state that is invalid because of the job
execution's current state (for example, an attempt to change a request in state SUCCESS to state
IN_PROGRESS). In this case, the body of the error message also contains the executionState field.
ResourceNotFoundException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ClearDefaultAuthorizer
Clears the default authorizer.
Synopsis
cli-input-json format
{
}
Output
None
676
AWS IoT Developer Guide
CreateAuthorizer
Errors
ResourceNotFoundException
CreateAuthorizer
Creates an authorizer.
Synopsis
cli-input-json format
{
"authorizerName": "string",
"authorizerFunctionArn": "string",
"tokenKeyName": "string",
"tokenSigningPublicKeys": {
"string": "string"
},
"status": "string"
}
cli-input-json fields
pattern: [w=,@-]+
677
AWS IoT Developer Guide
CreateAuthorizer
Output
{
"authorizerName": "string",
"authorizerArn": "string"
}
pattern: [w=,@-]+
Errors
ResourceAlreadyExistsException
678
AWS IoT Developer Guide
CreateBillingGroup
ServiceUnavailableException
CreateBillingGroup
Creates a billing group.
Synopsis
cli-input-json format
{
"billingGroupName": "string",
"billingGroupProperties": {
"billingGroupDescription": "string"
},
"tags": [
{
"Key": "string",
"Value": "string"
}
]
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
679
AWS IoT Developer Guide
CreateCertificateFromCsr
Output
{
"billingGroupName": "string",
"billingGroupArn": "string",
"billingGroupId": "string"
}
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9-]+
Errors
InvalidRequestException
CreateCertificateFromCsr
Creates an X.509 certificate using the specified certificate signing request.
Note: The CSR must include a public key that is either an RSA key with a length of at least 2048 bits or
an ECC key from NIST P-256 or NIST P-384 curves.
680
AWS IoT Developer Guide
CreateCertificateFromCsr
Note: Reusing the same certificate signing request (CSR) results in a distinct certificate.
You can create multiple certificates in a batch by creating a directory, copying multiple .csr files into that
directory, and then specifying that directory on the command line. The following commands show how
to create a batch of certificates given a batch of CSRs.
This command lists all of the CSRs in my-csr-directory and pipes each CSR file name to the aws iot
create-certificate-from-csr AWS CLI command to create a certificate for the corresponding CSR.
The aws iot create-certificate-from-csr part of the command can also be run in parallel to speed up the
certificate creation process:
On Windows PowerShell, the command to create certificates for all CSRs in my-csr-directory is:
On a Windows command prompt, the command to create certificates for all CSRs in my-csr-directory is:
Synopsis
cli-input-json format
{
"certificateSigningRequest": "string",
"setAsActive": "boolean"
}
cli-input-json fields
681
AWS IoT Developer Guide
CreateDynamicThingGroup
Output
{
"certificateArn": "string",
"certificateId": "string",
"certificatePem": "string"
}
Errors
InvalidRequestException
CreateDynamicThingGroup
Creates a dynamic thing group.
Synopsis
682
AWS IoT Developer Guide
CreateDynamicThingGroup
[--thing-group-properties <value>] \
[--index-name <value>] \
--query-string <value> \
[--query-version <value>] \
[--tags <value>] \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"thingGroupName": "string",
"thingGroupProperties": {
"thingGroupDescription": "string",
"attributePayload": {
"attributes": {
"string": "string"
},
"merge": "boolean"
}
},
"indexName": "string",
"queryString": "string",
"queryVersion": "string",
"tags": [
{
"Key": "string",
"Value": "string"
}
]
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
length- max:2028
pattern: [\\p{Graph} ]*
\"attributes\":
{\"string1\":
\"string2\"}
683
AWS IoT Developer Guide
CreateDynamicThingGroup
Output
{
"thingGroupName": "string",
"thingGroupArn": "string",
"thingGroupId": "string",
684
AWS IoT Developer Guide
CreateDynamicThingGroup
"indexName": "string",
"queryString": "string",
"queryVersion": "string"
}
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9-]+
pattern: [a-zA-Z0-9:_-]+
Errors
InvalidRequestException
685
AWS IoT Developer Guide
CreateJob
CreateJob
Creates a job.
Synopsis
cli-input-json format
{
"jobId": "string",
"targets": [
"string"
],
"documentSource": "string",
"document": "string",
"description": "string",
"presignedUrlConfig": {
"roleArn": "string",
"expiresInSec": "long"
},
"targetSelection": "string",
"jobExecutionsRolloutConfig": {
"maximumPerMinute": "integer",
"exponentialRate": {
"baseRatePerMinute": "integer",
"incrementFactor": "double",
"rateIncreaseCriteria": {
"numberOfNotifiedThings": "integer",
"numberOfSucceededThings": "integer"
}
}
},
"abortConfig": {
"criteriaList": [
{
"failureType": "string",
"action": "string",
"thresholdPercentage": "double",
"minNumberOfExecutedThings": "integer"
}
]
},
"timeoutConfig": {
"inProgressTimeoutInMinutes": "long"
},
"tags": [
{
686
AWS IoT Developer Guide
CreateJob
"Key": "string",
"Value": "string"
}
]
}
cli-input-json fields
pattern: [^\\p{C}]+
687
AWS IoT Developer Guide
CreateJob
enum: CONTINUOUS |
SNAPSHOT
688
AWS IoT Developer Guide
CreateJob
enum: CANCEL
689
AWS IoT Developer Guide
CreateJob
Output
{
"jobArn": "string",
"jobId": "string",
"description": "string"
}
pattern: [a-zA-Z0-9_-]+
length- max:2028
pattern: [^\\p{C}]+
Errors
InvalidRequestException
690
AWS IoT Developer Guide
CreateKeysAndCertificate
ResourceNotFoundException
CreateKeysAndCertificate
Creates a 2048-bit RSA key pair and issues an X.509 certificate using the issued public key.
Note This is the only time AWS IoT issues the private key for this certificate, so it is important to keep it
in a secure location.
Synopsis
cli-input-json format
{
"setAsActive": "boolean"
}
cli-input-json fields
Output
{
"certificateArn": "string",
"certificateId": "string",
"certificatePem": "string",
"keyPair": {
"PublicKey": "string",
"PrivateKey": "string"
}
}
691
AWS IoT Developer Guide
CreateOTAUpdate
length- min:1
length- min:1
Errors
InvalidRequestException
CreateOTAUpdate
Creates an AWS IoT OTAUpdate on a target group of things or groups.
Synopsis
692
AWS IoT Developer Guide
CreateOTAUpdate
[--tags <value>] \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"otaUpdateId": "string",
"description": "string",
"targets": [
"string"
],
"targetSelection": "string",
"awsJobExecutionsRolloutConfig": {
"maximumPerMinute": "integer"
},
"files": [
{
"fileName": "string",
"fileVersion": "string",
"fileLocation": {
"stream": {
"streamId": "string",
"fileId": "integer"
},
"s3Location": {
"bucket": "string",
"key": "string",
"version": "string"
}
},
"codeSigning": {
"awsSignerJobId": "string",
"startSigningJobParameter": {
"signingProfileParameter": {
"certificateArn": "string",
"platform": "string",
"certificatePathOnDevice": "string"
},
"signingProfileName": "string",
"destination": {
"s3Destination": {
"bucket": "string",
"prefix": "string"
}
}
},
"customCodeSigning": {
"signature": {
"inlineDocument": "blob"
},
"certificateChain": {
"certificateName": "string",
"inlineDocument": "string"
},
"hashAlgorithm": "string",
"signatureAlgorithm": "string"
}
},
"attributes": {
"string": "string"
}
}
],
"roleArn": "string",
693
AWS IoT Developer Guide
CreateOTAUpdate
"additionalParameters": {
"string": "string"
},
"tags": [
{
"Key": "string",
"Value": "string"
}
]
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
pattern: [^\\p{C}]+
enum: CONTINUOUS |
SNAPSHOT
694
AWS IoT Developer Guide
CreateOTAUpdate
pattern: [a-zA-Z0-9_-]+
length- min:1
length- min:1
695
AWS IoT Developer Guide
CreateOTAUpdate
Output
{
"otaUpdateId": "string",
"awsIotJobId": "string",
"otaUpdateArn": "string",
"awsIotJobArn": "string",
696
AWS IoT Developer Guide
CreateOTAUpdate
"otaUpdateStatus": "string"
}
pattern: [a-zA-Z0-9_-]+
enum: CREATE_PENDING
| CREATE_IN_PROGRESS
| CREATE_COMPLETE |
CREATE_FAILED
Errors
InvalidRequestException
697
AWS IoT Developer Guide
CreatePolicy
CreatePolicy
Creates an AWS IoT policy.
The created policy is the default version for the policy. This operation creates a policy version with a
version identifier of 1 and sets 1 as the policy's default version.
Synopsis
cli-input-json format
{
"policyName": "string",
"policyDocument": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
Output
{
"policyName": "string",
"policyArn": "string",
"policyDocument": "string",
"policyVersionId": "string"
}
pattern: [w+=,.@-]+
698
AWS IoT Developer Guide
CreatePolicyVersion
pattern: [0-9]+
Errors
ResourceAlreadyExistsException
CreatePolicyVersion
Creates a new version of the specified AWS IoT policy. To update a policy, create a new policy
version. A managed policy can have up to five versions. If the policy has five versions, you must use
DeletePolicyVersion to delete an existing version before you create a new one.
Optionally, you can set the new version as the policy's default version. The default version is the
operative version (that is, the version that is in effect for the certificates to which the policy is attached).
Synopsis
cli-input-json format
{
"policyName": "string",
699
AWS IoT Developer Guide
CreatePolicyVersion
"policyDocument": "string",
"setAsDefault": "boolean"
}
cli-input-json fields
pattern: [w+=,.@-]+
Output
{
"policyArn": "string",
"policyDocument": "string",
"policyVersionId": "string",
"isDefaultVersion": "boolean"
}
pattern: [0-9]+
Errors
ResourceNotFoundException
700
AWS IoT Developer Guide
CreateRoleAlias
MalformedPolicyException
CreateRoleAlias
Creates a role alias.
Synopsis
cli-input-json format
{
"roleAlias": "string",
"roleArn": "string",
"credentialDurationSeconds": "integer"
}
cli-input-json fields
701
AWS IoT Developer Guide
CreateScheduledAudit
Output
{
"roleAlias": "string",
"roleAliasArn": "string"
}
pattern: [w=,@-]+
Errors
ResourceAlreadyExistsException
CreateScheduledAudit
Creates a scheduled audit that is run at a specified time interval.
Synopsis
702
AWS IoT Developer Guide
CreateScheduledAudit
cli-input-json format
{
"frequency": "string",
"dayOfMonth": "string",
"dayOfWeek": "string",
"targetCheckNames": [
"string"
],
"tags": [
{
"Key": "string",
"Value": "string"
}
],
"scheduledAuditName": "string"
}
cli-input-json fields
703
AWS IoT Developer Guide
CreateScheduledAudit
Output
{
"scheduledAuditArn": "string"
}
Errors
InvalidRequestException
704
AWS IoT Developer Guide
CreateSecurityProfile
LimitExceededException
CreateSecurityProfile
Creates a Device Defender security profile.
Synopsis
cli-input-json format
{
"securityProfileName": "string",
"securityProfileDescription": "string",
"behaviors": [
{
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
}
],
"alertTargets": {
"string": {
"alertTargetArn": "string",
"roleArn": "string"
}
},
"additionalMetricsToRetain": [
"string"
],
"tags": [
{
"Key": "string",
705
AWS IoT Developer Guide
CreateSecurityProfile
"Value": "string"
}
]
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
pattern: [a-zA-Z0-9:_-]+
706
AWS IoT Developer Guide
CreateSecurityProfile
707
AWS IoT Developer Guide
CreateSecurityProfile
Output
{
"securityProfileName": "string",
708
AWS IoT Developer Guide
CreateStream
"securityProfileArn": "string"
}
pattern: [a-zA-Z0-9:_-]+
Errors
InvalidRequestException
CreateStream
Creates a stream for delivering one or more large files in chunks over MQTT. A stream transports data
bytes in chunks or blocks packaged as MQTT messages from a source like S3. You can have one or more
files associated with a stream. The total size of a file associated with the stream cannot exceed more
than 2 MB. The stream will be created with version 0. If a stream is created with the same streamID
as a stream that existed and was deleted within last 90 days, we will resurrect that old stream by
incrementing the version by 1.
Synopsis
cli-input-json format
{
"streamId": "string",
"description": "string",
"files": [
709
AWS IoT Developer Guide
CreateStream
{
"fileId": "integer",
"s3Location": {
"bucket": "string",
"key": "string",
"version": "string"
}
}
],
"roleArn": "string",
"tags": [
{
"Key": "string",
"Value": "string"
}
]
}
cli-input-json fields
Name Type Description
pattern: [a-zA-Z0-9_-]+
length- max:2028
pattern: [^\\p{C}]+
member: StreamFile
length- min:1
length- min:1
710
AWS IoT Developer Guide
CreateStream
Output
{
"streamId": "string",
"streamArn": "string",
"description": "string",
"streamVersion": "integer"
}
pattern: [a-zA-Z0-9_-]+
length- max:2028
pattern: [^\\p{C}]+
Errors
InvalidRequestException
711
AWS IoT Developer Guide
CreateThing
ServiceUnavailableException
CreateThing
Creates a thing record in the registry. If this call is made multiple times using the same thing name
and configuration, the call will succeed. If this call is made with the same thing name but different
configuration a ResourceAlreadyExistsException is thrown.
Note
This is a control plane operation. See Authorization for information about authorizing control
plane actions.
Synopsis
cli-input-json format
{
"thingName": "string",
"thingTypeName": "string",
"attributePayload": {
"attributes": {
"string": "string"
},
"merge": "boolean"
},
"billingGroupName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
712
AWS IoT Developer Guide
CreateThing
\"attributes\":
{\"string1\":
\"string2\"}
\"attributes\":
{\"string1\":
\"string2\"}
pattern: [a-zA-Z0-9:_-]+
Output
{
"thingName": "string",
"thingArn": "string",
"thingId": "string"
}
pattern: [a-zA-Z0-9:_-]+
713
AWS IoT Developer Guide
CreateThingGroup
Errors
InvalidRequestException
CreateThingGroup
Create a thing group.
Note
This is a control plane operation. See Authorization for information about authorizing control
plane actions.
Synopsis
cli-input-json format
{
"thingGroupName": "string",
"parentGroupName": "string",
714
AWS IoT Developer Guide
CreateThingGroup
"thingGroupProperties": {
"thingGroupDescription": "string",
"attributePayload": {
"attributes": {
"string": "string"
},
"merge": "boolean"
}
},
"tags": [
{
"Key": "string",
"Value": "string"
}
]
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
length- max:2028
pattern: [\\p{Graph} ]*
\"attributes\":
{\"string1\":
\"string2\"}
715
AWS IoT Developer Guide
CreateThingGroup
Output
{
"thingGroupName": "string",
"thingGroupArn": "string",
"thingGroupId": "string"
}
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9-]+
Errors
InvalidRequestException
716
AWS IoT Developer Guide
CreateThingType
CreateThingType
Creates a new thing type.
Synopsis
cli-input-json format
{
"thingTypeName": "string",
"thingTypeProperties": {
"thingTypeDescription": "string",
"searchableAttributes": [
"string"
]
},
"tags": [
{
"Key": "string",
"Value": "string"
}
]
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
717
AWS IoT Developer Guide
CreateThingType
Output
{
"thingTypeName": "string",
"thingTypeArn": "string",
"thingTypeId": "string"
}
pattern: [a-zA-Z0-9:_-]+
Errors
InvalidRequestException
718
AWS IoT Developer Guide
CreateTopicRule
CreateTopicRule
Creates a rule. Creating rules is an administrator-level action. Any user who has permission to create
rules will be able to access data processed by the rule.
Synopsis
cli-input-json format
{
"ruleName": "string",
"topicRulePayload": {
"sql": "string",
"description": "string",
"actions": [
{
"dynamoDB": {
"tableName": "string",
"roleArn": "string",
"operation": "string",
"hashKeyField": "string",
"hashKeyValue": "string",
"hashKeyType": "string",
"rangeKeyField": "string",
"rangeKeyValue": "string",
"rangeKeyType": "string",
"payloadField": "string"
},
"dynamoDBv2": {
"roleArn": "string",
"putItem": {
"tableName": "string"
}
},
"lambda": {
"functionArn": "string"
},
"sns": {
"targetArn": "string",
"roleArn": "string",
"messageFormat": "string"
},
"sqs": {
"roleArn": "string",
"queueUrl": "string",
"useBase64": "boolean"
},
"kinesis": {
"roleArn": "string",
"streamName": "string",
"partitionKey": "string"
},
"republish": {
"roleArn": "string",
"topic": "string"
},
719
AWS IoT Developer Guide
CreateTopicRule
"s3": {
"roleArn": "string",
"bucketName": "string",
"key": "string",
"cannedAcl": "string"
},
"firehose": {
"roleArn": "string",
"deliveryStreamName": "string",
"separator": "string"
},
"cloudwatchMetric": {
"roleArn": "string",
"metricNamespace": "string",
"metricName": "string",
"metricValue": "string",
"metricUnit": "string",
"metricTimestamp": "string"
},
"cloudwatchAlarm": {
"roleArn": "string",
"alarmName": "string",
"stateReason": "string",
"stateValue": "string"
},
"elasticsearch": {
"roleArn": "string",
"endpoint": "string",
"index": "string",
"type": "string",
"id": "string"
},
"salesforce": {
"token": "string",
"url": "string"
},
"iotAnalytics": {
"channelArn": "string",
"channelName": "string",
"roleArn": "string"
},
"iotEvents": {
"inputName": "string",
"messageId": "string",
"roleArn": "string"
},
"stepFunctions": {
"executionNamePrefix": "string",
"stateMachineName": "string",
"roleArn": "string"
}
}
],
"ruleDisabled": "boolean",
"awsIotSqlVersion": "string",
"errorAction": {
"dynamoDB": {
"tableName": "string",
"roleArn": "string",
"operation": "string",
"hashKeyField": "string",
"hashKeyValue": "string",
"hashKeyType": "string",
"rangeKeyField": "string",
"rangeKeyValue": "string",
"rangeKeyType": "string",
720
AWS IoT Developer Guide
CreateTopicRule
"payloadField": "string"
},
"dynamoDBv2": {
"roleArn": "string",
"putItem": {
"tableName": "string"
}
},
"lambda": {
"functionArn": "string"
},
"sns": {
"targetArn": "string",
"roleArn": "string",
"messageFormat": "string"
},
"sqs": {
"roleArn": "string",
"queueUrl": "string",
"useBase64": "boolean"
},
"kinesis": {
"roleArn": "string",
"streamName": "string",
"partitionKey": "string"
},
"republish": {
"roleArn": "string",
"topic": "string"
},
"s3": {
"roleArn": "string",
"bucketName": "string",
"key": "string",
"cannedAcl": "string"
},
"firehose": {
"roleArn": "string",
"deliveryStreamName": "string",
"separator": "string"
},
"cloudwatchMetric": {
"roleArn": "string",
"metricNamespace": "string",
"metricName": "string",
"metricValue": "string",
"metricUnit": "string",
"metricTimestamp": "string"
},
"cloudwatchAlarm": {
"roleArn": "string",
"alarmName": "string",
"stateReason": "string",
"stateValue": "string"
},
"elasticsearch": {
"roleArn": "string",
"endpoint": "string",
"index": "string",
"type": "string",
"id": "string"
},
"salesforce": {
"token": "string",
"url": "string"
},
721
AWS IoT Developer Guide
CreateTopicRule
"iotAnalytics": {
"channelArn": "string",
"channelName": "string",
"roleArn": "string"
},
"iotEvents": {
"inputName": "string",
"messageId": "string",
"roleArn": "string"
},
"stepFunctions": {
"executionNamePrefix": "string",
"stateMachineName": "string",
"roleArn": "string"
}
}
},
"tags": "string"
}
cli-input-json fields
pattern: ^[a-zA-Z0-9_]+$
722
AWS IoT Developer Guide
CreateTopicRule
{ "dynamoDBv2":
{ "roleArn":
"aws:iam:12341251:my-
role" "putItem":
{ "tableName": "my-
table" } } }
723
AWS IoT Developer Guide
CreateTopicRule
724
AWS IoT Developer Guide
CreateTopicRule
725
AWS IoT Developer Guide
CreateTopicRule
726
AWS IoT Developer Guide
CreateTopicRule
727
AWS IoT Developer Guide
CreateTopicRule
{ "dynamoDBv2":
{ "roleArn":
"aws:iam:12341251:my-
role" "putItem":
{ "tableName": "my-
table" } } }
728
AWS IoT Developer Guide
CreateTopicRule
729
AWS IoT Developer Guide
CreateTopicRule
730
AWS IoT Developer Guide
CreateTopicRule
731
AWS IoT Developer Guide
CreateTopicRule
732
AWS IoT Developer Guide
DeleteAccountAuditConfiguration
Output
None
Errors
SqlParseException
A conflicting resource update exception. This exception is thrown when two pending updates cause a
conflict.
DeleteAccountAuditConfiguration
Restores the default settings for Device Defender audits for this account. Any configuration data you
entered is deleted and all audit checks are reset to disabled.
Synopsis
cli-input-json format
733
AWS IoT Developer Guide
DeleteAuthorizer
{
"deleteScheduledAudits": "boolean"
}
cli-input-json fields
Output
None
Errors
InvalidRequestException
DeleteAuthorizer
Deletes an authorizer.
Synopsis
cli-input-json format
{
"authorizerName": "string"
}
cli-input-json fields
pattern: [w=,@-]+
734
AWS IoT Developer Guide
DeleteBillingGroup
Output
None
Errors
DeleteConflictException
You can't delete the resource because it is attached to one or more resources.
ResourceNotFoundException
DeleteBillingGroup
Deletes the billing group.
Synopsis
cli-input-json format
{
"billingGroupName": "string",
"expectedVersion": "long"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
735
AWS IoT Developer Guide
DeleteCACertificate
Output
None
Errors
InvalidRequestException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
DeleteCACertificate
Deletes a registered CA certificate.
Synopsis
cli-input-json format
{
"certificateId": "string"
}
cli-input-json fields
736
AWS IoT Developer Guide
DeleteCertificate
Output
None
Errors
InvalidRequestException
DeleteCertificate
Deletes the specified certificate.
A certificate cannot be deleted if it has a policy or IoT thing attached to it or if its status is set to ACTIVE.
To delete a certificate, first use the DetachPrincipalPolicy API to detach all policies. Next, use the
UpdateCertificate API to set the certificate to the INACTIVE status.
Synopsis
cli-input-json format
{
"certificateId": "string",
"forceDelete": "boolean"
}
737
AWS IoT Developer Guide
DeleteDynamicThingGroup
cli-input-json fields
Output
None
Errors
CertificateStateException
You can't delete the resource because it is attached to one or more resources.
InvalidRequestException
DeleteDynamicThingGroup
Deletes a dynamic thing group.
Synopsis
738
AWS IoT Developer Guide
DeleteJob
cli-input-json format
{
"thingGroupName": "string",
"expectedVersion": "long"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
None
Errors
InvalidRequestException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
DeleteJob
Deletes a job and its related job executions.
Deleting a job may take time, depending on the number of job executions created for the job
and various other factors. While the job is being deleted, the status of the job will be shown
as "DELETION_IN_PROGRESS". Attempting to delete or cancel a job whose status is already
"DELETION_IN_PROGRESS" will result in an error.
Only 10 jobs may have status "DELETION_IN_PROGRESS" at the same time, or a LimitExceededException
will occur.
Synopsis
739
AWS IoT Developer Guide
DeleteJob
--job-id <value> \
[--force | --no-force] \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"jobId": "string",
"force": "boolean"
}
cli-input-json fields
Output
None
Errors
InvalidRequestException
740
AWS IoT Developer Guide
DeleteJobExecution
InvalidStateTransitionException
An update attempted to change the job execution to a state that is invalid because of the job
execution's current state (for example, an attempt to change a request in state SUCCESS to state
IN_PROGRESS). In this case, the body of the error message also contains the executionState field.
ResourceNotFoundException
DeleteJobExecution
Deletes a job execution.
Synopsis
cli-input-json format
{
"jobId": "string",
"thingName": "string",
"executionNumber": "long",
"force": "boolean"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
741
AWS IoT Developer Guide
DeleteJobExecution
Output
None
Errors
InvalidRequestException
An update attempted to change the job execution to a state that is invalid because of the job
execution's current state (for example, an attempt to change a request in state SUCCESS to state
IN_PROGRESS). In this case, the body of the error message also contains the executionState field.
ResourceNotFoundException
742
AWS IoT Developer Guide
DeleteOTAUpdate
ServiceUnavailableException
DeleteOTAUpdate
Delete an OTA update.
Synopsis
cli-input-json format
{
"otaUpdateId": "string",
"deleteStream": "boolean",
"forceDeleteAWSJob": "boolean"
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
Output
None
Errors
InvalidRequestException
743
AWS IoT Developer Guide
DeletePolicy
ThrottlingException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
DeletePolicy
Deletes the specified policy.
To delete a policy, use the DeletePolicyVersion API to delete all non-default versions of the policy; use
the DetachPrincipalPolicy API to detach the policy from any certificate; and then use the DeletePolicy API
to delete the policy.
When a policy is deleted using DeletePolicy, its default version is deleted with it.
Synopsis
cli-input-json format
{
"policyName": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
Output
None
744
AWS IoT Developer Guide
DeletePolicyVersion
Errors
DeleteConflictException
You can't delete the resource because it is attached to one or more resources.
ResourceNotFoundException
DeletePolicyVersion
Deletes the specified version of the specified policy. You cannot delete the default version of a policy
using this API. To delete the default version of a policy, use DeletePolicy. To find out which version of a
policy is marked as the default version, use ListPolicyVersions.
Synopsis
cli-input-json format
{
"policyName": "string",
"policyVersionId": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
745
AWS IoT Developer Guide
DeleteRegistrationCode
pattern: [0-9]+
Output
None
Errors
DeleteConflictException
You can't delete the resource because it is attached to one or more resources.
ResourceNotFoundException
DeleteRegistrationCode
Deletes a CA certificate registration code.
Synopsis
cli-input-json format
{
}
Output
None
746
AWS IoT Developer Guide
DeleteRoleAlias
Errors
ThrottlingException
DeleteRoleAlias
Deletes a role alias
Synopsis
cli-input-json format
{
"roleAlias": "string"
}
cli-input-json fields
pattern: [w=,@-]+
Output
None
Errors
DeleteConflictException
You can't delete the resource because it is attached to one or more resources.
747
AWS IoT Developer Guide
DeleteScheduledAudit
InvalidRequestException
DeleteScheduledAudit
Deletes a scheduled audit.
Synopsis
cli-input-json format
{
"scheduledAuditName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
Output
None
Errors
InvalidRequestException
748
AWS IoT Developer Guide
DeleteSecurityProfile
ResourceNotFoundException
DeleteSecurityProfile
Deletes a Device Defender security profile.
Synopsis
cli-input-json format
{
"securityProfileName": "string",
"expectedVersion": "long"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
None
Errors
InvalidRequestException
749
AWS IoT Developer Guide
DeleteStream
ThrottlingException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
DeleteStream
Deletes a stream.
Synopsis
cli-input-json format
{
"streamId": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
Output
None
Errors
ResourceNotFoundException
You can't delete the resource because it is attached to one or more resources.
InvalidRequestException
750
AWS IoT Developer Guide
DeleteThing
ThrottlingException
DeleteThing
Deletes the specified thing. Returns successfully with no error if the deletion is successful or you specify a
thing that doesn't exist.
Synopsis
cli-input-json format
{
"thingName": "string",
"expectedVersion": "long"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
None
751
AWS IoT Developer Guide
DeleteThingGroup
Errors
ResourceNotFoundException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
InvalidRequestException
DeleteThingGroup
Deletes a thing group.
Synopsis
cli-input-json format
{
"thingGroupName": "string",
"expectedVersion": "long"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
752
AWS IoT Developer Guide
DeleteThingShadow
Output
None
Errors
InvalidRequestException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
DeleteThingShadow
Deletes the shadow for the specified thing.
For more information, see DeleteThingShadow in the AWS IoT Developer Guide.
Synopsis
cli-input-json format
{
"thingName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
753
AWS IoT Developer Guide
DeleteThingType
Output
{
"payload": "blob"
}
Errors
ResourceNotFoundException
DeleteThingType
Deletes the specified thing type. You cannot delete a thing type if it has things associated with it.
To delete a thing type, first mark it as deprecated by calling DeprecateThingType, then remove any
associated things by calling UpdateThing to change the thing type on any associated thing, and finally
use DeleteThingType to delete the thing type.
Synopsis
754
AWS IoT Developer Guide
DeleteTopicRule
[--generate-cli-skeleton]
cli-input-json format
{
"thingTypeName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
None
Errors
ResourceNotFoundException
DeleteTopicRule
Deletes the rule.
Synopsis
755
AWS IoT Developer Guide
DeleteV2LoggingLevel
[--generate-cli-skeleton]
cli-input-json format
{
"ruleName": "string"
}
cli-input-json fields
pattern: ^[a-zA-Z0-9_]+$
Output
None
Errors
InternalException
A conflicting resource update exception. This exception is thrown when two pending updates cause a
conflict.
DeleteV2LoggingLevel
Deletes a logging level.
Synopsis
cli-input-json format
756
AWS IoT Developer Guide
DeprecateThingType
{
"targetType": "string",
"targetName": "string"
}
cli-input-json fields
Output
None
Errors
InternalException
DeprecateThingType
Deprecates a thing type. You can not associate new things with deprecated thing type.
Synopsis
cli-input-json format
{
"thingTypeName": "string",
"undoDeprecate": "boolean"
}
757
AWS IoT Developer Guide
DescribeAccountAuditConfiguration
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
None
Errors
ResourceNotFoundException
DescribeAccountAuditConfiguration
Gets information about the Device Defender audit settings for this account. Settings include how audit
notifications are sent and which audit checks are enabled or disabled.
Synopsis
cli-input-json format
758
AWS IoT Developer Guide
DescribeAccountAuditConfiguration
{
}
Output
{
"roleArn": "string",
"auditNotificationTargetConfigurations": {
"string": {
"targetArn": "string",
"roleArn": "string",
"enabled": "boolean"
}
},
"auditCheckConfigurations": {
"string": {
"enabled": "boolean"
}
}
}
auditNotificationTargetConfigurations
map Information about the targets
to which audit notifications are
sent for this account.
Errors
759
AWS IoT Developer Guide
DescribeAuditTask
ThrottlingException
DescribeAuditTask
Gets information about a Device Defender audit.
Synopsis
cli-input-json format
{
"taskId": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9-]+
Output
{
"taskStatus": "string",
"taskType": "string",
"taskStartTime": "timestamp",
"taskStatistics": {
"totalChecks": "integer",
"inProgressChecks": "integer",
"waitingForDataCollectionChecks": "integer",
"compliantChecks": "integer",
"nonCompliantChecks": "integer",
"failedChecks": "integer",
"canceledChecks": "integer"
},
"scheduledAuditName": "string",
"auditDetails": {
"string": {
"checkRunStatus": "string",
"checkCompliant": "boolean",
"totalResourcesCount": "long",
"nonCompliantResourcesCount": "long",
760
AWS IoT Developer Guide
DescribeAuditTask
"errorCode": "string",
"message": "string"
}
}
}
enum: IN_PROGRESS |
COMPLETED | FAILED |
CANCELED
enum:
ON_DEMAND_AUDIT_TASK |
SCHEDULED_AUDIT_TASK
761
AWS IoT Developer Guide
DescribeAuthorizer
enum: IN_PROGRESS |
WAITING_FOR_DATA_COLLECTION
| CANCELED |
COMPLETED_COMPLIANT |
COMPLETED_NON_COMPLIANT
| FAILED
Errors
InvalidRequestException
DescribeAuthorizer
Describes an authorizer.
762
AWS IoT Developer Guide
DescribeAuthorizer
Synopsis
cli-input-json format
{
"authorizerName": "string"
}
cli-input-json fields
pattern: [w=,@-]+
Output
{
"authorizerDescription": {
"authorizerName": "string",
"authorizerArn": "string",
"authorizerFunctionArn": "string",
"tokenKeyName": "string",
"tokenSigningPublicKeys": {
"string": "string"
},
"status": "string",
"creationDate": "timestamp",
"lastModifiedDate": "timestamp"
}
}
pattern: [w=,@-]+
763
AWS IoT Developer Guide
DescribeBillingGroup
pattern: [a-zA-Z0-9_-]+
Errors
ResourceNotFoundException
DescribeBillingGroup
Returns information about a billing group.
Synopsis
cli-input-json format
764
AWS IoT Developer Guide
DescribeBillingGroup
"billingGroupName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"billingGroupName": "string",
"billingGroupId": "string",
"billingGroupArn": "string",
"version": "long",
"billingGroupProperties": {
"billingGroupDescription": "string"
},
"billingGroupMetadata": {
"creationDate": "timestamp"
}
}
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9-]+
pattern: [\\p{Graph} ]*
765
AWS IoT Developer Guide
DescribeCACertificate
Errors
InvalidRequestException
DescribeCACertificate
Describes a registered CA certificate.
Synopsis
cli-input-json format
{
"certificateId": "string"
}
cli-input-json fields
pattern: (0x)?[a-fA-F0-9]+
Output
{
"certificateDescription": {
"certificateArn": "string",
"certificateId": "string",
"status": "string",
"certificatePem": "string",
766
AWS IoT Developer Guide
DescribeCACertificate
"ownedBy": "string",
"creationDate": "timestamp",
"autoRegistrationStatus": "string",
"lastModifiedDate": "timestamp",
"customerVersion": "integer",
"generationId": "string",
"validity": {
"notBefore": "timestamp",
"notAfter": "timestamp"
}
},
"registrationConfig": {
"templateBody": "string",
"roleArn": "string"
}
}
pattern: (0x)?[a-fA-F0-9]+
pattern: [0-9]+
767
AWS IoT Developer Guide
DescribeCertificate
Errors
InvalidRequestException
DescribeCertificate
Gets information about the specified certificate.
Synopsis
cli-input-json format
768
AWS IoT Developer Guide
DescribeCertificate
"certificateId": "string"
}
cli-input-json fields
Output
{
"certificateDescription": {
"certificateArn": "string",
"certificateId": "string",
"caCertificateId": "string",
"status": "string",
"certificatePem": "string",
"ownedBy": "string",
"previousOwnedBy": "string",
"creationDate": "timestamp",
"lastModifiedDate": "timestamp",
"customerVersion": "integer",
"transferData": {
"transferMessage": "string",
"rejectReason": "string",
"transferDate": "timestamp",
"acceptDate": "timestamp",
"rejectDate": "timestamp"
},
"generationId": "string",
"validity": {
"notBefore": "timestamp",
"notAfter": "timestamp"
}
}
}
pattern: (0x)?[a-fA-F0-9]+
769
AWS IoT Developer Guide
DescribeCertificate
pattern: [0-9]+
length- max:128
770
AWS IoT Developer Guide
DescribeDefaultAuthorizer
Errors
InvalidRequestException
DescribeDefaultAuthorizer
Describes the default authorizer.
Synopsis
cli-input-json format
{
}
Output
{
"authorizerDescription": {
"authorizerName": "string",
"authorizerArn": "string",
"authorizerFunctionArn": "string",
"tokenKeyName": "string",
"tokenSigningPublicKeys": {
"string": "string"
},
771
AWS IoT Developer Guide
DescribeDefaultAuthorizer
"status": "string",
"creationDate": "timestamp",
"lastModifiedDate": "timestamp"
}
}
pattern: [w=,@-]+
pattern: [a-zA-Z0-9_-]+
Errors
ResourceNotFoundException
772
AWS IoT Developer Guide
DescribeEndpoint
ServiceUnavailableException
DescribeEndpoint
Returns a unique endpoint specific to the AWS account making the call.
Synopsis
cli-input-json format
{
"endpointType": "string"
}
cli-input-json fields
• iot:Data - Returns a
VeriSign signed data endpoint.
• iot:Data-ATS - Returns an
ATS signed data endpoint.
• iot:CredentialProvider
- Returns an AWS IoT
credentials provider API
endpoint.
Output
{
"endpointAddress": "string"
}
773
AWS IoT Developer Guide
DescribeEventConfigurations
Errors
InternalFailureException
DescribeEventConfigurations
Describes event configurations.
Synopsis
cli-input-json format
{
}
Output
{
"eventConfigurations": {
"string": {
"Enabled": "boolean"
}
},
"creationDate": "timestamp",
"lastModifiedDate": "timestamp"
}
774
AWS IoT Developer Guide
DescribeIndex
Errors
InternalFailureException
DescribeIndex
Describes a search index.
Synopsis
cli-input-json format
{
"indexName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"indexName": "string",
"indexStatus": "string",
"schema": "string"
775
AWS IoT Developer Guide
DescribeIndex
pattern: [a-zA-Z0-9:_-]+
Errors
InvalidRequestException
776
AWS IoT Developer Guide
DescribeJob
DescribeJob
Describes a job.
Synopsis
cli-input-json format
{
"jobId": "string"
}
cli-input-json fields
Output
{
"documentSource": "string",
"job": {
"jobArn": "string",
"jobId": "string",
"targetSelection": "string",
"status": "string",
"forceCanceled": "boolean",
"reasonCode": "string",
"comment": "string",
"targets": [
"string"
],
"description": "string",
"presignedUrlConfig": {
"roleArn": "string",
"expiresInSec": "long"
},
"jobExecutionsRolloutConfig": {
"maximumPerMinute": "integer",
"exponentialRate": {
"baseRatePerMinute": "integer",
"incrementFactor": "double",
"rateIncreaseCriteria": {
"numberOfNotifiedThings": "integer",
"numberOfSucceededThings": "integer"
}
}
},
"abortConfig": {
"criteriaList": [
777
AWS IoT Developer Guide
DescribeJob
{
"failureType": "string",
"action": "string",
"thresholdPercentage": "double",
"minNumberOfExecutedThings": "integer"
}
]
},
"createdAt": "timestamp",
"lastUpdatedAt": "timestamp",
"completedAt": "timestamp",
"jobProcessDetails": {
"processingTargets": [
"string"
],
"numberOfCanceledThings": "integer",
"numberOfSucceededThings": "integer",
"numberOfFailedThings": "integer",
"numberOfRejectedThings": "integer",
"numberOfQueuedThings": "integer",
"numberOfInProgressThings": "integer",
"numberOfRemovedThings": "integer",
"numberOfTimedOutThings": "integer"
},
"timeoutConfig": {
"inProgressTimeoutInMinutes": "long"
}
}
}
778
AWS IoT Developer Guide
DescribeJob
enum: CONTINUOUS |
SNAPSHOT
enum: IN_PROGRESS |
CANCELED | COMPLETED |
DELETION_IN_PROGRESS
pattern: [^\\p{C}]+
pattern: [^\\p{C}]+
779
AWS IoT Developer Guide
DescribeJob
780
AWS IoT Developer Guide
DescribeJob
enum: CANCEL
781
AWS IoT Developer Guide
DescribeJobExecution
Errors
InvalidRequestException
DescribeJobExecution
Gets details of a job execution.
782
AWS IoT Developer Guide
DescribeJobExecution
Synopsis
cli-input-json format
{
"jobId": "string",
"thingName": "string",
"includeJobDocument": "boolean",
"executionNumber": "long"
}
cli-input-json fields
Output
{
"execution": {
"jobId": "string",
"thingName": "string",
"status": "string",
"statusDetails": {
"string": "string"
},
"queuedAt": "long",
"startedAt": "long",
"lastUpdatedAt": "long",
"approximateSecondsBeforeTimedOut": "long",
"versionNumber": "long",
"executionNumber": "long",
"jobDocument": "string"
783
AWS IoT Developer Guide
DescribeJobExecution
}
}
pattern: [a-zA-Z0-9:_-]+
approximateSecondsBeforeTimedOut
long The estimated number of
seconds that remain before
the job execution status will be
changed to TIMED_OUT. The
actual job execution timeout
can occur up to 60 seconds later
than the estimated duration.
784
AWS IoT Developer Guide
DescribeJobExecution
Errors
InvalidRequestException
DescribeJobExecution
Describes a job execution.
Synopsis
cli-input-json format
{
"jobId": "string",
"thingName": "string",
"executionNumber": "long"
}
785
AWS IoT Developer Guide
DescribeJobExecution
cli-input-json fields
Name Type Description
pattern: [a-zA-Z0-9:_-]+
Output
{
"execution": {
"jobId": "string",
"status": "string",
"forceCanceled": "boolean",
"statusDetails": {
"detailsMap": {
"string": "string"
}
},
"thingArn": "string",
"queuedAt": "timestamp",
"startedAt": "timestamp",
"lastUpdatedAt": "timestamp",
"executionNumber": "long",
"versionNumber": "long",
"approximateSecondsBeforeTimedOut": "long"
}
}
786
AWS IoT Developer Guide
DescribeJobExecution
approximateSecondsBeforeTimedOut
long The estimated number of
seconds that remain before
the job execution status will
be changed to TIMED_OUT.
The timeout interval can be
anywhere between 1 minute and
7 days (1 to 10080 minutes). The
actual job execution timeout
can occur up to 60 seconds later
than the estimated duration.
This value will not be included if
the job execution has reached a
terminal status.
787
AWS IoT Developer Guide
DescribeRoleAlias
Errors
InvalidRequestException
DescribeRoleAlias
Describes a role alias.
Synopsis
cli-input-json format
{
"roleAlias": "string"
}
cli-input-json fields
pattern: [w=,@-]+
Output
{
"roleAliasDescription": {
"roleAlias": "string",
"roleAliasArn": "string",
"roleArn": "string",
"owner": "string",
"credentialDurationSeconds": "integer",
"creationDate": "timestamp",
"lastModifiedDate": "timestamp"
788
AWS IoT Developer Guide
DescribeRoleAlias
}
}
pattern: [w=,@-]+
pattern: [0-9]+
Errors
InvalidRequestException
789
AWS IoT Developer Guide
DescribeScheduledAudit
DescribeScheduledAudit
Gets information about a scheduled audit.
Synopsis
cli-input-json format
{
"scheduledAuditName": "string"
}
cli-input-json fields
Name Type Description
Output
{
"frequency": "string",
"dayOfMonth": "string",
"dayOfWeek": "string",
"targetCheckNames": [
"string"
],
"scheduledAuditName": "string",
"scheduledAuditArn": "string"
}
790
AWS IoT Developer Guide
DescribeSecurityProfile
pattern: [a-zA-Z0-9_-]+
Errors
InvalidRequestException
DescribeSecurityProfile
Gets information about a Device Defender security profile.
Synopsis
791
AWS IoT Developer Guide
DescribeSecurityProfile
--security-profile-name <value> \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"securityProfileName": "string"
}
cli-input-json fields
Output
{
"securityProfileName": "string",
"securityProfileArn": "string",
"securityProfileDescription": "string",
"behaviors": [
{
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
}
],
"alertTargets": {
"string": {
"alertTargetArn": "string",
"roleArn": "string"
}
},
"additionalMetricsToRetain": [
"string"
],
"version": "long",
"creationDate": "timestamp",
792
AWS IoT Developer Guide
DescribeSecurityProfile
"lastModifiedDate": "timestamp"
}
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
793
AWS IoT Developer Guide
DescribeSecurityProfile
794
AWS IoT Developer Guide
DescribeSecurityProfile
Errors
InvalidRequestException
795
AWS IoT Developer Guide
DescribeStream
ResourceNotFoundException
DescribeStream
Gets information about a stream.
Synopsis
cli-input-json format
{
"streamId": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
Output
{
"streamInfo": {
"streamId": "string",
"streamArn": "string",
"streamVersion": "integer",
"description": "string",
"files": [
{
"fileId": "integer",
"s3Location": {
"bucket": "string",
"key": "string",
"version": "string"
}
}
],
796
AWS IoT Developer Guide
DescribeStream
"createdAt": "timestamp",
"lastUpdatedAt": "timestamp",
"roleArn": "string"
}
}
pattern: [a-zA-Z0-9_-]+
length- max:2028
pattern: [^\\p{C}]+
member: StreamFile
length- min:1
length- min:1
Errors
797
AWS IoT Developer Guide
DescribeThing
InvalidRequestException
DescribeThing
Gets information about the specified thing.
Synopsis
cli-input-json format
{
"thingName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"defaultClientId": "string",
"thingName": "string",
"thingId": "string",
"thingArn": "string",
"thingTypeName": "string",
"attributes": {
798
AWS IoT Developer Guide
DescribeThing
"string": "string"
},
"version": "long",
"billingGroupName": "string"
}
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
Errors
ResourceNotFoundException
799
AWS IoT Developer Guide
DescribeThingGroup
ThrottlingException
DescribeThingGroup
Describe a thing group.
Synopsis
cli-input-json format
{
"thingGroupName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"thingGroupName": "string",
"thingGroupId": "string",
"thingGroupArn": "string",
"version": "long",
"thingGroupProperties": {
"thingGroupDescription": "string",
"attributePayload": {
"attributes": {
"string": "string"
},
"merge": "boolean"
}
800
AWS IoT Developer Guide
DescribeThingGroup
},
"thingGroupMetadata": {
"parentGroupName": "string",
"rootToParentThingGroups": [
{
"groupName": "string",
"groupArn": "string"
}
],
"creationDate": "timestamp"
},
"indexName": "string",
"queryString": "string",
"queryVersion": "string",
"status": "string"
}
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9-]+
length- max:2028
pattern: [\\p{Graph} ]*
\"attributes\":
{\"string1\":
\"string2\"}
801
AWS IoT Developer Guide
DescribeThingGroup
pattern: [a-zA-Z0-9:_-]+
member: GroupNameAndArn
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
Errors
InvalidRequestException
802
AWS IoT Developer Guide
DescribeThingRegistrationTask
ThrottlingException
DescribeThingRegistrationTask
Describes a bulk thing provisioning task.
Synopsis
cli-input-json format
{
"taskId": "string"
}
cli-input-json fields
length- max:40
Output
{
"taskId": "string",
"creationDate": "timestamp",
"lastModifiedDate": "timestamp",
"templateBody": "string",
"inputFileBucket": "string",
"inputFileKey": "string",
"roleArn": "string",
"status": "string",
"message": "string",
"successCount": "integer",
"failureCount": "integer",
"percentageProgress": "integer"
}
803
AWS IoT Developer Guide
DescribeThingRegistrationTask
pattern: [a-zA-Z0-9._-]+
pattern: [a-zA-Z0-9!_.*'()-/]+
length- max:2048
Errors
InvalidRequestException
804
AWS IoT Developer Guide
DescribeThingType
InternalFailureException
DescribeThingType
Gets information about the specified thing type.
Synopsis
cli-input-json format
{
"thingTypeName": "string"
}
cli-input-json fields
Name Type Description
pattern: [a-zA-Z0-9:_-]+
Output
{
"thingTypeName": "string",
"thingTypeId": "string",
"thingTypeArn": "string",
"thingTypeProperties": {
"thingTypeDescription": "string",
"searchableAttributes": [
"string"
]
},
"thingTypeMetadata": {
"deprecated": "boolean",
"deprecationDate": "timestamp",
"creationDate": "timestamp"
}
}
805
AWS IoT Developer Guide
DescribeThingType
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
Errors
ResourceNotFoundException
806
AWS IoT Developer Guide
DetachPolicy
UnauthorizedException
DetachPolicy
Detaches a policy from the specified target.
Synopsis
cli-input-json format
{
"policyName": "string",
"target": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
Output
None
Errors
InvalidRequestException
807
AWS IoT Developer Guide
DetachPrincipalPolicy
UnauthorizedException
DetachPrincipalPolicy
Removes the specified policy from the specified certificate.
Synopsis
cli-input-json format
{
"policyName": "string",
"principal": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
Output
None
808
AWS IoT Developer Guide
DetachSecurityProfile
Errors
ResourceNotFoundException
DetachSecurityProfile
Disassociates a Device Defender security profile from a thing group or from this account.
Synopsis
cli-input-json format
{
"securityProfileName": "string",
"securityProfileTargetArn": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
809
AWS IoT Developer Guide
DetachThingPrincipal
None
Errors
InvalidRequestException
DetachThingPrincipal
Detaches the specified principal from the specified thing. A principal can be X.509 certificates, IAM users,
groups, and roles, Amazon Cognito identities or federated identities.
Note
This call is asynchronous. It might take several seconds for the detachment to propagate.
Synopsis
cli-input-json format
{
"thingName": "string",
"principal": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
810
AWS IoT Developer Guide
DisableTopicRule
Output
None
Errors
ResourceNotFoundException
DisableTopicRule
Disables the rule.
Synopsis
cli-input-json format
{
"ruleName": "string"
}
cli-input-json fields
pattern: ^[a-zA-Z0-9_]+$
Output
None
811
AWS IoT Developer Guide
EnableTopicRule
Errors
InternalException
A conflicting resource update exception. This exception is thrown when two pending updates cause a
conflict.
EnableTopicRule
Enables the rule.
Synopsis
cli-input-json format
{
"ruleName": "string"
}
cli-input-json fields
pattern: ^[a-zA-Z0-9_]+$
Output
None
Errors
InternalException
812
AWS IoT Developer Guide
GetEffectivePolicies
InvalidRequestException
A conflicting resource update exception. This exception is thrown when two pending updates cause a
conflict.
GetEffectivePolicies
Gets a list of the policies that have an effect on the authorization behavior of the specified device when it
connects to the AWS IoT device gateway.
Synopsis
cli-input-json format
{
"principal": "string",
"cognitoIdentityPoolId": "string",
"thingName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"effectivePolicies": [
{
813
AWS IoT Developer Guide
GetIndexingConfiguration
"policyName": "string",
"policyArn": "string",
"policyDocument": "string"
}
]
}
member: EffectivePolicy
pattern: [w+=,.@-]+
Errors
ResourceNotFoundException
GetIndexingConfiguration
Gets the search configuration.
Synopsis
814
AWS IoT Developer Guide
GetIndexingConfiguration
cli-input-json format
{
}
Output
{
"thingIndexingConfiguration": {
"thingIndexingMode": "string",
"thingConnectivityIndexingMode": "string"
},
"thingGroupIndexingConfiguration": {
"thingGroupIndexingMode": "string"
}
}
815
AWS IoT Developer Guide
GetJobDocument
enum: OFF | ON
Errors
InvalidRequestException
GetJobDocument
Gets a job document.
Synopsis
cli-input-json format
{
"jobId": "string"
}
cli-input-json fields
Output
{
"document": "string"
816
AWS IoT Developer Guide
GetLoggingOptions
length- max:32768
Errors
InvalidRequestException
GetLoggingOptions
Gets the logging options.
Synopsis
cli-input-json format
{
}
Output
{
"roleArn": "string",
"logLevel": "string"
}
817
AWS IoT Developer Guide
GetOTAUpdate
Errors
InternalException
GetOTAUpdate
Gets an OTA update.
Synopsis
cli-input-json format
{
"otaUpdateId": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
Output
{
"otaUpdateInfo": {
"otaUpdateId": "string",
"otaUpdateArn": "string",
"creationDate": "timestamp",
818
AWS IoT Developer Guide
GetOTAUpdate
"lastModifiedDate": "timestamp",
"description": "string",
"targets": [
"string"
],
"awsJobExecutionsRolloutConfig": {
"maximumPerMinute": "integer"
},
"targetSelection": "string",
"otaUpdateFiles": [
{
"fileName": "string",
"fileVersion": "string",
"fileLocation": {
"stream": {
"streamId": "string",
"fileId": "integer"
},
"s3Location": {
"bucket": "string",
"key": "string",
"version": "string"
}
},
"codeSigning": {
"awsSignerJobId": "string",
"startSigningJobParameter": {
"signingProfileParameter": {
"certificateArn": "string",
"platform": "string",
"certificatePathOnDevice": "string"
},
"signingProfileName": "string",
"destination": {
"s3Destination": {
"bucket": "string",
"prefix": "string"
}
}
},
"customCodeSigning": {
"signature": {
"inlineDocument": "blob"
},
"certificateChain": {
"certificateName": "string",
"inlineDocument": "string"
},
"hashAlgorithm": "string",
"signatureAlgorithm": "string"
}
},
"attributes": {
"string": "string"
}
}
],
"otaUpdateStatus": "string",
"awsIotJobId": "string",
"awsIotJobArn": "string",
"errorInfo": {
"code": "string",
"message": "string"
},
"additionalParameters": {
"string": "string"
819
AWS IoT Developer Guide
GetOTAUpdate
}
}
}
pattern: [a-zA-Z0-9_-]+
length- max:2028
pattern: [^\\p{C}]+
member: Target
enum: CONTINUOUS |
SNAPSHOT
820
AWS IoT Developer Guide
GetOTAUpdate
pattern: [a-zA-Z0-9_-]+
length- min:1
length- min:1
821
AWS IoT Developer Guide
GetOTAUpdate
enum: CREATE_PENDING
| CREATE_IN_PROGRESS
| CREATE_COMPLETE |
CREATE_FAILED
822
AWS IoT Developer Guide
GetPendingJobExecutions
Errors
InvalidRequestException
GetPendingJobExecutions
Gets the list of all jobs for a thing that are not in a terminal status.
Synopsis
cli-input-json format
{
"thingName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"inProgressJobs": [
{
"jobId": "string",
823
AWS IoT Developer Guide
GetPendingJobExecutions
"queuedAt": "long",
"startedAt": "long",
"lastUpdatedAt": "long",
"versionNumber": "long",
"executionNumber": "long"
}
],
"queuedJobs": [
{
"jobId": "string",
"queuedAt": "long",
"startedAt": "long",
"lastUpdatedAt": "long",
"versionNumber": "long",
"executionNumber": "long"
}
]
}
824
AWS IoT Developer Guide
GetPolicy
Errors
InvalidRequestException
GetPolicy
Gets information about the specified policy with the policy document of the default version.
Synopsis
825
AWS IoT Developer Guide
GetPolicy
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"policyName": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
Output
{
"policyName": "string",
"policyArn": "string",
"policyDocument": "string",
"defaultVersionId": "string",
"creationDate": "timestamp",
"lastModifiedDate": "timestamp",
"generationId": "string"
}
pattern: [w+=,.@-]+
pattern: [0-9]+
Errors
826
AWS IoT Developer Guide
GetPolicyVersion
ResourceNotFoundException
GetPolicyVersion
Gets information about the specified policy version.
Synopsis
cli-input-json format
{
"policyName": "string",
"policyVersionId": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
pattern: [0-9]+
Output
{
"policyArn": "string",
827
AWS IoT Developer Guide
GetPolicyVersion
"policyName": "string",
"policyDocument": "string",
"policyVersionId": "string",
"isDefaultVersion": "boolean",
"creationDate": "timestamp",
"lastModifiedDate": "timestamp",
"generationId": "string"
}
pattern: [w+=,.@-]+
pattern: [0-9]+
Errors
ResourceNotFoundException
828
AWS IoT Developer Guide
GetRegistrationCode
GetRegistrationCode
Gets a registration code used to register a CA certificate with AWS IoT.
Synopsis
cli-input-json format
{
}
Output
{
"registrationCode": "string"
}
pattern: (0x)?[a-fA-F0-9]+
Errors
ThrottlingException
GetStatistics
Gets statistics about things that match the specified query.
Synopsis
829
AWS IoT Developer Guide
GetStatistics
cli-input-json format
{
"indexName": "string",
"queryString": "string",
"aggregationField": "string",
"queryVersion": "string"
}
cli-input-json fields
Output
{
"statistics": {
"count": "integer"
}
}
830
AWS IoT Developer Guide
GetThingShadow
Errors
InvalidRequestException
GetThingShadow
Gets the shadow for the specified thing.
For more information, see GetThingShadow in the AWS IoT Developer Guide.
Synopsis
cli-input-json format
{
"thingName": "string"
}
cli-input-json fields
Name Type Description
pattern: [a-zA-Z0-9:_-]+
831
AWS IoT Developer Guide
GetTopicRule
Output
{
"payload": "blob"
}
Errors
InvalidRequestException
GetTopicRule
Gets information about the rule.
Synopsis
cli-input-json format
{
"ruleName": "string"
832
AWS IoT Developer Guide
GetTopicRule
cli-input-json fields
Name Type Description
pattern: ^[a-zA-Z0-9_]+$
Output
{
"ruleArn": "string",
"rule": {
"ruleName": "string",
"sql": "string",
"description": "string",
"createdAt": "timestamp",
"actions": [
{
"dynamoDB": {
"tableName": "string",
"roleArn": "string",
"operation": "string",
"hashKeyField": "string",
"hashKeyValue": "string",
"hashKeyType": "string",
"rangeKeyField": "string",
"rangeKeyValue": "string",
"rangeKeyType": "string",
"payloadField": "string"
},
"dynamoDBv2": {
"roleArn": "string",
"putItem": {
"tableName": "string"
}
},
"lambda": {
"functionArn": "string"
},
"sns": {
"targetArn": "string",
"roleArn": "string",
"messageFormat": "string"
},
"sqs": {
"roleArn": "string",
"queueUrl": "string",
"useBase64": "boolean"
},
"kinesis": {
"roleArn": "string",
"streamName": "string",
"partitionKey": "string"
},
"republish": {
"roleArn": "string",
"topic": "string"
},
833
AWS IoT Developer Guide
GetTopicRule
"s3": {
"roleArn": "string",
"bucketName": "string",
"key": "string",
"cannedAcl": "string"
},
"firehose": {
"roleArn": "string",
"deliveryStreamName": "string",
"separator": "string"
},
"cloudwatchMetric": {
"roleArn": "string",
"metricNamespace": "string",
"metricName": "string",
"metricValue": "string",
"metricUnit": "string",
"metricTimestamp": "string"
},
"cloudwatchAlarm": {
"roleArn": "string",
"alarmName": "string",
"stateReason": "string",
"stateValue": "string"
},
"elasticsearch": {
"roleArn": "string",
"endpoint": "string",
"index": "string",
"type": "string",
"id": "string"
},
"salesforce": {
"token": "string",
"url": "string"
},
"iotAnalytics": {
"channelArn": "string",
"channelName": "string",
"roleArn": "string"
},
"iotEvents": {
"inputName": "string",
"messageId": "string",
"roleArn": "string"
},
"stepFunctions": {
"executionNamePrefix": "string",
"stateMachineName": "string",
"roleArn": "string"
}
}
],
"ruleDisabled": "boolean",
"awsIotSqlVersion": "string",
"errorAction": {
"dynamoDB": {
"tableName": "string",
"roleArn": "string",
"operation": "string",
"hashKeyField": "string",
"hashKeyValue": "string",
"hashKeyType": "string",
"rangeKeyField": "string",
"rangeKeyValue": "string",
"rangeKeyType": "string",
834
AWS IoT Developer Guide
GetTopicRule
"payloadField": "string"
},
"dynamoDBv2": {
"roleArn": "string",
"putItem": {
"tableName": "string"
}
},
"lambda": {
"functionArn": "string"
},
"sns": {
"targetArn": "string",
"roleArn": "string",
"messageFormat": "string"
},
"sqs": {
"roleArn": "string",
"queueUrl": "string",
"useBase64": "boolean"
},
"kinesis": {
"roleArn": "string",
"streamName": "string",
"partitionKey": "string"
},
"republish": {
"roleArn": "string",
"topic": "string"
},
"s3": {
"roleArn": "string",
"bucketName": "string",
"key": "string",
"cannedAcl": "string"
},
"firehose": {
"roleArn": "string",
"deliveryStreamName": "string",
"separator": "string"
},
"cloudwatchMetric": {
"roleArn": "string",
"metricNamespace": "string",
"metricName": "string",
"metricValue": "string",
"metricUnit": "string",
"metricTimestamp": "string"
},
"cloudwatchAlarm": {
"roleArn": "string",
"alarmName": "string",
"stateReason": "string",
"stateValue": "string"
},
"elasticsearch": {
"roleArn": "string",
"endpoint": "string",
"index": "string",
"type": "string",
"id": "string"
},
"salesforce": {
"token": "string",
"url": "string"
},
835
AWS IoT Developer Guide
GetTopicRule
"iotAnalytics": {
"channelArn": "string",
"channelName": "string",
"roleArn": "string"
},
"iotEvents": {
"inputName": "string",
"messageId": "string",
"roleArn": "string"
},
"stepFunctions": {
"executionNamePrefix": "string",
"stateMachineName": "string",
"roleArn": "string"
}
}
}
}
pattern: ^[a-zA-Z0-9_]+$
836
AWS IoT Developer Guide
GetTopicRule
{ "dynamoDBv2":
{ "roleArn":
"aws:iam:12341251:my-
role" "putItem":
{ "tableName": "my-
table" } } }
837
AWS IoT Developer Guide
GetTopicRule
838
AWS IoT Developer Guide
GetTopicRule
839
AWS IoT Developer Guide
GetTopicRule
840
AWS IoT Developer Guide
GetTopicRule
841
AWS IoT Developer Guide
GetTopicRule
842
AWS IoT Developer Guide
GetTopicRule
{ "dynamoDBv2":
{ "roleArn":
"aws:iam:12341251:my-
role" "putItem":
{ "tableName": "my-
table" } } }
843
AWS IoT Developer Guide
GetTopicRule
844
AWS IoT Developer Guide
GetTopicRule
845
AWS IoT Developer Guide
GetTopicRule
846
AWS IoT Developer Guide
GetV2LoggingOptions
Errors
InternalException
GetV2LoggingOptions
Gets the fine grained logging options.
Synopsis
cli-input-json format
{
}
Output
847
AWS IoT Developer Guide
ListActiveViolations
"roleArn": "string",
"defaultLogLevel": "string",
"disableAllLogs": "boolean"
}
Errors
InternalException
ListActiveViolations
Lists the active violations for a given Device Defender security profile.
Synopsis
cli-input-json format
{
"thingName": "string",
"securityProfileName": "string",
"nextToken": "string",
"maxResults": "integer"
}
848
AWS IoT Developer Guide
ListActiveViolations
cli-input-json fields
Name Type Description
pattern: [a-zA-Z0-9:_-]+
Output
{
"activeViolations": [
{
"violationId": "string",
"thingName": "string",
"securityProfileName": "string",
"behavior": {
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
},
"lastViolationValue": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"lastViolationTime": "timestamp",
849
AWS IoT Developer Guide
ListActiveViolations
"violationStartTime": "timestamp"
}
],
"nextToken": "string"
}
member: ActiveViolation
pattern: [a-zA-Z0-9-]+
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
850
AWS IoT Developer Guide
ListActiveViolations
851
AWS IoT Developer Guide
ListActiveViolations
Errors
InvalidRequestException
852
AWS IoT Developer Guide
ListAttachedPolicies
ResourceNotFoundException
ListAttachedPolicies
Lists the policies attached to the specified thing group.
Synopsis
cli-input-json format
{
"target": "string",
"recursive": "boolean",
"marker": "string",
"pageSize": "integer"
}
cli-input-json fields
Name Type Description
Output
{
"policies": [
{
"policyName": "string",
"policyArn": "string"
853
AWS IoT Developer Guide
ListAuditFindings
}
],
"nextMarker": "string"
}
member: Policy
pattern: [w+=,.@-]+
Errors
ResourceNotFoundException
ListAuditFindings
Lists the findings (results) of a Device Defender audit or of the audits performed during a specified time
period. (Findings are retained for 180 days.)
Synopsis
854
AWS IoT Developer Guide
ListAuditFindings
cli-input-json format
{
"taskId": "string",
"checkName": "string",
"resourceIdentifier": {
"deviceCertificateId": "string",
"caCertificateId": "string",
"cognitoIdentityPoolId": "string",
"clientId": "string",
"policyVersionIdentifier": {
"policyName": "string",
"policyVersionId": "string"
},
"account": "string"
},
"maxResults": "integer",
"nextToken": "string",
"startTime": "timestamp",
"endTime": "timestamp"
}
cli-input-json fields
pattern: (0x)?[a-fA-F0-9]+
pattern: (0x)?[a-fA-F0-9]+
855
AWS IoT Developer Guide
ListAuditFindings
pattern: [w+=,.@-]+
pattern: [0-9]+
Output
{
"findings": [
{
"taskId": "string",
"checkName": "string",
"taskStartTime": "timestamp",
"findingTime": "timestamp",
"severity": "string",
"nonCompliantResource": {
"resourceType": "string",
"resourceIdentifier": {
"deviceCertificateId": "string",
"caCertificateId": "string",
856
AWS IoT Developer Guide
ListAuditFindings
"cognitoIdentityPoolId": "string",
"clientId": "string",
"policyVersionIdentifier": {
"policyName": "string",
"policyVersionId": "string"
},
"account": "string"
},
"additionalInfo": {
"string": "string"
}
},
"relatedResources": [
{
"resourceType": "string",
"resourceIdentifier": {
"deviceCertificateId": "string",
"caCertificateId": "string",
"cognitoIdentityPoolId": "string",
"clientId": "string",
"policyVersionIdentifier": {
"policyName": "string",
"policyVersionId": "string"
},
"account": "string"
},
"additionalInfo": {
"string": "string"
}
}
],
"reasonForNonCompliance": "string",
"reasonForNonComplianceCode": "string"
}
],
"nextToken": "string"
}
pattern: [a-zA-Z0-9-]+
857
AWS IoT Developer Guide
ListAuditFindings
enum: DEVICE_CERTIFICATE |
CA_CERTIFICATE | IOT_POLICY
| COGNITO_IDENTITY_POOL
| CLIENT_ID |
ACCOUNT_SETTINGS
pattern: (0x)?[a-fA-F0-9]+
pattern: (0x)?[a-fA-F0-9]+
pattern: [w+=,.@-]+
pattern: [0-9]+
858
AWS IoT Developer Guide
ListAuditFindings
member: RelatedResource
enum: DEVICE_CERTIFICATE |
CA_CERTIFICATE | IOT_POLICY
| COGNITO_IDENTITY_POOL
| CLIENT_ID |
ACCOUNT_SETTINGS
pattern: (0x)?[a-fA-F0-9]+
pattern: (0x)?[a-fA-F0-9]+
pattern: [w+=,.@-]+
pattern: [0-9]+
859
AWS IoT Developer Guide
ListAuditTasks
Errors
InvalidRequestException
ListAuditTasks
Lists the Device Defender audits that have been performed during a given time period.
Synopsis
cli-input-json format
{
"startTime": "timestamp",
"endTime": "timestamp",
"taskType": "string",
"taskStatus": "string",
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
860
AWS IoT Developer Guide
ListAuditTasks
enum:
ON_DEMAND_AUDIT_TASK |
SCHEDULED_AUDIT_TASK
enum: IN_PROGRESS |
COMPLETED | FAILED |
CANCELED
Output
{
"tasks": [
{
"taskId": "string",
"taskStatus": "string",
"taskType": "string"
}
],
"nextToken": "string"
}
861
AWS IoT Developer Guide
ListAuthorizers
pattern: [a-zA-Z0-9-]+
enum: IN_PROGRESS |
COMPLETED | FAILED |
CANCELED
enum:
ON_DEMAND_AUDIT_TASK |
SCHEDULED_AUDIT_TASK
Errors
InvalidRequestException
ListAuthorizers
Lists the authorizers registered in your account.
Synopsis
cli-input-json format
862
AWS IoT Developer Guide
ListAuthorizers
{
"pageSize": "integer",
"marker": "string",
"ascendingOrder": "boolean",
"status": "string"
}
cli-input-json fields
Name Type Description
Output
{
"authorizers": [
{
"authorizerName": "string",
"authorizerArn": "string"
}
],
"nextMarker": "string"
}
member: AuthorizerSummary
pattern: [w=,@-]+
863
AWS IoT Developer Guide
ListBillingGroups
Errors
InvalidRequestException
ListBillingGroups
Lists the billing groups you have created.
Synopsis
cli-input-json format
{
"nextToken": "string",
"maxResults": "integer",
"namePrefixFilter": "string"
}
cli-input-json fields
864
AWS IoT Developer Guide
ListCACertificates
Output
{
"billingGroups": [
{
"groupName": "string",
"groupArn": "string"
}
],
"nextToken": "string"
}
member: GroupNameAndArn
pattern: [a-zA-Z0-9:_-]+
Errors
InvalidRequestException
ListCACertificates
Lists the CA certificates registered for your AWS account.
The results are paginated with a default page size of 25. You can use the returned marker to retrieve
additional results.
865
AWS IoT Developer Guide
ListCACertificates
Synopsis
cli-input-json format
{
"pageSize": "integer",
"marker": "string",
"ascendingOrder": "boolean"
}
cli-input-json fields
Output
{
"certificates": [
{
"certificateArn": "string",
"certificateId": "string",
"status": "string",
"creationDate": "timestamp"
}
],
"nextMarker": "string"
}
866
AWS IoT Developer Guide
ListCertificates
pattern: (0x)?[a-fA-F0-9]+
Errors
InvalidRequestException
ListCertificates
Lists the certificates registered in your AWS account.
The results are paginated with a default page size of 25. You can use the returned marker to retrieve
additional results.
Synopsis
867
AWS IoT Developer Guide
ListCertificates
[--generate-cli-skeleton]
cli-input-json format
{
"pageSize": "integer",
"marker": "string",
"ascendingOrder": "boolean"
}
cli-input-json fields
Output
{
"certificates": [
{
"certificateArn": "string",
"certificateId": "string",
"status": "string",
"creationDate": "timestamp"
}
],
"nextMarker": "string"
}
868
AWS IoT Developer Guide
ListCertificatesByCA
Errors
InvalidRequestException
ListCertificatesByCA
List the device certificates signed by the specified CA certificate.
Synopsis
cli-input-json format
{
"caCertificateId": "string",
869
AWS IoT Developer Guide
ListCertificatesByCA
"pageSize": "integer",
"marker": "string",
"ascendingOrder": "boolean"
}
cli-input-json fields
Name Type Description
Output
{
"certificates": [
{
"certificateArn": "string",
"certificateId": "string",
"status": "string",
"creationDate": "timestamp"
}
],
"nextMarker": "string"
}
870
AWS IoT Developer Guide
ListIndices
Errors
InvalidRequestException
ListIndices
Lists the search indices.
Synopsis
cli-input-json format
{
"nextToken": "string",
"maxResults": "integer"
}
871
AWS IoT Developer Guide
ListJobExecutionsForJob
cli-input-json fields
Output
{
"indexNames": [
"string"
],
"nextToken": "string"
}
member: IndexName
Errors
InvalidRequestException
ListJobExecutionsForJob
Lists the job executions for a job.
872
AWS IoT Developer Guide
ListJobExecutionsForJob
Synopsis
cli-input-json format
{
"jobId": "string",
"status": "string",
"maxResults": "integer",
"nextToken": "string"
}
cli-input-json fields
Name Type Description
Output
{
"executionSummaries": [
{
"thingArn": "string",
"jobExecutionSummary": {
"status": "string",
"queuedAt": "timestamp",
"startedAt": "timestamp",
"lastUpdatedAt": "timestamp",
"executionNumber": "long"
}
}
],
"nextToken": "string"
}
873
AWS IoT Developer Guide
ListJobExecutionsForJob
Errors
InvalidRequestException
874
AWS IoT Developer Guide
ListJobExecutionsForThing
ServiceUnavailableException
ListJobExecutionsForThing
Lists the job executions for the specified thing.
Synopsis
cli-input-json format
{
"thingName": "string",
"status": "string",
"maxResults": "integer",
"nextToken": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
875
AWS IoT Developer Guide
ListJobExecutionsForThing
"executionSummaries": [
{
"jobId": "string",
"jobExecutionSummary": {
"status": "string",
"queuedAt": "timestamp",
"startedAt": "timestamp",
"lastUpdatedAt": "timestamp",
"executionNumber": "long"
}
}
],
"nextToken": "string"
}
876
AWS IoT Developer Guide
ListJobs
Errors
InvalidRequestException
ListJobs
Lists jobs.
Synopsis
cli-input-json format
{
"status": "string",
"targetSelection": "string",
"maxResults": "integer",
"nextToken": "string",
"thingGroupName": "string",
"thingGroupId": "string"
}
cli-input-json fields
877
AWS IoT Developer Guide
ListJobs
enum: CONTINUOUS |
SNAPSHOT
Output
{
"jobs": [
{
"jobArn": "string",
"jobId": "string",
"thingGroupId": "string",
"targetSelection": "string",
"status": "string",
"createdAt": "timestamp",
"lastUpdatedAt": "timestamp",
"completedAt": "timestamp"
}
],
"nextToken": "string"
}
878
AWS IoT Developer Guide
ListJobs
member: JobSummary
pattern: [a-zA-Z0-9-]+
enum: CONTINUOUS |
SNAPSHOT
enum: IN_PROGRESS |
CANCELED | COMPLETED |
DELETION_IN_PROGRESS
879
AWS IoT Developer Guide
ListOTAUpdates
Errors
InvalidRequestException
ListOTAUpdates
Lists OTA updates.
Synopsis
cli-input-json format
{
"maxResults": "integer",
"nextToken": "string",
"otaUpdateStatus": "string"
}
cli-input-json fields
880
AWS IoT Developer Guide
ListOTAUpdates
enum: CREATE_PENDING
| CREATE_IN_PROGRESS
| CREATE_COMPLETE |
CREATE_FAILED
Output
{
"otaUpdates": [
{
"otaUpdateId": "string",
"otaUpdateArn": "string",
"creationDate": "timestamp"
}
],
"nextToken": "string"
}
member: OTAUpdateSummary
pattern: [a-zA-Z0-9_-]+
Errors
InvalidRequestException
881
AWS IoT Developer Guide
ListOutgoingCertificates
ServiceUnavailableException
ListOutgoingCertificates
Lists certificates that are being transferred but not yet accepted.
Synopsis
cli-input-json format
{
"pageSize": "integer",
"marker": "string",
"ascendingOrder": "boolean"
}
cli-input-json fields
Output
{
"outgoingCertificates": [
{
"certificateArn": "string",
"certificateId": "string",
"transferredTo": "string",
"transferDate": "timestamp",
"transferMessage": "string",
"creationDate": "timestamp"
}
],
"nextMarker": "string"
}
882
AWS IoT Developer Guide
ListPolicies
pattern: (0x)?[a-fA-F0-9]+
pattern: [0-9]+
length- max:128
Errors
InvalidRequestException
ListPolicies
Lists your policies.
883
AWS IoT Developer Guide
ListPolicies
Synopsis
cli-input-json format
{
"marker": "string",
"pageSize": "integer",
"ascendingOrder": "boolean"
}
cli-input-json fields
Output
{
"policies": [
{
"policyName": "string",
"policyArn": "string"
}
],
"nextMarker": "string"
}
member: Policy
884
AWS IoT Developer Guide
ListPolicyPrincipals
Errors
InvalidRequestException
ListPolicyPrincipals
Lists the principals associated with the specified policy.
Synopsis
cli-input-json format
{
"policyName": "string",
"marker": "string",
"pageSize": "integer",
"ascendingOrder": "boolean"
}
cli-input-json fields
Name Type Description
885
AWS IoT Developer Guide
ListPolicyPrincipals
pattern: [w+=,.@-]+
Output
{
"principals": [
"string"
],
"nextMarker": "string"
}
Errors
ResourceNotFoundException
886
AWS IoT Developer Guide
ListPolicyVersions
InternalFailureException
ListPolicyVersions
Lists the versions of the specified policy and identifies the default version.
Synopsis
cli-input-json format
{
"policyName": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
Output
{
"policyVersions": [
{
"versionId": "string",
"isDefaultVersion": "boolean",
"createDate": "timestamp"
}
]
}
member: PolicyVersion
pattern: [0-9]+
887
AWS IoT Developer Guide
ListPrincipalPolicies
Errors
ResourceNotFoundException
ListPrincipalPolicies
Lists the policies attached to the specified principal. If you use an Cognito identity, the ID must be in
AmazonCognito Identity format.
Synopsis
cli-input-json format
{
"principal": "string",
"marker": "string",
"pageSize": "integer",
"ascendingOrder": "boolean"
888
AWS IoT Developer Guide
ListPrincipalPolicies
cli-input-json fields
Output
{
"policies": [
{
"policyName": "string",
"policyArn": "string"
}
],
"nextMarker": "string"
}
member: Policy
pattern: [w+=,.@-]+
Errors
ResourceNotFoundException
889
AWS IoT Developer Guide
ListPrincipalThings
InvalidRequestException
ListPrincipalThings
Lists the things associated with the specified principal. A principal can be X.509 certificates, IAM users,
groups, and roles, Amazon Cognito identities or federated identities.
Synopsis
cli-input-json format
{
"nextToken": "string",
"maxResults": "integer",
"principal": "string"
}
cli-input-json fields
Output
{
"things": [
"string"
890
AWS IoT Developer Guide
ListRoleAliases
],
"nextToken": "string"
}
member: ThingName
Errors
InvalidRequestException
ListRoleAliases
Lists the role aliases registered in your account.
Synopsis
cli-input-json format
{
"pageSize": "integer",
"marker": "string",
"ascendingOrder": "boolean"
891
AWS IoT Developer Guide
ListRoleAliases
cli-input-json fields
Output
{
"roleAliases": [
"string"
],
"nextMarker": "string"
}
member: RoleAlias
Errors
InvalidRequestException
892
AWS IoT Developer Guide
ListScheduledAudits
ListScheduledAudits
Lists all of your scheduled audits.
Synopsis
cli-input-json format
{
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
Output
{
"scheduledAudits": [
{
"scheduledAuditName": "string",
"scheduledAuditArn": "string",
"frequency": "string",
"dayOfMonth": "string",
"dayOfWeek": "string"
}
],
"nextToken": "string"
}
member:
ScheduledAuditMetadata
893
AWS IoT Developer Guide
ListSecurityProfiles
pattern: [a-zA-Z0-9_-]+
Errors
InvalidRequestException
ListSecurityProfiles
Lists the Device Defender security profiles you have created. You can use filters to list only those security
profiles associated with a thing group or only those associated with your account.
Synopsis
894
AWS IoT Developer Guide
ListSecurityProfiles
[--next-token <value>] \
[--max-results <value>] \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
Output
{
"securityProfileIdentifiers": [
{
"name": "string",
"arn": "string"
}
],
"nextToken": "string"
}
pattern: [a-zA-Z0-9:_-]+
895
AWS IoT Developer Guide
ListSecurityProfilesForTarget
Errors
InvalidRequestException
ListSecurityProfilesForTarget
Lists the Device Defender security profiles attached to a target (thing group).
Synopsis
cli-input-json format
{
"nextToken": "string",
"maxResults": "integer",
"recursive": "boolean",
"securityProfileTargetArn": "string"
}
cli-input-json fields
Output
{
"securityProfileTargetMappings": [
896
AWS IoT Developer Guide
ListSecurityProfilesForTarget
{
"securityProfileIdentifier": {
"name": "string",
"arn": "string"
},
"target": {
"arn": "string"
}
}
],
"nextToken": "string"
}
pattern: [a-zA-Z0-9:_-]+
Errors
InvalidRequestException
897
AWS IoT Developer Guide
ListStreams
ListStreams
Lists all of the streams in your AWS account.
Synopsis
cli-input-json format
{
"maxResults": "integer",
"nextToken": "string",
"ascendingOrder": "boolean"
}
cli-input-json fields
Output
{
"streams": [
{
"streamId": "string",
"streamArn": "string",
"streamVersion": "integer",
"description": "string"
}
],
"nextToken": "string"
}
member: StreamSummary
898
AWS IoT Developer Guide
ListTagsForResource
pattern: [a-zA-Z0-9_-]+
length- max:2028
pattern: [^\\p{C}]+
Errors
InvalidRequestException
ListTagsForResource
Lists the tags (metadata) you have assigned to the resource.
Synopsis
cli-input-json format
{
"resourceArn": "string",
"nextToken": "string"
}
899
AWS IoT Developer Guide
ListTargetsForPolicy
cli-input-json fields
Name Type Description
Output
{
"tags": [
{
"Key": "string",
"Value": "string"
}
],
"nextToken": "string"
}
Errors
InvalidRequestException
ListTargetsForPolicy
List targets for the specified policy.
900
AWS IoT Developer Guide
ListTargetsForPolicy
Synopsis
cli-input-json format
{
"policyName": "string",
"marker": "string",
"pageSize": "integer"
}
cli-input-json fields
pattern: [w+=,.@-]+
Output
{
"targets": [
"string"
],
"nextMarker": "string"
}
member: PolicyTarget
901
AWS IoT Developer Guide
ListTargetsForSecurityProfile
Errors
ResourceNotFoundException
ListTargetsForSecurityProfile
Lists the targets (thing groups) associated with a given Device Defender security profile.
Synopsis
cli-input-json format
{
"securityProfileName": "string",
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
902
AWS IoT Developer Guide
ListThingGroups
Output
{
"securityProfileTargets": [
{
"arn": "string"
}
],
"nextToken": "string"
}
Errors
InvalidRequestException
ListThingGroups
List the thing groups in your account.
903
AWS IoT Developer Guide
ListThingGroups
Synopsis
cli-input-json format
{
"nextToken": "string",
"maxResults": "integer",
"parentGroup": "string",
"namePrefixFilter": "string",
"recursive": "boolean"
}
cli-input-json fields
Output
{
"thingGroups": [
{
"groupName": "string",
"groupArn": "string"
}
],
"nextToken": "string"
}
904
AWS IoT Developer Guide
ListThingGroupsForThing
member: GroupNameAndArn
pattern: [a-zA-Z0-9:_-]+
Errors
InvalidRequestException
ListThingGroupsForThing
List the thing groups to which the specified thing belongs.
Synopsis
cli-input-json format
{
"thingName": "string",
"nextToken": "string",
"maxResults": "integer"
}
905
AWS IoT Developer Guide
ListThingGroupsForThing
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"thingGroups": [
{
"groupName": "string",
"groupArn": "string"
}
],
"nextToken": "string"
}
member: GroupNameAndArn
pattern: [a-zA-Z0-9:_-]+
Errors
InvalidRequestException
906
AWS IoT Developer Guide
ListThingPrincipals
ResourceNotFoundException
ListThingPrincipals
Lists the principals associated with the specified thing. A principal can be X.509 certificates, IAM users,
groups, and roles, Amazon Cognito identities or federated identities.
Synopsis
cli-input-json format
{
"thingName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"principals": [
"string"
]
}
Errors
InvalidRequestException
907
AWS IoT Developer Guide
ListThingRegistrationTaskReports
ThrottlingException
ListThingRegistrationTaskReports
Information about the thing registration tasks.
Synopsis
cli-input-json format
{
"taskId": "string",
"reportType": "string",
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
length- max:40
908
AWS IoT Developer Guide
ListThingRegistrationTasks
Output
{
"resourceLinks": [
"string"
],
"reportType": "string",
"nextToken": "string"
}
member: S3FileUrl
Errors
InvalidRequestException
ListThingRegistrationTasks
List bulk thing provisioning tasks.
Synopsis
cli-input-json format
909
AWS IoT Developer Guide
ListThingRegistrationTasks
"nextToken": "string",
"maxResults": "integer",
"status": "string"
}
cli-input-json fields
Output
{
"taskIds": [
"string"
],
"nextToken": "string"
}
Errors
InvalidRequestException
910
AWS IoT Developer Guide
ListThingTypes
ListThingTypes
Lists the existing thing types.
Synopsis
cli-input-json format
{
"nextToken": "string",
"maxResults": "integer",
"thingTypeName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"thingTypes": [
{
"thingTypeName": "string",
"thingTypeArn": "string",
"thingTypeProperties": {
"thingTypeDescription": "string",
"searchableAttributes": [
"string"
]
},
"thingTypeMetadata": {
"deprecated": "boolean",
"deprecationDate": "timestamp",
"creationDate": "timestamp"
}
}
],
"nextToken": "string"
911
AWS IoT Developer Guide
ListThingTypes
member: ThingTypeDefinition
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
Errors
912
AWS IoT Developer Guide
ListThings
InvalidRequestException
ListThings
Lists your things. Use the attributeName and attributeValue parameters to filter your things. For
example, calling ListThings with attributeName=Color and attributeValue=Red retrieves all things in
the registry that contain an attribute Color with the value Red.
Synopsis
cli-input-json format
{
"nextToken": "string",
"maxResults": "integer",
"attributeName": "string",
"attributeValue": "string",
"thingTypeName": "string"
}
cli-input-json fields
913
AWS IoT Developer Guide
ListThings
pattern: [a-zA-Z0-9_.,@/:#-]+
pattern: [a-zA-Z0-9_.,@/:#-]*
pattern: [a-zA-Z0-9:_-]+
Output
{
"things": [
{
"thingName": "string",
"thingTypeName": "string",
"thingArn": "string",
"attributes": {
"string": "string"
},
"version": "long"
}
],
"nextToken": "string"
}
member: ThingAttribute
pattern: [a-zA-Z0-9:_-]+
914
AWS IoT Developer Guide
ListThingsInBillingGroup
Errors
InvalidRequestException
ListThingsInBillingGroup
Lists the things you have added to the given billing group.
Synopsis
cli-input-json format
{
"billingGroupName": "string",
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
915
AWS IoT Developer Guide
ListThingsInThingGroup
pattern: [a-zA-Z0-9:_-]+
Output
{
"things": [
"string"
],
"nextToken": "string"
}
Errors
InvalidRequestException
ListThingsInThingGroup
Lists the things in the specified group.
Synopsis
916
AWS IoT Developer Guide
ListThingsInThingGroup
cli-input-json format
{
"thingGroupName": "string",
"recursive": "boolean",
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"things": [
"string"
],
"nextToken": "string"
}
917
AWS IoT Developer Guide
ListTopicRules
Errors
InvalidRequestException
ListTopicRules
Lists the rules for the specific topic.
Synopsis
cli-input-json format
{
"topic": "string",
"maxResults": "integer",
"nextToken": "string",
"ruleDisabled": "boolean"
}
cli-input-json fields
Output
918
AWS IoT Developer Guide
ListV2LoggingLevels
"rules": [
{
"ruleArn": "string",
"ruleName": "string",
"topicPattern": "string",
"createdAt": "timestamp",
"ruleDisabled": "boolean"
}
],
"nextToken": "string"
}
member: TopicRuleListItem
pattern: ^[a-zA-Z0-9_]+$
Errors
InternalException
ListV2LoggingLevels
Lists logging levels.
Synopsis
919
AWS IoT Developer Guide
ListV2LoggingLevels
cli-input-json format
{
"targetType": "string",
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
Output
{
"logTargetConfigurations": [
{
"logTarget": {
"targetType": "string",
"targetName": "string"
},
"logLevel": "string"
}
],
"nextToken": "string"
}
920
AWS IoT Developer Guide
ListViolationEvents
Errors
InternalException
ListViolationEvents
Lists the Device Defender security profile violations discovered during the given time period. You can use
filters to limit the results to those alerts issued for a particular security profile, behavior or thing (device).
Synopsis
cli-input-json format
{
"startTime": "timestamp",
"endTime": "timestamp",
"thingName": "string",
921
AWS IoT Developer Guide
ListViolationEvents
"securityProfileName": "string",
"nextToken": "string",
"maxResults": "integer"
}
cli-input-json fields
Output
{
"violationEvents": [
{
"violationId": "string",
"thingName": "string",
"securityProfileName": "string",
"behavior": {
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
922
AWS IoT Developer Guide
ListViolationEvents
}
},
"metricValue": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"violationEventType": "string",
"violationEventTime": "timestamp"
}
],
"nextToken": "string"
}
pattern: [a-zA-Z0-9-]+
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
923
AWS IoT Developer Guide
ListViolationEvents
924
AWS IoT Developer Guide
ListViolationEvents
925
AWS IoT Developer Guide
Publish
Errors
InvalidRequestException
Publish
Publishes state information.
For more information, see HTTP Protocol in the AWS IoT Developer Guide.
Synopsis
cli-input-json format
{
"topic": "string",
"qos": "integer",
"payload": "blob"
}
cli-input-json fields
926
AWS IoT Developer Guide
RegisterCACertificate
Output
None
Errors
InternalFailureException
RegisterCACertificate
Registers a CA certificate with AWS IoT. This CA certificate can then be used to sign device certificates,
which can be then registered with AWS IoT. You can register up to 10 CA certificates per AWS account
that have the same subject field. This enables you to have up to 10 certificate authorities sign your
device certificates. If you have more than one CA certificate registered, make sure you pass the CA
certificate when you register your device certificates with the RegisterCertificate API.
Synopsis
cli-input-json format
{
"caCertificate": "string",
"verificationCertificate": "string",
"setAsActive": "boolean",
"allowAutoRegistration": "boolean",
"registrationConfig": {
"templateBody": "string",
"roleArn": "string"
927
AWS IoT Developer Guide
RegisterCACertificate
}
}
cli-input-json fields
Output
{
"certificateArn": "string",
"certificateId": "string"
}
pattern: (0x)?[a-fA-F0-9]+
Errors
ResourceAlreadyExistsException
928
AWS IoT Developer Guide
RegisterCertificate
InvalidRequestException
RegisterCertificate
Registers a device certificate with AWS IoT. If you have more than one CA certificate that has the same
subject field, you must specify the CA certificate that was used to sign the device certificate being
registered.
Synopsis
cli-input-json format
{
"certificatePem": "string",
"caCertificatePem": "string",
"status": "string"
}
cli-input-json fields
929
AWS IoT Developer Guide
RegisterCertificate
Output
{
"certificateArn": "string",
"certificateId": "string"
}
pattern: (0x)?[a-fA-F0-9]+
Errors
ResourceAlreadyExistsException
Unable to verify the CA certificate used to sign the device certificate you are attempting to register.
This is happens when you have registered more than one CA certificate that has the same subject
field and public key.
ThrottlingException
930
AWS IoT Developer Guide
RegisterThing
InternalFailureException
RegisterThing
Provisions a thing.
Synopsis
cli-input-json format
{
"templateBody": "string",
"parameters": {
"string": "string"
}
}
cli-input-json fields
Name Type Description
Output
{
"certificatePem": "string",
"resourceArns": {
"string": "string"
}
}
certificatePem string .
931
AWS IoT Developer Guide
RejectCertificateTransfer
Errors
InternalFailureException
A conflicting resource update exception. This exception is thrown when two pending updates cause a
conflict.
ResourceRegistrationFailureException
RejectCertificateTransfer
Rejects a pending certificate transfer. After AWS IoT rejects a certificate transfer, the certificate status
changes from PENDING_TRANSFER to INACTIVE.
To check for pending certificate transfers, call ListCertificates to enumerate your certificates.
This operation can only be called by the transfer destination. After it is called, the certificate will be
returned to the source's account in the INACTIVE state.
Synopsis
cli-input-json format
{
"certificateId": "string",
"rejectReason": "string"
}
cli-input-json fields
932
AWS IoT Developer Guide
RemoveThingFromBillingGroup
Output
None
Errors
ResourceNotFoundException
You can't revert the certificate transfer because the transfer is already complete.
InvalidRequestException
RemoveThingFromBillingGroup
Removes the given thing from the billing group.
Synopsis
cli-input-json format
{
"billingGroupName": "string",
"billingGroupArn": "string",
"thingName": "string",
"thingArn": "string"
933
AWS IoT Developer Guide
RemoveThingFromThingGroup
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
Output
None
Errors
InvalidRequestException
RemoveThingFromThingGroup
Remove the specified thing from the specified group.
Synopsis
cli-input-json format
934
AWS IoT Developer Guide
ReplaceTopicRule
{
"thingGroupName": "string",
"thingGroupArn": "string",
"thingName": "string",
"thingArn": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
Output
None
Errors
InvalidRequestException
ReplaceTopicRule
Replaces the rule. You must specify all parameters for the new rule. Creating rules is an administrator-
level action. Any user who has permission to create rules will be able to access data processed by the
rule.
Synopsis
935
AWS IoT Developer Guide
ReplaceTopicRule
--rule-name <value> \
--topic-rule-payload <value> \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"ruleName": "string",
"topicRulePayload": {
"sql": "string",
"description": "string",
"actions": [
{
"dynamoDB": {
"tableName": "string",
"roleArn": "string",
"operation": "string",
"hashKeyField": "string",
"hashKeyValue": "string",
"hashKeyType": "string",
"rangeKeyField": "string",
"rangeKeyValue": "string",
"rangeKeyType": "string",
"payloadField": "string"
},
"dynamoDBv2": {
"roleArn": "string",
"putItem": {
"tableName": "string"
}
},
"lambda": {
"functionArn": "string"
},
"sns": {
"targetArn": "string",
"roleArn": "string",
"messageFormat": "string"
},
"sqs": {
"roleArn": "string",
"queueUrl": "string",
"useBase64": "boolean"
},
"kinesis": {
"roleArn": "string",
"streamName": "string",
"partitionKey": "string"
},
"republish": {
"roleArn": "string",
"topic": "string"
},
"s3": {
"roleArn": "string",
"bucketName": "string",
"key": "string",
"cannedAcl": "string"
},
"firehose": {
"roleArn": "string",
"deliveryStreamName": "string",
"separator": "string"
},
936
AWS IoT Developer Guide
ReplaceTopicRule
"cloudwatchMetric": {
"roleArn": "string",
"metricNamespace": "string",
"metricName": "string",
"metricValue": "string",
"metricUnit": "string",
"metricTimestamp": "string"
},
"cloudwatchAlarm": {
"roleArn": "string",
"alarmName": "string",
"stateReason": "string",
"stateValue": "string"
},
"elasticsearch": {
"roleArn": "string",
"endpoint": "string",
"index": "string",
"type": "string",
"id": "string"
},
"salesforce": {
"token": "string",
"url": "string"
},
"iotAnalytics": {
"channelArn": "string",
"channelName": "string",
"roleArn": "string"
},
"iotEvents": {
"inputName": "string",
"messageId": "string",
"roleArn": "string"
},
"stepFunctions": {
"executionNamePrefix": "string",
"stateMachineName": "string",
"roleArn": "string"
}
}
],
"ruleDisabled": "boolean",
"awsIotSqlVersion": "string",
"errorAction": {
"dynamoDB": {
"tableName": "string",
"roleArn": "string",
"operation": "string",
"hashKeyField": "string",
"hashKeyValue": "string",
"hashKeyType": "string",
"rangeKeyField": "string",
"rangeKeyValue": "string",
"rangeKeyType": "string",
"payloadField": "string"
},
"dynamoDBv2": {
"roleArn": "string",
"putItem": {
"tableName": "string"
}
},
"lambda": {
"functionArn": "string"
},
937
AWS IoT Developer Guide
ReplaceTopicRule
"sns": {
"targetArn": "string",
"roleArn": "string",
"messageFormat": "string"
},
"sqs": {
"roleArn": "string",
"queueUrl": "string",
"useBase64": "boolean"
},
"kinesis": {
"roleArn": "string",
"streamName": "string",
"partitionKey": "string"
},
"republish": {
"roleArn": "string",
"topic": "string"
},
"s3": {
"roleArn": "string",
"bucketName": "string",
"key": "string",
"cannedAcl": "string"
},
"firehose": {
"roleArn": "string",
"deliveryStreamName": "string",
"separator": "string"
},
"cloudwatchMetric": {
"roleArn": "string",
"metricNamespace": "string",
"metricName": "string",
"metricValue": "string",
"metricUnit": "string",
"metricTimestamp": "string"
},
"cloudwatchAlarm": {
"roleArn": "string",
"alarmName": "string",
"stateReason": "string",
"stateValue": "string"
},
"elasticsearch": {
"roleArn": "string",
"endpoint": "string",
"index": "string",
"type": "string",
"id": "string"
},
"salesforce": {
"token": "string",
"url": "string"
},
"iotAnalytics": {
"channelArn": "string",
"channelName": "string",
"roleArn": "string"
},
"iotEvents": {
"inputName": "string",
"messageId": "string",
"roleArn": "string"
},
"stepFunctions": {
938
AWS IoT Developer Guide
ReplaceTopicRule
"executionNamePrefix": "string",
"stateMachineName": "string",
"roleArn": "string"
}
}
}
}
cli-input-json fields
pattern: ^[a-zA-Z0-9_]+$
939
AWS IoT Developer Guide
ReplaceTopicRule
{ "dynamoDBv2":
{ "roleArn":
"aws:iam:12341251:my-
role" "putItem":
{ "tableName": "my-
table" } } }
940
AWS IoT Developer Guide
ReplaceTopicRule
941
AWS IoT Developer Guide
ReplaceTopicRule
942
AWS IoT Developer Guide
ReplaceTopicRule
943
AWS IoT Developer Guide
ReplaceTopicRule
944
AWS IoT Developer Guide
ReplaceTopicRule
{ "dynamoDBv2":
{ "roleArn":
"aws:iam:12341251:my-
role" "putItem":
{ "tableName": "my-
table" } } }
945
AWS IoT Developer Guide
ReplaceTopicRule
946
AWS IoT Developer Guide
ReplaceTopicRule
947
AWS IoT Developer Guide
ReplaceTopicRule
948
AWS IoT Developer Guide
ReplaceTopicRule
Output
None
949
AWS IoT Developer Guide
SearchIndex
Errors
SqlParseException
A conflicting resource update exception. This exception is thrown when two pending updates cause a
conflict.
SearchIndex
The query search index.
Synopsis
cli-input-json format
{
"indexName": "string",
"queryString": "string",
"nextToken": "string",
"maxResults": "integer",
"queryVersion": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
950
AWS IoT Developer Guide
SearchIndex
Output
{
"nextToken": "string",
"things": [
{
"thingName": "string",
"thingId": "string",
"thingTypeName": "string",
"thingGroupNames": [
"string"
],
"attributes": {
"string": "string"
},
"shadow": "string",
"connectivity": {
"connected": "boolean",
"timestamp": "long"
}
}
],
"thingGroups": [
{
"thingGroupName": "string",
"thingGroupId": "string",
"thingGroupDescription": "string",
"attributes": {
"string": "string"
},
"parentGroupNames": [
"string"
]
}
]
}
951
AWS IoT Developer Guide
SearchIndex
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9:_-]+
member: ThingGroupName
pattern: [a-zA-Z0-9:_-]+
pattern: [a-zA-Z0-9-]+
952
AWS IoT Developer Guide
SetDefaultAuthorizer
length- max:2028
pattern: [\\p{Graph} ]*
member: ThingGroupName
Errors
InvalidRequestException
SetDefaultAuthorizer
Sets the default authorizer. This will be used if a websocket connection is made without specifying an
authorizer.
Synopsis
cli-input-json format
953
AWS IoT Developer Guide
SetDefaultAuthorizer
{
"authorizerName": "string"
}
cli-input-json fields
pattern: [w=,@-]+
Output
{
"authorizerName": "string",
"authorizerArn": "string"
}
pattern: [w=,@-]+
Errors
ResourceNotFoundException
954
AWS IoT Developer Guide
SetDefaultPolicyVersion
SetDefaultPolicyVersion
Sets the specified version of the specified policy as the policy's default (operative) version. This action
affects all certificates to which the policy is attached. To list the principals the policy is attached to, use
the ListPrincipalPolicy API.
Synopsis
cli-input-json format
{
"policyName": "string",
"policyVersionId": "string"
}
cli-input-json fields
pattern: [w+=,.@-]+
pattern: [0-9]+
Output
None
Errors
ResourceNotFoundException
955
AWS IoT Developer Guide
SetLoggingOptions
InternalFailureException
SetLoggingOptions
Sets the logging options.
Synopsis
cli-input-json format
{
"loggingOptionsPayload": {
"roleArn": "string",
"logLevel": "string"
}
}
cli-input-json fields
Output
None
Errors
InternalException
956
AWS IoT Developer Guide
SetV2LoggingLevel
SetV2LoggingLevel
Sets the logging level.
Synopsis
cli-input-json format
{
"logTarget": {
"targetType": "string",
"targetName": "string"
},
"logLevel": "string"
}
cli-input-json fields
Output
None
Errors
InternalException
957
AWS IoT Developer Guide
SetV2LoggingOptions
SetV2LoggingOptions
Sets the logging options for the V2 logging service.
Synopsis
cli-input-json format
{
"roleArn": "string",
"defaultLogLevel": "string",
"disableAllLogs": "boolean"
}
cli-input-json fields
Output
None
Errors
InternalException
StartNextPendingJobExecution
Gets and starts the next pending (status IN_PROGRESS or QUEUED) job execution for a thing.
958
AWS IoT Developer Guide
StartNextPendingJobExecution
Synopsis
cli-input-json format
{
"thingName": "string",
"statusDetails": {
"string": "string"
},
"stepTimeoutInMinutes": "long"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
959
AWS IoT Developer Guide
StartNextPendingJobExecution
Output
{
"execution": {
"jobId": "string",
"thingName": "string",
"status": "string",
"statusDetails": {
"string": "string"
},
"queuedAt": "long",
"startedAt": "long",
"lastUpdatedAt": "long",
"approximateSecondsBeforeTimedOut": "long",
"versionNumber": "long",
"executionNumber": "long",
"jobDocument": "string"
}
}
pattern: [a-zA-Z0-9:_-]+
960
AWS IoT Developer Guide
StartOnDemandAuditTask
approximateSecondsBeforeTimedOut
long The estimated number of
seconds that remain before
the job execution status will be
changed to TIMED_OUT. The
actual job execution timeout
can occur up to 60 seconds later
than the estimated duration.
Errors
InvalidRequestException
StartOnDemandAuditTask
Starts an on-demand Device Defender audit.
Synopsis
961
AWS IoT Developer Guide
StartOnDemandAuditTask
--target-check-names <value> \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"targetCheckNames": [
"string"
]
}
cli-input-json fields
Output
{
"taskId": "string"
}
pattern: [a-zA-Z0-9-]+
Errors
InvalidRequestException
962
AWS IoT Developer Guide
StartThingRegistrationTask
LimitExceededException
StartThingRegistrationTask
Creates a bulk thing provisioning task.
Synopsis
cli-input-json format
{
"templateBody": "string",
"inputFileBucket": "string",
"inputFileKey": "string",
"roleArn": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9._-]+
Output
{
"taskId": "string"
}
963
AWS IoT Developer Guide
StopThingRegistrationTask
Errors
InvalidRequestException
StopThingRegistrationTask
Cancels a bulk thing provisioning task.
Synopsis
cli-input-json format
{
"taskId": "string"
}
cli-input-json fields
Output
None
Errors
964
AWS IoT Developer Guide
TagResource
InvalidRequestException
TagResource
Adds to or modifies the tags of the given resource. Tags are metadata which can be used to manage a
resource.
Synopsis
cli-input-json format
{
"resourceArn": "string",
"tags": [
{
"Key": "string",
"Value": "string"
}
]
}
cli-input-json fields
965
AWS IoT Developer Guide
TestAuthorization
Output
None
Errors
InvalidRequestException
TestAuthorization
Tests if a specified principal is authorized to perform an AWS IoT action on a specified resource. Use this
to test and debug the authorization behavior of devices that connect to the AWS IoT device gateway.
Synopsis
cli-input-json format
{
"principal": "string",
"cognitoIdentityPoolId": "string",
"authInfos": [
{
"actionType": "string",
"resources": [
"string"
]
}
],
"clientId": "string",
"policyNamesToAdd": [
"string"
],
"policyNamesToSkip": [
"string"
966
AWS IoT Developer Guide
TestAuthorization
]
}
cli-input-json fields
Output
{
"authResults": [
{
"authInfo": {
"actionType": "string",
"resources": [
"string"
]
},
"allowed": {
"policies": [
{
"policyName": "string",
"policyArn": "string"
}
]
},
967
AWS IoT Developer Guide
TestAuthorization
"denied": {
"implicitDeny": {
"policies": [
{
"policyName": "string",
"policyArn": "string"
}
]
},
"explicitDeny": {
"policies": [
{
"policyName": "string",
"policyArn": "string"
}
]
}
},
"authDecision": "string",
"missingContextValues": [
"string"
]
}
]
}
member: AuthResult
pattern: [w+=,.@-]+
968
AWS IoT Developer Guide
TestAuthorization
pattern: [w+=,.@-]+
pattern: [w+=,.@-]+
enum: ALLOWED
| EXPLICIT_DENY |
IMPLICIT_DENY
969
AWS IoT Developer Guide
TestInvokeAuthorizer
Errors
ResourceNotFoundException
TestInvokeAuthorizer
Tests a custom authorization behavior by invoking a specified custom authorizer. Use this to test and
debug the custom authorization behavior of devices that connect to the AWS IoT device gateway.
Synopsis
cli-input-json format
{
"authorizerName": "string",
"token": "string",
"tokenSignature": "string"
}
cli-input-json fields
970
AWS IoT Developer Guide
TestInvokeAuthorizer
Output
{
"isAuthenticated": "boolean",
"principalId": "string",
"policyDocuments": [
"string"
],
"refreshAfterInSeconds": "integer",
"disconnectAfterInSeconds": "integer"
}
pattern: [a-zA-Z0-9]+
member: PolicyDocument
Errors
ResourceNotFoundException
971
AWS IoT Developer Guide
TransferCertificate
ThrottlingException
TransferCertificate
Transfers the specified certificate to the specified AWS account.
No notification is sent to the transfer destination's account. It is up to the caller to notify the transfer
target.
The certificate being transferred must not be in the ACTIVE state. You can use the UpdateCertificate API
to deactivate it.
The certificate must not have any policies attached to it. You can use the DetachPrincipalPolicy API to
detach them.
Synopsis
cli-input-json format
{
"certificateId": "string",
"targetAwsAccount": "string",
"transferMessage": "string"
}
cli-input-json fields
972
AWS IoT Developer Guide
UntagResource
pattern: [0-9]+
length- max:128
Output
{
"transferredCertificateArn": "string"
}
Errors
InvalidRequestException
You can't transfer the certificate because authorization policies are still attached.
ThrottlingException
UntagResource
Removes the given tags (metadata) from the resource.
973
AWS IoT Developer Guide
UpdateAccountAuditConfiguration
Synopsis
cli-input-json format
{
"resourceArn": "string",
"tagKeys": [
"string"
]
}
cli-input-json fields
Name Type Description
Output
None
Errors
InvalidRequestException
UpdateAccountAuditConfiguration
Configures or reconfigures the Device Defender audit settings for this account. Settings include how
audit notifications are sent and which audit checks are enabled or disabled.
Synopsis
974
AWS IoT Developer Guide
UpdateAccountAuditConfiguration
[--audit-check-configurations <value>] \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"roleArn": "string",
"auditNotificationTargetConfigurations": {
"string": {
"targetArn": "string",
"roleArn": "string",
"enabled": "boolean"
}
},
"auditCheckConfigurations": {
"string": {
"enabled": "boolean"
}
}
}
cli-input-json fields
auditNotificationTargetConfigurations
map Information about the targets
to which audit notifications are
sent.
975
AWS IoT Developer Guide
UpdateAuthorizer
Output
None
Errors
InvalidRequestException
UpdateAuthorizer
Updates an authorizer.
Synopsis
cli-input-json format
{
"authorizerName": "string",
"authorizerFunctionArn": "string",
"tokenKeyName": "string",
"tokenSigningPublicKeys": {
976
AWS IoT Developer Guide
UpdateAuthorizer
"string": "string"
},
"status": "string"
}
cli-input-json fields
Name Type Description
pattern: [w=,@-]+
pattern: [a-zA-Z0-9_-]+
Output
{
"authorizerName": "string",
"authorizerArn": "string"
}
pattern: [w=,@-]+
Errors
ResourceNotFoundException
977
AWS IoT Developer Guide
UpdateBillingGroup
LimitExceededException
UpdateBillingGroup
Updates information about the billing group.
Synopsis
cli-input-json format
{
"billingGroupName": "string",
"billingGroupProperties": {
"billingGroupDescription": "string"
},
"expectedVersion": "long"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
978
AWS IoT Developer Guide
UpdateCACertificate
Output
{
"version": "long"
}
Errors
InvalidRequestException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
UpdateCACertificate
Updates a registered CA certificate.
Synopsis
979
AWS IoT Developer Guide
UpdateCACertificate
[--remove-auto-registration | --no-remove-auto-registration] \
[--cli-input-json <value>] \
[--generate-cli-skeleton]
cli-input-json format
{
"certificateId": "string",
"newStatus": "string",
"newAutoRegistrationStatus": "string",
"registrationConfig": {
"templateBody": "string",
"roleArn": "string"
},
"removeAutoRegistration": "boolean"
}
cli-input-json fields
pattern: (0x)?[a-fA-F0-9]+
Output
None
Errors
980
AWS IoT Developer Guide
UpdateCertificate
ResourceNotFoundException
UpdateCertificate
Updates the status of the specified certificate. This operation is idempotent.
Moving a certificate from the ACTIVE state (including REVOKED) will not disconnect currently connected
devices, but these devices will be unable to reconnect.
The ACTIVE state is required to authenticate devices connecting to AWS IoT using a certificate.
Synopsis
cli-input-json format
{
"certificateId": "string",
"newStatus": "string"
}
cli-input-json fields
981
AWS IoT Developer Guide
UpdateDynamicThingGroup
Output
None
Errors
ResourceNotFoundException
UpdateDynamicThingGroup
Updates a dynamic thing group.
Synopsis
982
AWS IoT Developer Guide
UpdateDynamicThingGroup
[--generate-cli-skeleton]
cli-input-json format
{
"thingGroupName": "string",
"thingGroupProperties": {
"thingGroupDescription": "string",
"attributePayload": {
"attributes": {
"string": "string"
},
"merge": "boolean"
}
},
"expectedVersion": "long",
"indexName": "string",
"queryString": "string",
"queryVersion": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
length- max:2028
pattern: [\\p{Graph} ]*
\"attributes\":
{\"string1\":
\"string2\"}
983
AWS IoT Developer Guide
UpdateDynamicThingGroup
Output
{
"version": "long"
}
Errors
InvalidRequestException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
984
AWS IoT Developer Guide
UpdateEventConfigurations
InternalFailureException
UpdateEventConfigurations
Updates the event configurations.
Synopsis
cli-input-json format
{
"eventConfigurations": {
"string": {
"Enabled": "boolean"
}
}
}
cli-input-json fields
Output
None
Errors
InvalidRequestException
985
AWS IoT Developer Guide
UpdateIndexingConfiguration
UpdateIndexingConfiguration
Updates the search configuration.
Synopsis
cli-input-json format
{
"thingIndexingConfiguration": {
"thingIndexingMode": "string",
"thingConnectivityIndexingMode": "string"
},
"thingGroupIndexingConfiguration": {
"thingGroupIndexingMode": "string"
}
}
cli-input-json fields
986
AWS IoT Developer Guide
UpdateJob
enum: OFF | ON
Output
None
Errors
InvalidRequestException
UpdateJob
Updates supported fields of the specified job.
Synopsis
cli-input-json format
{
"jobId": "string",
"description": "string",
"presignedUrlConfig": {
"roleArn": "string",
"expiresInSec": "long"
},
"jobExecutionsRolloutConfig": {
"maximumPerMinute": "integer",
987
AWS IoT Developer Guide
UpdateJob
"exponentialRate": {
"baseRatePerMinute": "integer",
"incrementFactor": "double",
"rateIncreaseCriteria": {
"numberOfNotifiedThings": "integer",
"numberOfSucceededThings": "integer"
}
}
},
"abortConfig": {
"criteriaList": [
{
"failureType": "string",
"action": "string",
"thresholdPercentage": "double",
"minNumberOfExecutedThings": "integer"
}
]
},
"timeoutConfig": {
"inProgressTimeoutInMinutes": "long"
}
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
pattern: [^\\p{C}]+
988
AWS IoT Developer Guide
UpdateJob
enum: CANCEL
989
AWS IoT Developer Guide
UpdateJobExecution
Output
None
Errors
InvalidRequestException
UpdateJobExecution
Updates the status of a job execution.
Synopsis
990
AWS IoT Developer Guide
UpdateJobExecution
cli-input-json format
{
"jobId": "string",
"thingName": "string",
"status": "string",
"statusDetails": {
"string": "string"
},
"stepTimeoutInMinutes": "long",
"expectedVersion": "long",
"includeJobExecutionState": "boolean",
"includeJobDocument": "boolean",
"executionNumber": "long"
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
pattern: [a-zA-Z0-9:_-]+
991
AWS IoT Developer Guide
UpdateJobExecution
992
AWS IoT Developer Guide
UpdateJobExecution
Output
{
"executionState": {
"status": "string",
"statusDetails": {
"string": "string"
},
"versionNumber": "long"
},
"jobDocument": "string"
}
Errors
InvalidRequestException
993
AWS IoT Developer Guide
UpdateRoleAlias
ThrottlingException
An update attempted to change the job execution to a state that is invalid because of the job
execution's current state (for example, an attempt to change a request in state SUCCESS to state
IN_PROGRESS). In this case, the body of the error message also contains the executionState field.
UpdateRoleAlias
Updates a role alias.
Synopsis
cli-input-json format
{
"roleAlias": "string",
"roleArn": "string",
"credentialDurationSeconds": "integer"
}
cli-input-json fields
pattern: [w=,@-]+
Output
994
AWS IoT Developer Guide
UpdateScheduledAudit
"roleAlias": "string",
"roleAliasArn": "string"
}
pattern: [w=,@-]+
Errors
ResourceNotFoundException
UpdateScheduledAudit
Updates a scheduled audit, including what checks are performed and how often the audit takes place.
Synopsis
cli-input-json format
{
"frequency": "string",
"dayOfMonth": "string",
"dayOfWeek": "string",
995
AWS IoT Developer Guide
UpdateScheduledAudit
"targetCheckNames": [
"string"
],
"scheduledAuditName": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
996
AWS IoT Developer Guide
UpdateSecurityProfile
Output
{
"scheduledAuditArn": "string"
}
Errors
InvalidRequestException
UpdateSecurityProfile
Updates a Device Defender security profile.
Synopsis
cli-input-json format
{
"securityProfileName": "string",
"securityProfileDescription": "string",
"behaviors": [
{
"name": "string",
"metric": "string",
997
AWS IoT Developer Guide
UpdateSecurityProfile
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
}
],
"alertTargets": {
"string": {
"alertTargetArn": "string",
"roleArn": "string"
}
},
"additionalMetricsToRetain": [
"string"
],
"deleteBehaviors": "boolean",
"deleteAlertTargets": "boolean",
"deleteAdditionalMetricsToRetain": "boolean",
"expectedVersion": "long"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
pattern: [a-zA-Z0-9:_-]+
998
AWS IoT Developer Guide
UpdateSecurityProfile
999
AWS IoT Developer Guide
UpdateSecurityProfile
1000
AWS IoT Developer Guide
UpdateSecurityProfile
Output
{
"securityProfileName": "string",
"securityProfileArn": "string",
"securityProfileDescription": "string",
"behaviors": [
{
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
}
1001
AWS IoT Developer Guide
UpdateSecurityProfile
],
"alertTargets": {
"string": {
"alertTargetArn": "string",
"roleArn": "string"
}
},
"additionalMetricsToRetain": [
"string"
],
"version": "long",
"creationDate": "timestamp",
"lastModifiedDate": "timestamp"
}
pattern: [a-zA-Z0-9:_-]+
pattern: [\\p{Graph} ]*
pattern: [a-zA-Z0-9:_-]+
1002
AWS IoT Developer Guide
UpdateSecurityProfile
1003
AWS IoT Developer Guide
UpdateSecurityProfile
Errors
InvalidRequestException
1004
AWS IoT Developer Guide
UpdateStream
VersionConflictException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
UpdateStream
Updates an existing stream. The stream version will be incremented by one.
Synopsis
cli-input-json format
{
"streamId": "string",
"description": "string",
"files": [
{
"fileId": "integer",
"s3Location": {
"bucket": "string",
"key": "string",
"version": "string"
}
}
],
"roleArn": "string"
}
cli-input-json fields
pattern: [a-zA-Z0-9_-]+
length- max:2028
pattern: [^\\p{C}]+
1005
AWS IoT Developer Guide
UpdateStream
length- min:1
length- min:1
Output
{
"streamId": "string",
"streamArn": "string",
"description": "string",
"streamVersion": "integer"
}
pattern: [a-zA-Z0-9_-]+
length- max:2028
pattern: [^\\p{C}]+
Errors
1006
AWS IoT Developer Guide
UpdateThing
InvalidRequestException
UpdateThing
Updates the data for a thing.
Synopsis
cli-input-json format
{
"thingName": "string",
"thingTypeName": "string",
"attributePayload": {
"attributes": {
"string": "string"
},
"merge": "boolean"
},
"expectedVersion": "long",
"removeThingType": "boolean"
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
1007
AWS IoT Developer Guide
UpdateThing
pattern: [a-zA-Z0-9:_-]+
\"attributes\":
{\"name1\":\"value2\"}
\"attributes\":
{\"string1\":
\"string2\"}
Output
None
1008
AWS IoT Developer Guide
UpdateThingGroup
Errors
InvalidRequestException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
UpdateThingGroup
Update a thing group.
Synopsis
cli-input-json format
{
"thingGroupName": "string",
"thingGroupProperties": {
"thingGroupDescription": "string",
"attributePayload": {
"attributes": {
"string": "string"
},
"merge": "boolean"
}
},
"expectedVersion": "long"
}
cli-input-json fields
Name Type Description
1009
AWS IoT Developer Guide
UpdateThingGroup
pattern: [a-zA-Z0-9:_-]+
length- max:2028
pattern: [\\p{Graph} ]*
\"attributes\":
{\"string1\":
\"string2\"}
Output
{
"version": "long"
}
1010
AWS IoT Developer Guide
UpdateThingGroupsForThing
Errors
InvalidRequestException
An exception thrown when the version of a thing passed to a command is different than the version
specified with the --version parameter.
ThrottlingException
UpdateThingGroupsForThing
Updates the groups to which the thing belongs.
Synopsis
cli-input-json format
{
"thingName": "string",
"thingGroupsToAdd": [
"string"
],
"thingGroupsToRemove": [
"string"
],
"overrideDynamicGroups": "boolean"
}
cli-input-json fields
Name Type Description
pattern: [a-zA-Z0-9:_-]+
1011
AWS IoT Developer Guide
UpdateThingShadow
Output
None
Errors
InvalidRequestException
UpdateThingShadow
Updates the shadow for the specified thing.
For more information, see UpdateThingShadow in the AWS IoT Developer Guide.
Synopsis
cli-input-json format
{
"thingName": "string",
"payload": "blob"
}
1012
AWS IoT Developer Guide
UpdateThingShadow
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
Output
{
"payload": "blob"
}
Errors
ConflictException
The specified version does not match the version of the document.
RequestEntityTooLargeException
1013
AWS IoT Developer Guide
ValidateSecurityProfileBehaviors
ValidateSecurityProfileBehaviors
Validates a Device Defender security profile behaviors specification.
Synopsis
cli-input-json format
{
"behaviors": [
{
"name": "string",
"metric": "string",
"criteria": {
"comparisonOperator": "string",
"value": {
"count": "long",
"cidrs": [
"string"
],
"ports": [
"integer"
]
},
"durationSeconds": "integer",
"consecutiveDatapointsToAlarm": "integer",
"consecutiveDatapointsToClear": "integer",
"statisticalThreshold": {
"statistic": "string"
}
}
}
]
}
cli-input-json fields
pattern: [a-zA-Z0-9:_-]+
1014
AWS IoT Developer Guide
ValidateSecurityProfileBehaviors
1015
AWS IoT Developer Guide
ValidateSecurityProfileBehaviors
Output
{
"valid": "boolean",
"validationErrors": [
{
"errorMessage": "string"
}
]
}
1016
AWS IoT Developer Guide
ValidateSecurityProfileBehaviors
Errors
InvalidRequestException
1017