Skip to content

Instantly share code, notes, and snippets.

@pablorcruh
Created May 10, 2023 02:09
Show Gist options
  • Save pablorcruh/00c2e6fa7e27d194c1120e32d9e2a35a to your computer and use it in GitHub Desktop.
Save pablorcruh/00c2e6fa7e27d194c1120e32d9e2a35a to your computer and use it in GitHub Desktop.
To create an SNS notification after a Step Function execution using AWS CDK in TypeScript, you can follow these steps:
Import the necessary AWS CDK libraries:
typescript
import * as cdk from 'aws-cdk-lib';
import * as sns from 'aws-cdk-lib/aws-sns';
import * as subs from 'aws-cdk-lib/aws-sns-subscriptions';
import * as stepfunctions from 'aws-cdk-lib/aws-stepfunctions';
import * as targets from 'aws-cdk-lib/aws-events-targets';
Define the SNS topic and the subscription:
typescript
const topic = new sns.Topic(this, 'MyTopic', {
displayName: 'My Topic'
});
const emailSubscription = new subs.EmailSubscription('[email protected]');
topic.addSubscription(emailSubscription);
This code creates an SNS topic and subscribes an email address to it. Replace '[email protected]' with the email address you want to receive the notification.
Define the Step Function:
typescript
const myStateMachine = new stepfunctions.StateMachine(this, 'MyStateMachine', {
definition: myStateMachineDefinition
});
Replace myStateMachineDefinition with the definition of your Step Function.
Add a CloudWatch Events rule to trigger the SNS notification:
typescript
const rule = new cdk.aws_events.Rule(this, 'MyRule', {
eventPattern: {
source: ['aws.states'],
detailType: ['Step Functions Execution Status Change'],
detail: {
status: ['SUCCEEDED']
}
}
});
rule.addTarget(new targets.SnsTopic(topic));
This code creates a CloudWatch Events rule that triggers the SNS topic when the Step Function execution succeeds. You can modify the eventPattern object to specify other conditions for triggering the SNS notification, such as failure or completion.
Deploy the stack:
shell
cdk deploy
This will create the SNS topic, the Step Function, and the CloudWatch Events rule.
After deploying the stack, you will receive an email notification when the Step Function execution succeeds.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment