Skip to content

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions sfn-comprehend-terraform/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# AWS Step Functions Express Workflow to Amazon Comprehend for Sentiment Analysis

The Step Functions Express Workflow can be started using the AWS CLI or from another service (e.g. API Gateway) to run an express workflow and return the result.

The Terraform template deploys a Step Functions Express workflow that invokes Amazon Comprehend and returns the sentiment analysis done by 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 SAM deployment process. These contain the resource names and/or ARNs which are used for testing.

## How it works

* 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.

Please refer to the architecture diagram below:

![End to End Architecture](image/architecture.png)


## Testing

Run the following AWS CLI command to send a 'start-sync-execution` comand to start the Step Functions workflow. Note, you must edit the {StateMachineExpressSyncToComprehend} placeholder with the ARN of the deployed Step Functions workflow. This is provided in the stack outputs.

```bash
aws stepfunctions start-sync-execution --name "test" --state-machine-arn "{StateMachineExpressSyncToComprehend}" --input "{\"message\":\"I am very happy today.\"}"
```

### Example output:

```bash
{
"executionArn": "arn:aws:states:us-east-1:796495736600:express:StateMachineExpressSyncToComprehend-cqmUxRLjlvq7:test:8b75495d-cb96-4933-ac25-1f908050e33d",
"stateMachineArn": "arn:aws:states:us-east-1:796495736600:stateMachine:StateMachineExpressSyncToComprehend-cqmUxRLjlvq7",
"name": "test",
"startDate": "2023-10-08T07:35:55.257000+05:30",
"stopDate": "2023-10-08T07:35:55.358000+05:30",
"status": "SUCCEEDED",
"input": "{\"message\":\"I am very happy today.\"}",
"inputDetails": {
"included": true
},
"output": "{\"message\":\"I am very happy today.\",\"Sentiment\":{\"Sentiment\":\"POSITIVE\",\"SentimentScore\":{\"Mixed\":1.4907288E-4,\"Negative\":1.3237515E-4,\"Neutral\":3.8026855E-4,\"Positive\":0.9993383}}}",
"outputDetails": {
"included": true
},
"billingDetails": {
"billedMemoryUsedInMB": 64,
"billedDurationInMilliseconds": 200
}
}
```
## 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
65 changes: 65 additions & 0 deletions sfn-comprehend-terraform/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"title": "AWS Step Functions Express Workflow to Amazon Comprehend for Sentiment Analysis",
"description": "The Terraform template deploys a Step Functions Express workflow that invokes Amazon Comprehend and returns the sentiment analysis done by Comprehend in the response. The SAM template contains the required resouces with IAM permission to run the application with logging enabled.",
"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": "sfn-comprehend-terraform/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": ""
}
]
}
Binary file added sfn-comprehend-terraform/image/architecture.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
98 changes: 98 additions & 0 deletions sfn-comprehend-terraform/main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
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.${var.aws_region}.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 = "*"
}]
})
}
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 = "*"
}]
})
}
# ---------------------------
# 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 = "EXPRESS"
logging_configuration {
level = "ALL"
include_execution_data = false
destinations {
cloudwatch_logs_log_group {
log_group_arn = aws_cloudwatch_log_group.state_machine_logs.arn
}
}
}
definition = file("${path.module}/detectSentiment.asl.json")
}
# ---------------------------
# Output
# ---------------------------
output "state_machine_arn" {
description = "ARN of the Step Function"
value = aws_sfn_state_machine.detect_sentiment_state_machine.arn
}
26 changes: 26 additions & 0 deletions sfn-comprehend-terraform/statemachine/detectSentiment.asl.json
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
}
}
}