Skip to content

Instantly share code, notes, and snippets.

@mikebroberts
Created April 28, 2022 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikebroberts/d0263ffd3b081b224840f2fea4af59c4 to your computer and use it in GitHub Desktop.
Save mikebroberts/d0263ffd3b081b224840f2fea4af59c4 to your computer and use it in GitHub Desktop.
Scheduled Step Function that calls a Lambda function, with backoff retry, in CDK
#!/usr/bin/env node
import 'source-map-support/register';
import {App, Duration, Stack, StackProps} from 'aws-cdk-lib';
import {Construct} from 'constructs';
import {Code, Function, Runtime} from "aws-cdk-lib/aws-lambda";
import {StateMachine} from "aws-cdk-lib/aws-stepfunctions";
import {LambdaInvoke} from "aws-cdk-lib/aws-stepfunctions-tasks";
import {Rule, RuleTargetInput, Schedule} from "aws-cdk-lib/aws-events";
import {SfnStateMachine} from "aws-cdk-lib/aws-events-targets";
class ScheduledStepFunctionStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const callLambdaState = new LambdaInvoke(this, 'CallLambda', {
// !! CHANGE YOUR LAMBDA DETAILS HERE !!
lambdaFunction: new Function(this, 'HelloWorldFunction', {
handler: 'lambda.handler',
code: Code.fromAsset('dist/api.zip'),
runtime: Runtime.NODEJS_14_X
}),
});
// !! CHANGE YOUR RETRY DETAILS HERE !!
callLambdaState.addRetry({
maxAttempts: 3,
interval: Duration.seconds(2),
backoffRate: 2
})
const stateMachine = new StateMachine(this, 'StateMachine', {
definition: callLambdaState
})
new Rule(this, 'rule', {
// !! CHANGE THIS TO A CRON EXPRESSION, OR CHANGE SCHEDULE !!
schedule: Schedule.rate(Duration.minutes(1)),
targets: [
new SfnStateMachine(stateMachine, {
input: RuleTargetInput.fromObject({foo: 'bar'}),
})
]
})
}
}
const app = new App();
new ScheduledStepFunctionStack(app, 'ScheduledStepFunction', {
env: {account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment