diff --git a/cloud_templates/README.md b/cloud_templates/README.md
new file mode 100644
index 0000000..e69de29
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/.gitignore b/cloud_templates/aws_cdk/TimestreamPattern/.gitignore
new file mode 100644
index 0000000..3037faa
--- /dev/null
+++ b/cloud_templates/aws_cdk/TimestreamPattern/.gitignore
@@ -0,0 +1,9 @@
+*.swp
+__pycache__
+.pytest_cache
+.venv
+*.egg-info
+
+# CDK asset staging directory
+.cdk.staging
+cdk.out
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/README.md b/cloud_templates/aws_cdk/TimestreamPattern/README.md
new file mode 100644
index 0000000..07513f1
--- /dev/null
+++ b/cloud_templates/aws_cdk/TimestreamPattern/README.md
@@ -0,0 +1,102 @@
+
+# Welcome to your CDK project!
+# IoT Data visulaization with Amazon Timestream
+
+The `cdk.json` file tells the CDK Toolkit how to execute your app.
+
+This project is set up like a standard Python project. The initialization
+process also creates a virtualenv within this project, stored under the `.venv`
+directory. To create the virtualenv it assumes that there is a `python3`
+(or `python` for Windows) executable in your path with access to the `venv`
+package. If for any reason the automatic creation of the virtualenv fails,
+you can create the virtualenv manually.
+
+To manually create a virtualenv on MacOS and Linux:
+
+```
+$ python3 -m venv .venv
+```
+
+After the init process completes and the virtualenv is created, you can use the following
+step to activate your virtualenv.
+
+```
+$ source .venv/bin/activate
+```
+
+If you are a Windows platform, you would activate the virtualenv like this:
+
+```
+% .venv\Scripts\activate.bat
+```
+
+Once the virtualenv is activated, you can install the required dependencies.
+
+```
+$ pip install -r requirements.txt
+```
+
+At this point you can now synthesize the CloudFormation template for this code.
+
+```
+$ cdk synth
+```
+
+To add additional dependencies, for example other CDK libraries, just add
+them to your `setup.py` file and rerun the `pip install -r requirements.txt`
+command.
+
+## Useful commands
+
+ * `cdk ls` list all stacks in the app
+ * `cdk synth` emits the synthesized CloudFormation template
+ * `cdk deploy` deploy this stack to your default AWS account/region
+ * `cdk diff` compare deployed stack with current state
+ * `cdk docs` open CDK documentation
+
+## Context parameters
+There are multiple context parameters that you need to set before synthesizing or delpoying this CDK stack. You can specify a context variable either as part of an AWS CDK CLI command, or in `cdk.json`.
+To create a command line context variable, use the __--context (-c) option__, as shown in the following example.
+
+```
+$ cdk cdk synth -c bucket_name=mybucket
+```
+
+To specify the same context variable and value in the cdk.json file, use the following sample code.
+
+```
+{
+ "context": {
+ "bucket_name": "mybucket"
+ }
+}
+```
+
+In this project, these are the following parameters to be set:
+
+* `topic_sql`
+
It is required for IoT Core rule creation to add a simplified SQL syntax to filter messages received on an MQTT topic and push the data elsewhere.
+
__Format__: Enter an SQL statement using the following: ```SELECT FROM WHERE ```. For example: ```SELECT temperature FROM 'iot/topic' WHERE temperature > 50```. To learn more, see AWS IoT SQL Reference.
+
+* `dimensions`
+
Each record contains an array of dimensions (minimum 1). Dimensions represent the metadata attributes of a time series data point. Specify the dimension(s) for your data.
+
__Format__: Must be in a format of a list of strings. For example, for the input ```[device_id]``` the following key-value would be attached to the IoT Core rule:
+
```{dimension's name: device_id, dimension_value: ${device_id}}```
+
+* `timestream_db_name` ``
+
The name of Timestream databse to hold your data.
+
__Format__: Specify a name that is unique for all Timestream databases in your AWS account in the current Region. You can not change this name once you create it. Must be between 3 and 256 characters long. Must contain letters, digits, dashes, periods or underscores.
+
+* `timestream_table_name` ``
+
The name of Timestream databse to hold your data.
+
__Format__: Specify a table name that is unique within its database. You can not change this name once you create it. Must be between 3 and 256 characters long. Must contain letters, digits, dashes, periods or underscores.
+
+* `timestream_iot_rule_name` ``
+
The name of the IoT Core rule that is going to be created.
+
__Format__: Should be an alphanumeric string that can also contain underscore (_) characters, but no spaces.
+
+* `timestream_iot_role_name` ``
+
An IAM role should be created to grant AWS IoT access to your endpoint. This parameter is for setting the name of this role.
+
__Format__: Enter a unique role name that contains alphanumeric characters, hyphens, and underscores. A role name can't contain any spaces.
+
+Enjoy!
\ No newline at end of file
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/app.py b/cloud_templates/aws_cdk/TimestreamPattern/app.py
new file mode 100644
index 0000000..b61e640
--- /dev/null
+++ b/cloud_templates/aws_cdk/TimestreamPattern/app.py
@@ -0,0 +1,27 @@
+import os
+
+import aws_cdk as cdk
+
+from timestream_pattern.timestream_pattern_stack import TimestreamPatternStack
+
+
+app = cdk.App()
+TimestreamPatternStack(app, "TimestreamPatternStack",
+ # If you don't specify 'env', this stack will be environment-agnostic.
+ # Account/Region-dependent features and context lookups will not work,
+ # but a single synthesized template can be deployed anywhere.
+
+ # Uncomment the next line to specialize this stack for the AWS Account
+ # and Region that are implied by the current CLI configuration.
+
+ #env=cdk.Environment(account=os.getenv('CDK_DEFAULT_ACCOUNT'), region=os.getenv('CDK_DEFAULT_REGION')),
+
+ # Uncomment the next line if you know exactly what Account and Region you
+ # want to deploy the stack to. */
+
+ #env=cdk.Environment(account='123456789012', region='us-east-1'),
+
+ # For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html
+ )
+
+app.synth()
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/cdk.json b/cloud_templates/aws_cdk/TimestreamPattern/cdk.json
new file mode 100644
index 0000000..389343b
--- /dev/null
+++ b/cloud_templates/aws_cdk/TimestreamPattern/cdk.json
@@ -0,0 +1,44 @@
+{
+ "app": "python3 app.py",
+ "watch": {
+ "include": [
+ "**"
+ ],
+ "exclude": [
+ "README.md",
+ "cdk*.json",
+ "requirements*.txt",
+ "source.bat",
+ "**/__init__.py",
+ "python/__pycache__",
+ "tests"
+ ]
+ },
+ "context": {
+ "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": true,
+ "@aws-cdk/core:stackRelativeExports": true,
+ "@aws-cdk/aws-rds:lowercaseDbIdentifier": true,
+ "@aws-cdk/aws-lambda:recognizeVersionProps": true,
+ "@aws-cdk/aws-lambda:recognizeLayerVersion": true,
+ "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true,
+ "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
+ "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
+ "@aws-cdk/core:checkSecretUsage": true,
+ "@aws-cdk/aws-iam:minimizePolicies": true,
+ "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
+ "@aws-cdk/core:validateSnapshotRemovalPolicy": true,
+ "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
+ "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
+ "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
+ "@aws-cdk/core:target-partitions": [
+ "aws",
+ "aws-cn"
+ ],
+ "topic_sql": "SELECT * FROM 'Timestream_demo'",
+ "dimensions": ["Location"],
+ "timestream_db_name": "demo_db",
+ "timestream_table_name": "demo_table",
+ "timestream_iot_role_name": "demo_iot_timestream_role",
+ "timestream_iot_rule_name": "demo_to_timetream_rule"
+ }
+}
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/requirements-dev.txt b/cloud_templates/aws_cdk/TimestreamPattern/requirements-dev.txt
new file mode 100644
index 0000000..9270945
--- /dev/null
+++ b/cloud_templates/aws_cdk/TimestreamPattern/requirements-dev.txt
@@ -0,0 +1 @@
+pytest==6.2.5
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/requirements.txt b/cloud_templates/aws_cdk/TimestreamPattern/requirements.txt
new file mode 100644
index 0000000..0822bbe
--- /dev/null
+++ b/cloud_templates/aws_cdk/TimestreamPattern/requirements.txt
@@ -0,0 +1,2 @@
+aws-cdk-lib==2.37.1
+constructs>=10.0.0,<11.0.0
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/source.bat b/cloud_templates/aws_cdk/TimestreamPattern/source.bat
new file mode 100644
index 0000000..9e1a834
--- /dev/null
+++ b/cloud_templates/aws_cdk/TimestreamPattern/source.bat
@@ -0,0 +1,13 @@
+@echo off
+
+rem The sole purpose of this script is to make the command
+rem
+rem source .venv/bin/activate
+rem
+rem (which activates a Python virtualenv on Linux or Mac OS X) work on Windows.
+rem On Windows, this command just runs this batch file (the argument is ignored).
+rem
+rem Now we don't need to document a Windows command for activating a virtualenv.
+
+echo Executing .venv\Scripts\activate.bat for you
+.venv\Scripts\activate.bat
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/tests/__init__.py b/cloud_templates/aws_cdk/TimestreamPattern/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/tests/unit/__init__.py b/cloud_templates/aws_cdk/TimestreamPattern/tests/unit/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/tests/unit/test_timestream_pattern_stack.py b/cloud_templates/aws_cdk/TimestreamPattern/tests/unit/test_timestream_pattern_stack.py
new file mode 100644
index 0000000..51b3aee
--- /dev/null
+++ b/cloud_templates/aws_cdk/TimestreamPattern/tests/unit/test_timestream_pattern_stack.py
@@ -0,0 +1,339 @@
+import aws_cdk as core
+import aws_cdk.assertions as assertions
+from aws_cdk.assertions import Match
+import pytest
+
+from timestream_pattern.timestream_pattern_stack import TimestreamPatternStack
+
+# Setting the context for the app
+app = core.App(context={
+ "topic_sql": "SELECT temperature, pressure, humidity FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+})
+
+stack = TimestreamPatternStack(app, "timestream-pattern")
+template = assertions.Template.from_stack(stack)
+
+# Defining Capture objects for obtaining values in tests
+table_ref = assertions.Capture()
+db_ref = assertions.Capture()
+policy_ref = assertions.Capture()
+role_ref = assertions.Capture()
+
+
+# Testing the resources' creation and properties
+
+def test_timestream_database_creation():
+ template.has_resource("AWS::Timestream::Database", {"DeletionPolicy":"Delete", "UpdateReplacePolicy":"Delete"})
+ template.resource_count_is("AWS::Timestream::Database", 1)
+
+def test_timestream_database_properties():
+ template.has_resource_properties("AWS::Timestream::Database", {
+ "DatabaseName": app.node.try_get_context("timestream_db_name")
+ })
+
+def test_timestream_table_creation():
+ template.has_resource("AWS::Timestream::Table", {"DeletionPolicy":"Delete", "UpdateReplacePolicy":"Delete"})
+ template.resource_count_is("AWS::Timestream::Table", 1)
+
+def test_timestream_table_properties():
+ template.has_resource_properties("AWS::Timestream::Table", {
+ "DatabaseName": app.node.try_get_context("timestream_db_name"),
+ "TableName" : app.node.try_get_context("timestream_table_name"),
+ "RetentionProperties": { "MemoryStoreRetentionPeriodInHours": "24", "MagneticStoreRetentionPeriodInDays": "7"}
+ })
+
+def test_timesream_role_creation():
+ template.has_resource("AWS::IAM::Role", {"DeletionPolicy":"Delete", "UpdateReplacePolicy":"Delete"})
+
+def test_timestream_role_properties():
+ template.has_resource_properties("AWS::IAM::Role", {
+ "AssumeRolePolicyDocument": {"Statement": [{ "Action": "sts:AssumeRole", "Effect": "Allow",
+ "Principal": { "Service": "iot.amazonaws.com"}}], "Version": Match.any_value()}
+ })
+
+def test_timestream_role_policy_properties():
+ template.has_resource_properties("AWS::IAM::Policy", {
+ "PolicyDocument": {
+ "Statement": [
+ {
+ "Action": "timestream:WriteRecords",
+ "Effect": "Allow",
+ "Resource": {
+ "Fn::GetAtt": [
+ table_ref,
+ "Arn"
+ ]
+ }
+ },
+ {
+ "Action": "timestream:DescribeEndpoints",
+ "Effect": "Allow",
+ "Resource": "*"
+ }
+ ],
+ "Version": Match.any_value()
+ },
+ "PolicyName": policy_ref,
+ "Roles": [
+ {
+ "Ref": role_ref
+ }
+ ]
+ })
+
+def test_iot_topic_rule_creation():
+ template.has_resource("AWS::IoT::TopicRule", {"DeletionPolicy":"Delete", "UpdateReplacePolicy":"Delete"})
+ template.resource_count_is("AWS::IoT::TopicRule", 1)
+
+def test_iot_topic_rule_properties():
+ dimesnsion_list = []
+ for d in app.node.try_get_context("dimensions"):
+ dimesnsion_list.append({
+ "Name": d,
+ "Value": "${" + d + "}"
+ })
+ template.has_resource_properties("AWS::IoT::TopicRule", {
+ "TopicRulePayload": {
+ "Actions": [{
+ "Timestream": {
+ "DatabaseName": app.node.try_get_context("timestream_db_name"),
+ "Dimensions": dimesnsion_list,
+ "RoleArn": {
+ "Fn::GetAtt": [
+ role_ref.as_string(),
+ "Arn"
+ ]
+ },
+ "TableName": app.node.try_get_context("timestream_table_name")
+ }
+ }],
+ "Sql": app.node.try_get_context("topic_sql")
+ }
+ })
+
+# Testing dependencies between the resources
+
+def test_timestream_table_dependencies():
+ template.has_resource("AWS::Timestream::Table", {
+ "DependsOn": [
+ db_ref
+ ]
+ })
+
+def test_timestream_role_dependencies():
+ template.has_resource("AWS::IAM::Role", {
+ "DependsOn": [
+ table_ref.as_string()
+ ]
+ })
+
+def test_timestream_policy_dependencies():
+ template.has_resource("AWS::IAM::Policy", {
+ "DependsOn": [
+ table_ref.as_string()
+ ]
+ })
+
+def test_iot_topic_rule_dependencies():
+ template.has_resource("AWS::IoT::TopicRule", {
+ "DependsOn": [
+ db_ref.as_string(),
+ table_ref.as_string(),
+ policy_ref.as_string(),
+ role_ref.as_string()
+ ]
+ })
+
+# Testing input validation process
+
+def test_no_sql():
+ test_app = core.App(context= {
+ "topic_sql": "",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"No sql statemtnt .*"):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+def test_no_dimension():
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"No dimesnsion is provided. *"):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+def test_wrong_dimension():
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": "device_id",
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"The provided input for the dimesnion list is not of type list."):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": [2,"id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"At least one of the provided dimensions is not of type string."):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+def test_wrong_sql():
+ test_app = core.App(context= {
+ "topic_sql": ["SELECT * FROM 'EL-timestream_test'"],
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"The input sql statement does not have a right format. *"):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+def test_wrong_db_name():
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": True,
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"The provided input for Timestream resource name is not of type string."):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"Invalid input length *"):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db!",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"Invalid input pattern *"):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+def test_wrong_table_name():
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": ["cdk_table"],
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"The provided input for Timestream resource name is not of type string."):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "x" * 300,
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"Invalid input length *"):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table@",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"Invalid input pattern *"):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+def test_wrong_topic_rule_name():
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": ["cdk_to_timetream_rule"]
+ })
+ with pytest.raises(Exception, match=r"The provided input for topic rule name is not of type string."):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk_timestream_role",
+ "timestream_iot_rule_name": "cdk_to timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"Invalid input pattern *"):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+def test_wrong_iam_role_name():
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "c" * 65,
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"Invalid input length .*"):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
+
+ test_app = core.App(context= {
+ "topic_sql": "SELECT * FROM 'EL-timestream_test'",
+ "dimensions": ["device_id"],
+ "timestream_db_name": "cdk_db",
+ "timestream_table_name": "cdk_table",
+ "timestream_iot_role_name": "cdk×tream_role",
+ "timestream_iot_rule_name": "cdk_to_timetream_rule"
+ })
+ with pytest.raises(Exception, match=r"Invalid input pattern *"):
+ stack = TimestreamPatternStack(test_app, "timestream-pattern")
+ template = assertions.Template.from_stack(stack)
\ No newline at end of file
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/timestream_pattern/__init__.py b/cloud_templates/aws_cdk/TimestreamPattern/timestream_pattern/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/cloud_templates/aws_cdk/TimestreamPattern/timestream_pattern/timestream_pattern_stack.py b/cloud_templates/aws_cdk/TimestreamPattern/timestream_pattern/timestream_pattern_stack.py
new file mode 100644
index 0000000..765a78a
--- /dev/null
+++ b/cloud_templates/aws_cdk/TimestreamPattern/timestream_pattern/timestream_pattern_stack.py
@@ -0,0 +1,151 @@
+import string
+import sys
+import re
+from aws_cdk import (
+ Stack,
+ aws_timestream as timestream,
+ aws_iot as iot,
+ aws_iam as iam,
+ aws_logs as logs
+)
+from constructs import Construct
+import aws_cdk as cdk
+
+sys.path.append('../')
+from common.inputValidation import *
+
+class TimestreamPatternStack(Stack):
+
+ # Defining class variables
+ dimensions_list = []
+ topic_sql = ""
+ timestream_db_name = ""
+ timestream_table_name = ""
+ timestream_iot_role_name = ""
+ timestream_iot_rule_name = ""
+
+
+ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
+ super().__init__(scope, construct_id, **kwargs)
+
+ # Getting the context parameters
+
+ # Required parameters for users to set in the CLI command or cdk.json
+ self.dimensions_list = self.node.try_get_context("dimensions")
+ self.topic_sql = self.node.try_get_context("topic_sql")
+
+ # Optional parameters for users to set in the CLI command or cdk.json
+ self.timestream_db_name = self.node.try_get_context("timestream_db_name")
+ self.timestream_table_name = self.node.try_get_context("timestream_table_name")
+ self.timestream_iot_role_name = self.node.try_get_context("timestream_iot_role_name")
+ self.timestream_iot_rule_name = self.node.try_get_context("timestream_iot_rule_name")
+
+ # Perform input validation
+ self.performInputValidation()
+
+ # Creating the timestream database
+ timestream_database = timestream.CfnDatabase(self, self.timestream_db_name, database_name=self.timestream_db_name)
+ timestream_database.apply_removal_policy(policy=cdk.RemovalPolicy.DESTROY)
+
+ # Creating the timestream table under the database previously made
+ timestream_table = timestream.CfnTable(self, self.timestream_table_name, database_name=self.timestream_db_name,
+ retention_properties={"MemoryStoreRetentionPeriodInHours": "24", "MagneticStoreRetentionPeriodInDays": "7"}, table_name=self.timestream_table_name)
+ timestream_table.node.add_dependency(timestream_database)
+ timestream_table.apply_removal_policy(policy=cdk.RemovalPolicy.DESTROY)
+
+ # Creating the role for the IoT-Timestream rule
+ iot_timestream_role = iam.Role(self, self.timestream_iot_role_name, assumed_by=iam.ServicePrincipal("iot.amazonaws.com"))
+ iot_timestream_role.add_to_policy(iam.PolicyStatement(effect=iam.Effect.ALLOW, resources=[timestream_table.attr_arn], actions=["timestream:WriteRecords"]))
+ iot_timestream_role.add_to_policy(iam.PolicyStatement(effect=iam.Effect.ALLOW, resources=["*"], actions=["timestream:DescribeEndpoints"]))
+ iot_timestream_role.node.add_dependency(timestream_table)
+ iot_timestream_role.apply_removal_policy(policy=cdk.RemovalPolicy.DESTROY)
+
+ # Creating the dimension list based on the user input
+ dimensions = [iot.CfnTopicRule.TimestreamDimensionProperty(name = dim, value = "${" + dim + "}") for dim in self.dimensions_list]
+
+ # Creating a cloudwatch log group for topic rule's error action
+ log_group = logs.LogGroup(self, "iot_to_timestream_log_group" , log_group_name="iot_to_timestream_log_group", removal_policy=cdk.RemovalPolicy.DESTROY)
+
+ iot_to_cloudwatch_logs_role = iam.Role(self, "iot_to_log_group_role", assumed_by=iam.ServicePrincipal("iot.amazonaws.com"))
+ iot_to_cloudwatch_logs_role.add_to_policy(iam.PolicyStatement(
+ effect=iam.Effect.ALLOW, resources=[log_group.log_group_arn],
+ actions=["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", "logs:PutMetricFilter", "logs:PutRetentionPolicy"]))
+ iot_to_cloudwatch_logs_role.node.add_dependency(log_group)
+ iot_to_cloudwatch_logs_role.apply_removal_policy(policy=cdk.RemovalPolicy.DESTROY)
+
+ # Creating the IoT Topic Rule
+ topic_rule = iot.CfnTopicRule(self, self.timestream_iot_rule_name, topic_rule_payload=iot.CfnTopicRule.TopicRulePayloadProperty(
+ actions=[iot.CfnTopicRule.ActionProperty(timestream=iot.CfnTopicRule.TimestreamActionProperty(
+ database_name=self.timestream_db_name,
+ dimensions=dimensions,
+ role_arn=iot_timestream_role.role_arn,
+ table_name=self.timestream_table_name
+ ))],
+ sql=self.topic_sql,
+ error_action= iot.CfnTopicRule.ActionProperty(
+ cloudwatch_logs=iot.CfnTopicRule.CloudwatchLogsActionProperty(
+ log_group_name=log_group.log_group_name,
+ role_arn=iot_to_cloudwatch_logs_role.role_arn
+ )
+ )))
+ topic_rule.node.add_dependency(timestream_database)
+ topic_rule.node.add_dependency(iot_timestream_role)
+ topic_rule.node.add_dependency(timestream_table)
+ topic_rule.apply_removal_policy(policy=cdk.RemovalPolicy.DESTROY)
+
+
+ def performInputValidation(self):
+ self.validateSql(self.topic_sql)
+ self.validateDimensionList(self.dimensions_list)
+ if not self.timestream_db_name:
+ self.timestream_db_name = "DemoTimestreamDB"
+ else:
+ self.validateTimestreamResourceName(self.timestream_db_name)
+ if not self.timestream_table_name:
+ self.timestream_db_name = "DemoTimestreamTable"
+ else:
+ self.validateTimestreamResourceName(self.timestream_table_name)
+ self.validateIoTtoTimestreamRoleName(self.timestream_iot_role_name)
+ self.validateIoTTpoicRuleName(self.timestream_iot_rule_name)
+
+ def validateSql(self, sqlStatement):
+ if not sqlStatement:
+ raise NoSQL
+ elif type(sqlStatement) != str:
+ raise WrongFormattedInput("The input sql statement does not have a right format. Please refer to README.md for more information.")
+ return
+
+ def validateTimestreamResourceName(self, inputStr):
+ if type(inputStr) != str:
+ raise WrongFormattedInput("The provided input for Timestream resource name is not of type string.")
+ else:
+ checkInputLength(self, 3, 256, inputStr, "Timestream resource")
+ checkInputPattern(self, r'^[a-zA-Z0-9-_\.]+$' , inputStr, "Timestream resource")
+
+ def validateIoTTpoicRuleName(self, inputStr):
+ if not inputStr:
+ self.timestream_iot_rule_name = "DemoIoTtoTimestreamRule"
+ elif type(inputStr) != str:
+ raise WrongFormattedInput("The provided input for topic rule name is not of type string.")
+ else:
+ checkInputPattern(self, r'^[a-zA-Z0-9_]+$' , inputStr, "IoT rule")
+
+ def validateIoTtoTimestreamRoleName(self, inputStr):
+ if not inputStr:
+ self.timestream_iot_role_name = "DemoIoTtoTimestreamRole"
+ elif type(inputStr) != str:
+ raise WrongFormattedInput("The provided input for the IAM role name is not of type string")
+ else:
+ checkInputLength(self, 1, 64, inputStr, "IAM role")
+ checkInputPattern(self, r'^[a-zA-Z0-9+=,@-_\.]+$' , inputStr, "IAM role")
+
+ def validateDimensionList(self, dimensinList):
+ if not dimensinList:
+ raise NoTimestreamDimension
+ elif type(dimensinList) != list:
+ raise WrongFormattedInput("The provided input for the dimesnion list is not of type list.")
+ else:
+ for d in dimensinList:
+ if type(d) != str:
+ raise WrongFormattedInput("At least one of the provided dimensions is not of type string.")
+ return
\ No newline at end of file
diff --git a/cloud_templates/demo/demo_templates/timestream_pattern.json b/cloud_templates/demo/demo_templates/timestream_pattern.json
new file mode 100644
index 0000000..51798fa
--- /dev/null
+++ b/cloud_templates/demo/demo_templates/timestream_pattern.json
@@ -0,0 +1,462 @@
+{
+ "Resources": {
+ "demodb": {
+ "Type": "AWS::Timestream::Database",
+ "Properties": {
+ "DatabaseName": "demo_db"
+ },
+ "UpdateReplacePolicy": "Delete",
+ "DeletionPolicy": "Delete",
+ "Metadata": {
+ "aws:cdk:path": "TimestreamPatternStack/demo_db"
+ }
+ },
+ "demotable": {
+ "Type": "AWS::Timestream::Table",
+ "Properties": {
+ "DatabaseName": "demo_db",
+ "RetentionProperties": {
+ "MemoryStoreRetentionPeriodInHours": "24",
+ "MagneticStoreRetentionPeriodInDays": "7"
+ },
+ "TableName": "demo_table"
+ },
+ "DependsOn": [
+ "demodb"
+ ],
+ "UpdateReplacePolicy": "Delete",
+ "DeletionPolicy": "Delete",
+ "Metadata": {
+ "aws:cdk:path": "TimestreamPatternStack/demo_table"
+ }
+ },
+ "demoiottimestreamrole59095436": {
+ "Type": "AWS::IAM::Role",
+ "Properties": {
+ "AssumeRolePolicyDocument": {
+ "Statement": [
+ {
+ "Action": "sts:AssumeRole",
+ "Effect": "Allow",
+ "Principal": {
+ "Service": "iot.amazonaws.com"
+ }
+ }
+ ],
+ "Version": "2012-10-17"
+ }
+ },
+ "DependsOn": [
+ "demotable"
+ ],
+ "UpdateReplacePolicy": "Delete",
+ "DeletionPolicy": "Delete",
+ "Metadata": {
+ "aws:cdk:path": "TimestreamPatternStack/demo_iot_timestream_role/Resource"
+ }
+ },
+ "demoiottimestreamroleDefaultPolicy6B3D586D": {
+ "Type": "AWS::IAM::Policy",
+ "Properties": {
+ "PolicyDocument": {
+ "Statement": [
+ {
+ "Action": "timestream:WriteRecords",
+ "Effect": "Allow",
+ "Resource": {
+ "Fn::GetAtt": [
+ "demotable",
+ "Arn"
+ ]
+ }
+ },
+ {
+ "Action": "timestream:DescribeEndpoints",
+ "Effect": "Allow",
+ "Resource": "*"
+ }
+ ],
+ "Version": "2012-10-17"
+ },
+ "PolicyName": "demoiottimestreamroleDefaultPolicy6B3D586D",
+ "Roles": [
+ {
+ "Ref": "demoiottimestreamrole59095436"
+ }
+ ]
+ },
+ "DependsOn": [
+ "demotable"
+ ],
+ "Metadata": {
+ "aws:cdk:path": "TimestreamPatternStack/demo_iot_timestream_role/DefaultPolicy/Resource"
+ }
+ },
+ "iottotimestreamloggroup28D0FCAA": {
+ "Type": "AWS::Logs::LogGroup",
+ "Properties": {
+ "LogGroupName": "iot_to_timestream_log_group",
+ "RetentionInDays": 731
+ },
+ "UpdateReplacePolicy": "Delete",
+ "DeletionPolicy": "Delete",
+ "Metadata": {
+ "aws:cdk:path": "TimestreamPatternStack/iot_to_timestream_log_group/Resource"
+ }
+ },
+ "iottologgrouproleBE9DD4DE": {
+ "Type": "AWS::IAM::Role",
+ "Properties": {
+ "AssumeRolePolicyDocument": {
+ "Statement": [
+ {
+ "Action": "sts:AssumeRole",
+ "Effect": "Allow",
+ "Principal": {
+ "Service": "iot.amazonaws.com"
+ }
+ }
+ ],
+ "Version": "2012-10-17"
+ }
+ },
+ "DependsOn": [
+ "iottotimestreamloggroup28D0FCAA"
+ ],
+ "UpdateReplacePolicy": "Delete",
+ "DeletionPolicy": "Delete",
+ "Metadata": {
+ "aws:cdk:path": "TimestreamPatternStack/iot_to_log_group_role/Resource"
+ }
+ },
+ "iottologgrouproleDefaultPolicyFAF3C98E": {
+ "Type": "AWS::IAM::Policy",
+ "Properties": {
+ "PolicyDocument": {
+ "Statement": [
+ {
+ "Action": [
+ "logs:CreateLogGroup",
+ "logs:CreateLogStream",
+ "logs:PutLogEvents",
+ "logs:PutMetricFilter",
+ "logs:PutRetentionPolicy"
+ ],
+ "Effect": "Allow",
+ "Resource": {
+ "Fn::GetAtt": [
+ "iottotimestreamloggroup28D0FCAA",
+ "Arn"
+ ]
+ }
+ }
+ ],
+ "Version": "2012-10-17"
+ },
+ "PolicyName": "iottologgrouproleDefaultPolicyFAF3C98E",
+ "Roles": [
+ {
+ "Ref": "iottologgrouproleBE9DD4DE"
+ }
+ ]
+ },
+ "DependsOn": [
+ "iottotimestreamloggroup28D0FCAA"
+ ],
+ "Metadata": {
+ "aws:cdk:path": "TimestreamPatternStack/iot_to_log_group_role/DefaultPolicy/Resource"
+ }
+ },
+ "demototimetreamrule": {
+ "Type": "AWS::IoT::TopicRule",
+ "Properties": {
+ "TopicRulePayload": {
+ "Actions": [
+ {
+ "Timestream": {
+ "DatabaseName": "demo_db",
+ "Dimensions": [
+ {
+ "Name": "Location",
+ "Value": "${Location}"
+ }
+ ],
+ "RoleArn": {
+ "Fn::GetAtt": [
+ "demoiottimestreamrole59095436",
+ "Arn"
+ ]
+ },
+ "TableName": "demo_table"
+ }
+ }
+ ],
+ "ErrorAction": {
+ "CloudwatchLogs": {
+ "LogGroupName": {
+ "Ref": "iottotimestreamloggroup28D0FCAA"
+ },
+ "RoleArn": {
+ "Fn::GetAtt": [
+ "iottologgrouproleBE9DD4DE",
+ "Arn"
+ ]
+ }
+ }
+ },
+ "Sql": "SELECT * FROM 'Timestream_demo'"
+ }
+ },
+ "DependsOn": [
+ "demodb",
+ "demoiottimestreamroleDefaultPolicy6B3D586D",
+ "demoiottimestreamrole59095436",
+ "demotable"
+ ],
+ "UpdateReplacePolicy": "Delete",
+ "DeletionPolicy": "Delete",
+ "Metadata": {
+ "aws:cdk:path": "TimestreamPatternStack/demo_to_timetream_rule"
+ }
+ },
+ "CDKMetadata": {
+ "Type": "AWS::CDK::Metadata",
+ "Properties": {
+ "Analytics": "v2:deflate64:H4sIAAAAAAAA/zWOwQ6CMBBEv4V7WVEOfgAmXjwQ9G5KqbhSuqTdxpCGf5dCPM3sTPZlTlCWUGTy63PVDbnBFuKdpRrEGj0j46g9Oy1HiNXLXiTLVnotVv+QrdGLwFQ1ZLZs05oMqjmdu1uEod5DvFF/dRSm1Pz9+k8MiUYTqiYkYuJoT8GpjVmR7ZCR7CLqmd9kDyWc4VhkH4+Yu2DTRmh2/QGC7DCgzwAAAA=="
+ },
+ "Metadata": {
+ "aws:cdk:path": "TimestreamPatternStack/CDKMetadata/Default"
+ },
+ "Condition": "CDKMetadataAvailable"
+ }
+ },
+ "Conditions": {
+ "CDKMetadataAvailable": {
+ "Fn::Or": [
+ {
+ "Fn::Or": [
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "af-south-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "ap-east-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "ap-northeast-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "ap-northeast-2"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "ap-south-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "ap-southeast-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "ap-southeast-2"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "ca-central-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "cn-north-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "cn-northwest-1"
+ ]
+ }
+ ]
+ },
+ {
+ "Fn::Or": [
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "eu-central-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "eu-north-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "eu-south-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "eu-west-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "eu-west-2"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "eu-west-3"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "me-south-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "sa-east-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "us-east-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "us-east-2"
+ ]
+ }
+ ]
+ },
+ {
+ "Fn::Or": [
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "us-west-1"
+ ]
+ },
+ {
+ "Fn::Equals": [
+ {
+ "Ref": "AWS::Region"
+ },
+ "us-west-2"
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ },
+ "Parameters": {
+ "BootstrapVersion": {
+ "Type": "AWS::SSM::Parameter::Value",
+ "Default": "/cdk-bootstrap/hnb659fds/version",
+ "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]"
+ }
+ },
+ "Rules": {
+ "CheckBootstrapVersion": {
+ "Assertions": [
+ {
+ "Assert": {
+ "Fn::Not": [
+ {
+ "Fn::Contains": [
+ [
+ "1",
+ "2",
+ "3",
+ "4",
+ "5"
+ ],
+ {
+ "Ref": "BootstrapVersion"
+ }
+ ]
+ }
+ ]
+ },
+ "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI."
+ }
+ ]
+ }
+ }
+}
+
diff --git a/cloud_templates/user_guides/timestream_guide.md b/cloud_templates/user_guides/timestream_guide.md
new file mode 100644
index 0000000..770e82a
--- /dev/null
+++ b/cloud_templates/user_guides/timestream_guide.md
@@ -0,0 +1,208 @@
+# Getting started with Timestream template guide
+
+## Setting up and prerequisites
+
+### AWS Account
+
+If you don't already have an AWS account follow the [Setup Your Environment](https://aws.amazon.com/getting-started/guides/setup-environment/) getting started guide for a quick overview.
+
+### AWS CloudFormation
+
+Before you start using AWS CloudFormation, you might need to know what IAM permissions you need, how to start logging AWS CloudFormation API calls, or what endpoints to use. Refer to this [guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/settingup.html) to get started using AWS CloudFormation.
+
+### AWS CDK
+
+**Note**: If you are just going to use the sample demo template you can skip this section.
+
+The AWS Cloud Development Kit (CDK) is an open source software development framework that lets you define your cloud infrastructure as code in one of its supported programming languages. It is intended for moderately to highly experienced AWS users. Refer to this [guide](https://aws.amazon.com/getting-started/guides/setup-cdk/?pg=gs&sec=gtkaws) to get started with AWS CDK.
+
+## Template deployment and CloudFormation stack creation
+
+A template is a JSON or YAML text file that contains the configuration information about the AWS resources you want to create in the [stack](https://docs.aws.amazon.com/cdk/v2/guide/stacks.html). To learn more about how to work with CloudFormation templates refer to [Working with templates](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html) guide.
+
+You can either use the provided demo template and deploy it directly to the console or customize the template’s resources before deployment using AWS CDK. Based on your decision follow the respective section below.
+
+### Sample demo template
+
+By using the sample json template that is provided under the `demo_templates` directory, you do not need to take any further actions except creating the stack by uploading it. You only need to make sure that your IoT device sends a similar payload as below one connected to the cloud:
+
+`{`
+`"Location = ",`
+`your other key-value pairs `
+`}`
+
+For simplicity’s sake, a sample code is provided that you can run on your device to send data to IoT Core. It is an example of multiple devices sending their weather measurements. You can follow the guide under `demo_templates` to learn about how to get the sample code working. However, if you already have your own set up, you can simply work with your own program but make sure to send a json payload similar to what is mentioned above and you should be good to continue with the demo.
+
+Follow the steps below to create the CloudFormation stack using the sample template file.
+
+1. Sign in to the AWS Management Console and open the [AWS CloudFormation console.](https://console.aws.amazon.com/cloudformation)
+2. If this is a new CloudFormation account, choose **Create New Stack**. Otherwise, choose **Create Stack** and then select **with new resources**.
+3. In the **Template** section, select **Upload a template file** and upload the json template file. Choose **Next**.
+4. In the **Specify Details** section, enter a stack name in the **Name** field.
+5. If you want you can add tags to your stack. Otherwise choose **Next**.
+6. Review the stack’s settings and then choose **Create.**
+7. At this point, you will find the status of your stack to be `CREATE_IN_PROGRESS`. Your stack might take several minutes to get created. See next sections to learn about monitoring your stack creation.
+
+### Custom template
+
+If you are interested in using the CloudFormation templates more than just for demo purposes, you need to customize the stack’s resources based on your specific use-case. Follow the steps below to do so:
+
+1. Make sure that you already [set up your AWS CDK](https://aws.amazon.com/getting-started/guides/setup-cdk/?pg=gs&sec=gtkaws) environment.
+2. Starting in your current directory, change your directory and go to `aws_cdk/TimestreamPattern` directory.
+3. Just to verify everything is working correctly, list the stacks in your app by running `cdk ls` command. If you don't see `TimestreamPatternStack`, make sure you are currently in `TimestreamPattern` directory.
+4. The structure of the files inside `TimestreamPattern` is as below:
+
+[Image: Screen Shot 2022-08-24 at 4.40.39 PM.png]
+* `timestream_pattern_stack.py` is the main code of the stack. It is here where the required resources are created.
+* `tests/unit/test_timestream_pattern_stack.py` is where the unit tests of the stack is written. The unit tests check
+ * Right creation of the resources in addition to their properties
+ * Dependencies between the resources
+ * Right error handlings in case of input violations
+* `cdk.json` tells the CDK Toolkit how to execute your app. Context values are key-value pairs that can be associated with an app, stack, or construct. You can add the context key-values to this file or in command line before synthesizing the template.
+* `README.md` is where you can find the detailed instructions on how to get started with the code including: how to synthesize the template, a set of useful commands, stack’s context parameters, and details about the code.
+* `cdk.out` is where the synthesized template (in a json format) will be located in.
+
+1. Run `source .venv/bin/activate` to activate the app's Python virtual environment.
+2. Run `python -m pip install -r requirements.txt` and `python -m pip install -r requirements.txt` to install the dependencies.
+3. Go through the `README.md` file to learn about the context parameters that need to be set by you prior to deployment.
+4. Set the context parameter values either by changing `cdk.json` file or by using the command line.
+ 1. To create a command line context variable, use the **`--context (-c) option`**, as shown in the following example: `$ cdk cdk synth -c bucket_name=mybucket`
+ 2. To specify the same context variable and value in the `cdk.json` file, use the following code.`
+ { "context": { "bucket_name": "mybucket" }`
+5. Run `cdk synth` to emit the synthesized CloudFormation template.
+6. Run `python -m pytest` to run the unit tests. It is the best practice to run the tests before deploying your template to the cloud.
+7. Run `cdk deploy` to deploy the stack to your default AWS account/region.
+8. Refer to the** *Stack management*** section below.
+
+## Stack management
+
+### Viewing CloudFormation stack data and resources
+
+After deployment, you may need to monitor your created stack and its resources. To do this your starting point should be AWS CloudFormation console.
+
+1. Sign in to the AWS Management Console and open the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation).
+2. Choose **Stacks** tab to view all the available stacks in your account.
+3. Find the stack that you just created and click on it.
+4. To verify that the stack’s creation is done successfully, check if its status is `CREATE_COMPLETE`. To learn more about what each status means refer to [stack status codes](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-view-stack-data-resources.html#cfn-console-view-stack-data-resources-status-codes).
+5. You can view the stack’s general information such as ID, status, policy, rollback configuration, etc under the **Stack info** tab.
+6. If you click on the **Events** tab, each major step in the creation of the stack sorted by the time of each event is displayed.
+7. You can also find the resources that are part of the stack under the **Resources** tab.
+
+There is more information on viewing your CloudFormation stack information [here](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-view-stack-data-resources.html#cfn-console-view-stack-data-resources-view-info).
+
+### Monitoring the generated resources
+
+If you deploy and create the stack successfully, the following resources must get created under your stack. You can verify their creation by checking the **Resources** tab in your stack as mentioned above.
+
+|Resourse |Type |
+|--- |--- |
+|CDKMetadata |[AWS::CDK::Metadata](https://docs.aws.amazon.com/cdk/api/v1/docs/constructs.ConstructMetadata.html) |
+|Timestream database |[AWS::Timestream::Database](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-timestream-database.html) |
+|Timestream table |[AWS::Timestream::Table](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-timestream-table.html) |
+|IAM role and policy that grant IoT access to Timestream |[AWS::IAM::Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html) [AWS::IAM::Policy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html) |
+|IoT Rule |[AWS::IoT::TopicRule](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-topicrule.html) |
+|CloudWatch log group to capture error logs |[AWS::Logs::LogGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html) |
+|IAM role and policy that grant IoT access to CloudWatch |[AWS::IAM::Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html) [AWS::IAM::Policy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html) |
+
+### Handling stack failures
+
+If CloudFormation fails to create, update, or delete your stack, you will be able to go through the logs or error messages to learn more about the issue. There are some general methods for troubleshooting a CloudFormation issue. For example, you can follow the steps below to find the issue manually in the console.
+
+* Check the status of your stack in the [CloudFormation console](https://console.aws.amazon.com/cloudformation/).
+* From the **Events** tab, you can see a set of events while the last operation was being done on your stack.
+* Find the failure event from the set of events and then check the status reason of that event. The status reason usually gives a good understanding of the issue that caused the failure.
+
+
+In case of failures in stack creations or updates, CloudFormation automatically performs a rollback. However, you can also [add rollback triggers during stack creation or updating](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-rollback-triggers.html#using-cfn-rollback-triggers-create) to further monitor the state of your application. By setting up the rollback triggers if the application breaches the threshold of the alarms you've specified, it will roll back to that operation.
+
+Finally, this [troubleshooting guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#basic-ts-guide) is a helpful resource to refer if there is an issue in your stack.
+
+### Estimating the cost of the stack
+
+There is no additional charge for AWS CloudFormation. You pay for AWS resources created using CloudFormation as if you created them by hand. Refer to this [guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-paying.html) to learn more about the stack cost estimation functionality.
+
+## Ingesting and visualizing your IoT data with the constructed resources
+
+### Sending data to the cloud from your device
+
+Now that your stack and all the required resources are created and available, you can start by connecting your device to the cloud and sending your data to the cloud.
+
+* If you are new to AWS IoT Core, this [guide](https://docs.aws.amazon.com/iot/latest/developerguide/connect-to-iot.html) is a great starting point to connect your device to the cloud.
+* After connecting your device to IoT Core, you can use the [MQTT test client](https://docs.aws.amazon.com/iot/latest/developerguide/view-mqtt-messages.html) to monitor the MQTT messages being passed in your AWS account.
+* Move to the **Rules** tab under **Message Routing** section in the [AWS IoT console](https://console.aws.amazon.com/iot/home). There you can verify the creation of the newly created topic rule and its [timestream rule action](https://docs.aws.amazon.com/iot/latest/developerguide/timestream-rule-action.html) which writes data received from your device to the Timestream database.
+
+### Query data in the Timestream service console
+
+In the previous section, you verified that your device is connected to the cloud and is sending data to IoT Core. To view your data in the Timestream table, follow these steps:
+
+* Open the [AWS Timestream Console](https://console.aws.amazon.com/timestream).
+* From the navigation pane, choose **Databases.**
+* Find the database that was just created by your stack and select it.
+* Choose **Tables** and find the table that was created by your stack and select it.
+* Select **Actions** and select **Query table**.
+* In the query editor, run a query. For instance, to see the latest 10 rows in the table, run:
+ * `SELECT * FROM . ORDER BY time DESC LIMIT 10`
+
+* Now you can see the result of your query in a table format.
+* If you cannot see any data in the query editor, follow these steps:
+ * First make sure that your device is connected to the cloud and is sending data by using the [MQTT test client](https://docs.aws.amazon.com/iot/latest/developerguide/view-mqtt-messages.html). More details about this are provided in the previous section.
+ * If your data is getting landed in IoT Core but Timestream is not receiving it, there might be an error happening while the IoT rule attempts to send data from IoT Core to Timestream. To find out about the issue, you can use the CloudWatch log group that was created by the template earlier. To do so, open the [Cloudwatch console](https://console.aws.amazon.com/cloudwatch). From the navigation bar, select **Log > Log Groups**. Find the log group name that was created by the stack earlier and select it. Now you can view the error logs to find out the issue.
+
+### Integrating with dashboards to visualize data
+
+In the previous section, you were able to see your device’s data in a table format under the Timestream’s table query editor. You can take a further step to visualize your data and create dashboards. Here are several possible Timestream integrations with reporting dashboards :
+
+#### Amazon QuickSight
+
+AWS IoT Analytics provides direct integration with [Amazon QuickSight](https://aws.amazon.com/quicksight/). Amazon QuickSight is a fast business analytics service you can use to build visualizations, perform ad-hoc analysis, and quickly get business insights from your data. Amazon QuickSight is available in [these regions](https://docs.aws.amazon.com/general/latest/gr/quicksight.html).
+
+To connect Amazon Timestream to QuickSight you need to follow these steps:
+
+1. Navigate to the AWS QuickSight console.
+2. If you have never used AWS QuickSight before, you will be asked to sign up. In this case, choose **Standard** tier and the correct region as your setup.
+3. During the sign up phase, give QuickSight access to your Amazon Timestream.
+4. If you already have an account, give Amazon QuickSight access your Timestream by choosing **Admin >** **Manage QuickSight > Security & permissions.** Under QuickSight access to AWS services, choose **Add or remove**, then select the check box next to AWS IoT Analytics and choose **Update**.
+5. From the admin Amazon QuickSight console page choose **New Analysis** and **New data set.**
+6. Choose Timestream as the source and enter a name for your data source.
+7. Choose your Timestream database and table to import, and then choose **Create data source**.
+8. After your data source is created, you can start making visualizations in Amazon QuickSight.
+
+You can follow this [guide](https://docs.aws.amazon.com/timestream/latest/developerguide/Quicksight.html) for a more detailed explanation of the above steps. Additionally, you can refer to this [video tutorial](https://youtu.be/TzW4HWl-L8s) to make QuickSight work with Timestream.
+
+#### Grafana
+
+1. If you have not already, install Grafana following [these instructions](https://grafana.com/docs/grafana/latest/setup-grafana/installation/).
+2. Grafana has default and custom configuration files. You can configure Grafana as explained [here](https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/).
+3. Restart and sign in to Grafana following this [guide](https://grafana.com/docs/grafana/latest/setup-grafana/restart-grafana/).
+4. After signing into Grafana, in the side menu under the Configuration link, click on **Data Sources.**
+5. Click** Add data source** button.
+6. Select **Timestream** in the Time series databases section.
+
+You can follow this [guide](https://grafana.com/grafana/plugins/grafana-timestream-datasource/) for more information on how to integrate Timestream with Grafana. Additionally, you can refer to this [video tutorial](https://www.youtube.com/watch?v=pilkz645cs4) to connect Timestream to Grafana.
+
+#### Amazon Managed Grafana
+
+With Amazon Managed Grafana, you can add Amazon Timestream as a data source by using the AWS data source configuration option in the Grafana workspace console. To get started refer to [Setting up](https://docs.aws.amazon.com/grafana/latest/userguide/Amazon-Managed-Grafana-setting-up.html) to set up your amazon Managed Grafana and then you can follow this [guide](https://docs.aws.amazon.com/grafana/latest/userguide/timestream-datasource.html) to connect Timestream to your Amazon Managed Grafana. Additionally, you can refer to [Using Amazon Managed Grafana to query and visualize data from Amazon Timestream](https://youtu.be/4oMbsLY28vc) video tutorial to connect Timestream to Amazon Managed Grafana.
+
+## Cleaning up the stack
+
+To clean-up all the resources used in this demo, all you need to do is to delete the initial CloudFormation stack. To delete a stack and its resources, follow these steps:
+
+1. Open the [AWS CloudFormation console](https://console.aws.amazon.com/cloudformation/).
+2. On the Stacks menu in the CloudFormation console, select the stack that you want to delete. (Note that the stack must be currently running.)
+3. In the stack details pane, choose **Delete**.
+4. Confirm deleting stack when prompted.
+
+After the stack is deleted, its status will be `DELETE_COMPLETE`. Stacks in the `DELETE_COMPLETE` state aren't displayed in the CloudFormation console by default. However, you can follow the instructions in [Viewing deleted stacks on the AWS CloudFormation console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-view-deleted-stacks.html) to be able to view them.
+
+Finally, if the stack deletion failed, the stack will be in the `DELETE_FAILED` state. For solutions, see the [Delete stack fails](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-delete-stack-fails) troubleshooting topic. In this case, make sure to refer to the **Monitoring the generated resources** section of this document to verify that all the resources got deleted successfully.
+
+## Useful resources
+
+* [CloudFormation User Guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/index.html)
+* [Timestream User Guide](https://docs.aws.amazon.com/timestream/latest/developerguide/index.html)
+* [IoT Core User Guide](https://docs.aws.amazon.com/iot/latest/developerguide/index.html)
+* [AWS CDK (v2) User Guide](https://docs.aws.amazon.com/cdk/v2/guide/index.html)
+* [Amazon Managed Grafana User Guide](https://docs.aws.amazon.com/grafana/latest/userguide/index.html)
+
+