Skip to content

Commit 939c58b

Browse files
authored
Merge pull request #2805 from awsrahulrsr/main
Terraform template for AWS Step Functions workflow to integrate with Amazon Comprehend for sentiment analysis
2 parents a0a62d1 + e30f563 commit 939c58b

File tree

6 files changed

+377
-0
lines changed

6 files changed

+377
-0
lines changed

sfn-comprehend-terraform/README.md

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
# AWS Step Functions integration with Amazon Comprehend using terraform
2+
3+
The AWS Step Functions Express Workflow can be started using the AWS CLI or from another service (e.g. Amazon API Gateway) to run an express workflow and return the result.
4+
5+
The Terraform template deploys an AWS Step Functions Express workflow that invokes Amazon Comprehend and returns the sentiment analysis done by Amazon Comprehend in the response. The Terraform template contains the required resouces with IAM permission to run the application with logging enabled.
6+
7+
Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/sfn-comprehend-terraform
8+
9+
Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.
10+
11+
## Requirements
12+
13+
* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
14+
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
15+
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
16+
* [Terraform](https://learn.hashicorp.com/tutorials/terraform/install-cli) with version 1.x installed
17+
18+
## Deployment Instructions
19+
20+
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
21+
```
22+
git clone https://github.com/aws-samples/serverless-patterns
23+
```
24+
2. Change directory to the pattern directory:
25+
```
26+
cd sfn-comprehend-terraform
27+
```
28+
3. From the command line, use Terraform to deploy the AWS resources for the pattern as specified in the main.tf file:
29+
```
30+
terraform init
31+
terraform apply --auto-approve
32+
```
33+
4. Review the output from the Terraform deployment process to ensure there are no errors.
34+
35+
5. Note the outputs from the Terraform deployment process. These contain the resource names and/or ARNs which are used for testing.
36+
37+
## How it works
38+
39+
* Start the Standard Workflow using the `start-execution` api command with a "message" string in English for sentiment analysis in the input payload.
40+
* The Express Workflow invokes Amazon Comprehend.
41+
* Amazon Comprehend returns the sentiment of the input text.
42+
* If the integration works fine, the sentiment analysis outcome is returned in Step Function execution results within a `output` object
43+
* If the integration fails, the AWS Step Functions workflow will retry up to 5 times before exiting with a `status:FAILED` response.
44+
45+
Please refer to the architecture diagram below:
46+
47+
![End to End Architecture](image/architecture.png)
48+
49+
50+
## Testing
51+
52+
Run the following AWS CLI command to send a 'start-execution' command to start the AWS Step Functions workflow. Note, you must edit the <StateMachineArn> placeholder with the ARN of the deployed AWS Step Functions workflow. This is provided in the stack outputs.
53+
54+
```bash
55+
aws stepfunctions start-execution \
56+
--state-machine-arn <StateMachineArn> \
57+
--input '{"message":"I am very happy today."}'
58+
```
59+
60+
After running the above command, the exection ARN will be displayed as follows -
61+
```bash
62+
{
63+
"executionArn": "arn:aws:states:us-east-1:<AccountId>:execution:StateMachineExpressSyncToComprehend:4d309af8-fb35-4427-aefc-da035954ccc3",
64+
"startDate": "2025-10-15T16:29:41.454000+02:00"
65+
}
66+
```
67+
68+
Run the describe-execution command to view the output from StepFunctions execution
69+
70+
```bash
71+
aws stepfunctions describe-execution --execution-arn arn:aws:states:us-east-1:<AccountId>:execution:StateMachineExpressSyncToComprehend:4d309af8-fb35-4427-aefc-da035954ccc3
72+
```
73+
74+
### Example output:
75+
76+
```bash
77+
{
78+
"executionArn": "arn:aws:states:us-east-1:204524526462:execution:StateMachineExpressSyncToComprehend:4d309af8-fb35-4427-aefc-da035954ccc3",
79+
"stateMachineArn": "arn:aws:states:us-east-1:204524526462:stateMachine:StateMachineExpressSyncToComprehend",
80+
"name": "4d309af8-fb35-4427-aefc-da035954ccc3",
81+
"status": "SUCCEEDED",
82+
"startDate": "2025-10-15T16:29:41.454000+02:00",
83+
"stopDate": "2025-10-15T16:29:41.724000+02:00",
84+
"input": "{\"message\":\"I am very happy today.\"}",
85+
"inputDetails": {
86+
"included": true
87+
},
88+
"output": "{\"message\":\"I am very happy today.\",\"Sentiment\":{\"Sentiment\":\"POSITIVE\",\"SentimentScore\":{\"Mixed\":6.753839E-4,\"Negative\":5.647173E-4,\"Neutral\":0.0011139456,\"Positive\":0.99764603}}}",
89+
"outputDetails": {
90+
"included": true
91+
},
92+
"redriveCount": 0,
93+
"redriveStatus": "NOT_REDRIVABLE",
94+
"redriveStatusReason": "Execution is SUCCEEDED and cannot be redriven"
95+
}
96+
```
97+
## Cleanup
98+
99+
Delete the stack
100+
```bash
101+
terraform destroy --auto-approve
102+
```
103+
104+
----
105+
Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
106+
107+
SPDX-License-Identifier: MIT-0
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
{
2+
"title": "AWS Step Functions integration with Amazon Comprehend using terraform",
3+
"description": "The Terraform template deploys an AWS Step Functions workflow with Amazon Comprehend and returns the sentiment analysis done by Amazon Comprehend.",
4+
"language": "",
5+
"level": "200",
6+
"framework": "Terraform",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"Start the Express Workflow using the start-sync-execution api command with a message string in English for sentiment analysis in the input payload.",
11+
"The Express Workflow invokes Amazon Comprehend.",
12+
"Comprehend returns the sentiment of the input text.",
13+
"If the integration works fine, the sentiment analysis outcome is returned in Step Function execution results within a output object.",
14+
"If the integration fails, the Step Functions workflow will retry up to 5 times before exiting with a status:FAILED response."
15+
]
16+
},
17+
"gitHub": {
18+
"template": {
19+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/sfn-comprehend-terraform",
20+
"templateURL": "serverless-patterns/sfn-comprehend-terraform",
21+
"projectFolder": "sfn-comprehend-terraform",
22+
"templateFile": "main.tf"
23+
}
24+
},
25+
"resources": {
26+
"bullets": [
27+
{
28+
"text": "AWS Step Function - AWS SDK service integrations",
29+
"link": "https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html"
30+
},
31+
{
32+
"text": "AWS Step Function - CloudWatch Logs",
33+
"link": "https://docs.aws.amazon.com/step-functions/latest/dg/cw-logs.html"
34+
},
35+
{
36+
"text": "ComprehendBasicAccessPolicy",
37+
"link": "https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-template-list.html#comprehend-basic-access-policy"
38+
}
39+
]
40+
},
41+
"deploy": {
42+
"text": [
43+
"terraform init",
44+
"terraform apply --auto-approve"
45+
]
46+
},
47+
"testing": {
48+
"text": [
49+
"See the GitHub repo for detailed testing instructions."
50+
]
51+
},
52+
"cleanup": {
53+
"text": [
54+
"terraform destroy --auto-approve"
55+
]
56+
},
57+
"authors": [
58+
{
59+
"name": "Rahul Sringeri",
60+
"image": "",
61+
"bio": "Technical Account Manager at AWS EMEA for Strategic Accounts",
62+
"linkedin": ""
63+
}
64+
]
65+
}
12.8 KB
Loading

sfn-comprehend-terraform/main.tf

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
provider "aws" {
2+
region = "us-east-1" # Change to your preferred region
3+
}
4+
# ---------------------------
5+
# IAM Role for Step Functions
6+
# ---------------------------
7+
resource "aws_iam_role" "states_execution_role" {
8+
name = "StatesExecutionRole"
9+
assume_role_policy = jsonencode({
10+
Version = "2012-10-17",
11+
Statement = [{
12+
Effect = "Allow",
13+
Principal = {
14+
Service = "states.amazonaws.com"
15+
},
16+
Action = "sts:AssumeRole"
17+
}]
18+
})
19+
}
20+
# ---------------------------
21+
# IAM Policies
22+
# ---------------------------
23+
resource "aws_iam_role_policy" "cwlogs" {
24+
name = "CWLogs"
25+
role = aws_iam_role.states_execution_role.id
26+
policy = jsonencode({
27+
Version = "2012-10-17",
28+
Statement = [{
29+
Effect = "Allow",
30+
Action = [
31+
"logs:CreateLogDelivery",
32+
"logs:CreateLogStream",
33+
"logs:GetLogDelivery",
34+
"logs:UpdateLogDelivery",
35+
"logs:DeleteLogDelivery",
36+
"logs:ListLogDeliveries",
37+
"logs:PutLogEvents",
38+
"logs:PutResourcePolicy",
39+
"logs:DescribeResourcePolicies",
40+
"logs:DescribeLogGroups"
41+
],
42+
Resource = "*"
43+
}]
44+
})
45+
}
46+
resource "aws_iam_role_policy" "comprehend_access" {
47+
name = "ComprehendAccess"
48+
role = aws_iam_role.states_execution_role.id
49+
policy = jsonencode({
50+
Version = "2012-10-17",
51+
Statement = [{
52+
Effect = "Allow",
53+
Action = [
54+
"comprehend:BatchDetectKeyPhrases",
55+
"comprehend:DetectDominantLanguage",
56+
"comprehend:DetectEntities",
57+
"comprehend:BatchDetectEntities",
58+
"comprehend:DetectKeyPhrases",
59+
"comprehend:DetectSentiment",
60+
"comprehend:BatchDetectDominantLanguage",
61+
"comprehend:BatchDetectSentiment"
62+
],
63+
Resource = "*"
64+
}]
65+
})
66+
}
67+
# ---------------------------
68+
# CloudWatch Log Group
69+
# ---------------------------
70+
resource "aws_cloudwatch_log_group" "state_machine_logs" {
71+
name = "/stepfunctions/StateMachineExpressSyncToComprehend"
72+
retention_in_days = 14
73+
}
74+
# ---------------------------
75+
# Step Function State Machine
76+
# ---------------------------
77+
resource "aws_sfn_state_machine" "detect_sentiment_state_machine" {
78+
name = "StateMachineExpressSyncToComprehend"
79+
role_arn = aws_iam_role.states_execution_role.arn
80+
type = "STANDARD"
81+
logging_configuration {
82+
level = "ALL"
83+
include_execution_data = false
84+
log_destination = "${aws_cloudwatch_log_group.state_machine_logs.arn}:*"
85+
}
86+
87+
definition = file("${path.module}/statemachine/detectSentiment.asl.json")
88+
}
89+
# ---------------------------
90+
# Output
91+
# ---------------------------
92+
output "state_machine_arn" {
93+
description = "ARN of the Step Function"
94+
value = aws_sfn_state_machine.detect_sentiment_state_machine.arn
95+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
{
2+
"title": "AWS Step Functions integration with Amazon Comprehend using terraform",
3+
"description": "The Terraform template deploys an AWS Step Functions workflow with Amazon Comprehend and returns the sentiment analysis done by Amazon Comprehend.",
4+
"language": "",
5+
"level": "200",
6+
"framework": "Terraform",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"Start the Express Workflow using the start-sync-execution api command with a message string in English for sentiment analysis in the input payload.",
11+
"The Express Workflow invokes Amazon Comprehend.",
12+
"Comprehend returns the sentiment of the input text.",
13+
"If the integration works fine, the sentiment analysis outcome is returned in Step Function execution results within a output object.",
14+
"If the integration fails, the Step Functions workflow will retry up to 5 times before exiting with a status:FAILED response."
15+
]
16+
},
17+
"gitHub": {
18+
"template": {
19+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/sfn-comprehend-terraform",
20+
"templateURL": "serverless-patterns/sfn-comprehend-terraform",
21+
"projectFolder": "sfn-comprehend-terraform",
22+
"templateFile": "main.tf"
23+
}
24+
},
25+
"resources": {
26+
"bullets": [
27+
{
28+
"text": "AWS Step Function - AWS SDK service integrations",
29+
"link": "https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html"
30+
},
31+
{
32+
"text": "AWS Step Function - CloudWatch Logs",
33+
"link": "https://docs.aws.amazon.com/step-functions/latest/dg/cw-logs.html"
34+
},
35+
{
36+
"text": "ComprehendBasicAccessPolicy",
37+
"link": "https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-template-list.html#comprehend-basic-access-policy"
38+
}
39+
]
40+
},
41+
"deploy": {
42+
"text": [
43+
"terraform init",
44+
"terraform apply --auto-approve"
45+
]
46+
},
47+
"testing": {
48+
"text": [
49+
"See the GitHub repo for detailed testing instructions."
50+
]
51+
},
52+
"cleanup": {
53+
"text": [
54+
"terraform destroy --auto-approve"
55+
]
56+
},
57+
"authors": [
58+
{
59+
"name": "Rahul Sringeri",
60+
"image": "",
61+
"bio": "Technical Account Manager at AWS EMEA for Strategic Accounts",
62+
"linkedin": ""
63+
}
64+
],
65+
"patternArch": {
66+
"icon1": {
67+
"x": 20,
68+
"y": 50,
69+
"service": "sfn",
70+
"label": "AWS Step Functions"
71+
},
72+
"icon2": {
73+
"x": 80,
74+
"y": 50,
75+
"service": "comprehend",
76+
"label": "Amazon Comprehend"
77+
},
78+
"line1": {
79+
"from": "icon1",
80+
"to": "icon2",
81+
"label": "Analyze sentiment"
82+
}
83+
}
84+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"Comment": "A Retry example of the Amazon States Language using an AWS Comprehend",
3+
"StartAt": "DetectSentiment",
4+
"States": {
5+
"DetectSentiment": {
6+
"Type": "Task",
7+
"Resource": "arn:aws:states:::aws-sdk:comprehend:detectSentiment",
8+
"ResultPath": "$.Sentiment",
9+
"Parameters": {
10+
"LanguageCode": "en",
11+
"Text.$": "$.message"
12+
},
13+
"Retry": [
14+
{
15+
"ErrorEquals": [
16+
"States.TaskFailed"
17+
],
18+
"IntervalSeconds": 20,
19+
"MaxAttempts": 5,
20+
"BackoffRate": 10
21+
}
22+
],
23+
"End": true
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)