-
Notifications
You must be signed in to change notification settings - Fork 1k
Terraform template for AWS Step Functions workflow to integrate with Amazon Comprehend for sentiment analysis #2805
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
09a2efa
70172ed
4928ebc
66e4edb
b6f5be7
21b9165
e30f563
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
# AWS Step Functions integration with Amazon Comprehend using terraform | ||
|
||
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. | ||
|
||
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. | ||
|
||
Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/sfn-comprehend-terraform | ||
|
||
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. | ||
|
||
## Requirements | ||
|
||
* [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. | ||
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured | ||
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) | ||
* [Terraform](https://learn.hashicorp.com/tutorials/terraform/install-cli) with version 1.x installed | ||
|
||
## Deployment Instructions | ||
|
||
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: | ||
``` | ||
git clone https://github.com/aws-samples/serverless-patterns | ||
``` | ||
2. Change directory to the pattern directory: | ||
``` | ||
cd sfn-comprehend-terraform | ||
``` | ||
3. From the command line, use Terraform to deploy the AWS resources for the pattern as specified in the main.tf file: | ||
``` | ||
terraform init | ||
terraform apply --auto-approve | ||
``` | ||
4. Review the output from the Terraform deployment process to ensure there are no errors. | ||
|
||
5. Note the outputs from the Terraform deployment process. These contain the resource names and/or ARNs which are used for testing. | ||
|
||
## How it works | ||
|
||
* Start the Standard Workflow using the `start-execution` api command with a "message" string in English for sentiment analysis in the input payload. | ||
* The Express Workflow invokes Amazon Comprehend. | ||
* Amazon Comprehend returns the sentiment of the input text. | ||
* If the integration works fine, the sentiment analysis outcome is returned in Step Function execution results within a `output` object | ||
* If the integration fails, the AWS Step Functions workflow will retry up to 5 times before exiting with a `status:FAILED` response. | ||
|
||
Please refer to the architecture diagram below: | ||
|
||
 | ||
|
||
|
||
## Testing | ||
|
||
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. | ||
|
||
```bash | ||
aws stepfunctions start-execution \ | ||
--state-machine-arn <StateMachineArn> \ | ||
--input '{"message":"I am very happy today."}' | ||
``` | ||
|
||
After running the above command, the exection ARN will be displayed as follows - | ||
```bash | ||
{ | ||
"executionArn": "arn:aws:states:us-east-1:<AccountId>:execution:StateMachineExpressSyncToComprehend:4d309af8-fb35-4427-aefc-da035954ccc3", | ||
"startDate": "2025-10-15T16:29:41.454000+02:00" | ||
} | ||
``` | ||
|
||
Run the describe-execution command to view the output from StepFunctions execution | ||
|
||
```bash | ||
aws stepfunctions describe-execution --execution-arn arn:aws:states:us-east-1:<AccountId>:execution:StateMachineExpressSyncToComprehend:4d309af8-fb35-4427-aefc-da035954ccc3 | ||
``` | ||
|
||
### Example output: | ||
|
||
```bash | ||
{ | ||
"executionArn": "arn:aws:states:us-east-1:204524526462:execution:StateMachineExpressSyncToComprehend:4d309af8-fb35-4427-aefc-da035954ccc3", | ||
"stateMachineArn": "arn:aws:states:us-east-1:204524526462:stateMachine:StateMachineExpressSyncToComprehend", | ||
"name": "4d309af8-fb35-4427-aefc-da035954ccc3", | ||
"status": "SUCCEEDED", | ||
"startDate": "2025-10-15T16:29:41.454000+02:00", | ||
"stopDate": "2025-10-15T16:29:41.724000+02:00", | ||
"input": "{\"message\":\"I am very happy today.\"}", | ||
"inputDetails": { | ||
"included": true | ||
}, | ||
"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}}}", | ||
"outputDetails": { | ||
"included": true | ||
}, | ||
"redriveCount": 0, | ||
"redriveStatus": "NOT_REDRIVABLE", | ||
"redriveStatusReason": "Execution is SUCCEEDED and cannot be redriven" | ||
} | ||
``` | ||
## Cleanup | ||
|
||
Delete the stack | ||
```bash | ||
terraform destroy --auto-approve | ||
``` | ||
|
||
---- | ||
Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
||
SPDX-License-Identifier: MIT-0 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
{ | ||
"title": "AWS Step Functions integration with Amazon Comprehend using terraform", | ||
"description": "The Terraform template deploys an AWS Step Functions workflow with Amazon Comprehend and returns the sentiment analysis done by Amazon Comprehend.", | ||
"language": "", | ||
"level": "200", | ||
"framework": "Terraform", | ||
"introBox": { | ||
"headline": "How it works", | ||
"text": [ | ||
"Start the Express Workflow using the start-sync-execution api command with a message string in English for sentiment analysis in the input payload.", | ||
"The Express Workflow invokes Amazon Comprehend.", | ||
"Comprehend returns the sentiment of the input text.", | ||
"If the integration works fine, the sentiment analysis outcome is returned in Step Function execution results within a output object.", | ||
"If the integration fails, the Step Functions workflow will retry up to 5 times before exiting with a status:FAILED response." | ||
] | ||
}, | ||
"gitHub": { | ||
"template": { | ||
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/sfn-comprehend-terraform", | ||
"templateURL": "serverless-patterns/sfn-comprehend-terraform", | ||
"projectFolder": "sfn-comprehend-terraform", | ||
"templateFile": "main.tf" | ||
} | ||
}, | ||
"resources": { | ||
"bullets": [ | ||
{ | ||
"text": "AWS Step Function - AWS SDK service integrations", | ||
"link": "https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html" | ||
}, | ||
{ | ||
"text": "AWS Step Function - CloudWatch Logs", | ||
"link": "https://docs.aws.amazon.com/step-functions/latest/dg/cw-logs.html" | ||
}, | ||
{ | ||
"text": "ComprehendBasicAccessPolicy", | ||
"link": "https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-template-list.html#comprehend-basic-access-policy" | ||
} | ||
] | ||
}, | ||
"deploy": { | ||
"text": [ | ||
"terraform init", | ||
"terraform apply --auto-approve" | ||
] | ||
}, | ||
"testing": { | ||
"text": [ | ||
"See the GitHub repo for detailed testing instructions." | ||
] | ||
}, | ||
"cleanup": { | ||
"text": [ | ||
"terraform destroy --auto-approve" | ||
] | ||
}, | ||
"authors": [ | ||
{ | ||
"name": "Rahul Sringeri", | ||
"image": "", | ||
"bio": "Technical Account Manager at AWS EMEA for Strategic Accounts", | ||
"linkedin": "" | ||
} | ||
] | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
provider "aws" { | ||
region = "us-east-1" # Change to your preferred region | ||
} | ||
# --------------------------- | ||
# IAM Role for Step Functions | ||
# --------------------------- | ||
resource "aws_iam_role" "states_execution_role" { | ||
name = "StatesExecutionRole" | ||
assume_role_policy = jsonencode({ | ||
Version = "2012-10-17", | ||
Statement = [{ | ||
Effect = "Allow", | ||
Principal = { | ||
Service = "states.amazonaws.com" | ||
}, | ||
Action = "sts:AssumeRole" | ||
}] | ||
}) | ||
} | ||
# --------------------------- | ||
# IAM Policies | ||
# --------------------------- | ||
resource "aws_iam_role_policy" "cwlogs" { | ||
name = "CWLogs" | ||
role = aws_iam_role.states_execution_role.id | ||
policy = jsonencode({ | ||
Version = "2012-10-17", | ||
Statement = [{ | ||
Effect = "Allow", | ||
Action = [ | ||
"logs:CreateLogDelivery", | ||
"logs:CreateLogStream", | ||
"logs:GetLogDelivery", | ||
"logs:UpdateLogDelivery", | ||
"logs:DeleteLogDelivery", | ||
"logs:ListLogDeliveries", | ||
"logs:PutLogEvents", | ||
"logs:PutResourcePolicy", | ||
"logs:DescribeResourcePolicies", | ||
"logs:DescribeLogGroups" | ||
], | ||
Resource = "*" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can this be more restrictive than providing access to all resources ("*")? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As per this documentation we need to use "*". I tried to restrict it but terraform --apply fails with access denied to log group error. |
||
}] | ||
}) | ||
} | ||
resource "aws_iam_role_policy" "comprehend_access" { | ||
name = "ComprehendAccess" | ||
role = aws_iam_role.states_execution_role.id | ||
policy = jsonencode({ | ||
Version = "2012-10-17", | ||
Statement = [{ | ||
Effect = "Allow", | ||
Action = [ | ||
"comprehend:BatchDetectKeyPhrases", | ||
"comprehend:DetectDominantLanguage", | ||
"comprehend:DetectEntities", | ||
"comprehend:BatchDetectEntities", | ||
"comprehend:DetectKeyPhrases", | ||
"comprehend:DetectSentiment", | ||
"comprehend:BatchDetectDominantLanguage", | ||
"comprehend:BatchDetectSentiment" | ||
], | ||
Resource = "*" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can this be more restrictive than providing access to all resources ("*")? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here the calls like Detect sentiment, Detect Entities cannot be resource level ARN's.. hence I've used "*" |
||
}] | ||
}) | ||
} | ||
# --------------------------- | ||
# CloudWatch Log Group | ||
# --------------------------- | ||
resource "aws_cloudwatch_log_group" "state_machine_logs" { | ||
name = "/stepfunctions/StateMachineExpressSyncToComprehend" | ||
retention_in_days = 14 | ||
} | ||
# --------------------------- | ||
# Step Function State Machine | ||
# --------------------------- | ||
resource "aws_sfn_state_machine" "detect_sentiment_state_machine" { | ||
name = "StateMachineExpressSyncToComprehend" | ||
role_arn = aws_iam_role.states_execution_role.arn | ||
type = "STANDARD" | ||
logging_configuration { | ||
level = "ALL" | ||
include_execution_data = false | ||
log_destination = "${aws_cloudwatch_log_group.state_machine_logs.arn}:*" | ||
} | ||
|
||
definition = file("${path.module}/statemachine/detectSentiment.asl.json") | ||
} | ||
# --------------------------- | ||
# Output | ||
# --------------------------- | ||
output "state_machine_arn" { | ||
description = "ARN of the Step Function" | ||
value = aws_sfn_state_machine.detect_sentiment_state_machine.arn | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
{ | ||
"title": "AWS Step Functions integration with Amazon Comprehend using terraform", | ||
"description": "The Terraform template deploys an AWS Step Functions workflow with Amazon Comprehend and returns the sentiment analysis done by Amazon Comprehend.", | ||
"language": "", | ||
"level": "200", | ||
"framework": "Terraform", | ||
"introBox": { | ||
"headline": "How it works", | ||
"text": [ | ||
"Start the Express Workflow using the start-sync-execution api command with a message string in English for sentiment analysis in the input payload.", | ||
"The Express Workflow invokes Amazon Comprehend.", | ||
"Comprehend returns the sentiment of the input text.", | ||
"If the integration works fine, the sentiment analysis outcome is returned in Step Function execution results within a output object.", | ||
"If the integration fails, the Step Functions workflow will retry up to 5 times before exiting with a status:FAILED response." | ||
] | ||
}, | ||
"gitHub": { | ||
"template": { | ||
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/sfn-comprehend-terraform", | ||
"templateURL": "serverless-patterns/sfn-comprehend-terraform", | ||
"projectFolder": "sfn-comprehend-terraform", | ||
"templateFile": "main.tf" | ||
} | ||
}, | ||
"resources": { | ||
"bullets": [ | ||
{ | ||
"text": "AWS Step Function - AWS SDK service integrations", | ||
"link": "https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html" | ||
}, | ||
{ | ||
"text": "AWS Step Function - CloudWatch Logs", | ||
"link": "https://docs.aws.amazon.com/step-functions/latest/dg/cw-logs.html" | ||
}, | ||
{ | ||
"text": "ComprehendBasicAccessPolicy", | ||
"link": "https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-template-list.html#comprehend-basic-access-policy" | ||
} | ||
] | ||
}, | ||
"deploy": { | ||
"text": [ | ||
"terraform init", | ||
"terraform apply --auto-approve" | ||
] | ||
}, | ||
"testing": { | ||
"text": [ | ||
"See the GitHub repo for detailed testing instructions." | ||
] | ||
}, | ||
"cleanup": { | ||
"text": [ | ||
"terraform destroy --auto-approve" | ||
] | ||
}, | ||
"authors": [ | ||
{ | ||
"name": "Rahul Sringeri", | ||
"image": "", | ||
"bio": "Technical Account Manager at AWS EMEA for Strategic Accounts", | ||
"linkedin": "" | ||
} | ||
], | ||
"patternArch": { | ||
"icon1": { | ||
"x": 20, | ||
"y": 50, | ||
"service": "sfn", | ||
"label": "AWS Step Functions" | ||
}, | ||
"icon2": { | ||
"x": 80, | ||
"y": 50, | ||
"service": "comprehend", | ||
"label": "Amazon Comprehend" | ||
}, | ||
"line1": { | ||
"from": "icon1", | ||
"to": "icon2", | ||
"label": "Analyze sentiment" | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
{ | ||
"Comment": "A Retry example of the Amazon States Language using an AWS Comprehend", | ||
"StartAt": "DetectSentiment", | ||
"States": { | ||
"DetectSentiment": { | ||
"Type": "Task", | ||
"Resource": "arn:aws:states:::aws-sdk:comprehend:detectSentiment", | ||
"ResultPath": "$.Sentiment", | ||
"Parameters": { | ||
"LanguageCode": "en", | ||
"Text.$": "$.message" | ||
}, | ||
"Retry": [ | ||
{ | ||
"ErrorEquals": [ | ||
"States.TaskFailed" | ||
], | ||
"IntervalSeconds": 20, | ||
"MaxAttempts": 5, | ||
"BackoffRate": 10 | ||
} | ||
], | ||
"End": true | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I got this error when running apply command.
│ Error: Reference to undeclared input variable
│
│ on main.tf line 14, in resource "aws_iam_role" "states_execution_role":
│ 14: Service = "states.${var.aws_region}.amazonaws.com"
│
│ An input variable with the name "aws_region" has not been declared. This variable can be declared with a variable
│ "aws_region" {} block.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed